You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ConfigFile.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*
  2. * Copyright (c) 2006-2017 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  5. * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
  6. * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
  7. * permit persons to whom the Software is furnished to do so, subject to the following conditions:
  8. *
  9. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
  10. * Software.
  11. *
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  13. * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
  14. * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  15. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  16. */
  17. package com.dmdirc.util.io;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.nio.charset.Charset;
  21. import java.nio.file.Path;
  22. import java.util.ArrayList;
  23. import java.util.Collection;
  24. import java.util.Collections;
  25. import java.util.GregorianCalendar;
  26. import java.util.HashMap;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.stream.Collectors;
  30. /**
  31. * Reads and writes a standard DMDirc config file.
  32. */
  33. public class ConfigFile extends TextFile {
  34. /** A list of domains in this config file. */
  35. private final Collection<String> domains = new ArrayList<>();
  36. /** The values associated with each flat domain. */
  37. private final Map<String, List<String>> flatdomains = new HashMap<>();
  38. /** The key/value sets associated with each key domain. */
  39. private final Map<String, Map<String, String>> keydomains = new HashMap<>();
  40. /** Whether or not we should automatically create domains. */
  41. private boolean automake;
  42. /**
  43. * Creates a new read-only Config File from the specified input stream.
  44. *
  45. * @param is The input stream to read
  46. */
  47. public ConfigFile(final InputStream is) {
  48. super(is, Charset.forName("UTF-8"));
  49. }
  50. /**
  51. * Creates a new config file from the specified path.
  52. *
  53. * @param path The path to read/write.
  54. */
  55. public ConfigFile(final Path path) {
  56. super(path, Charset.forName("UTF-8"));
  57. }
  58. /**
  59. * Sets the "automake" value of this config file. If automake is set to
  60. * true, any calls to getKeyDomain will automatically create the domain
  61. * if it did not previously exist.
  62. *
  63. * @param automake The new value of the automake setting of this file
  64. */
  65. public void setAutomake(final boolean automake) {
  66. this.automake = automake;
  67. }
  68. /**
  69. * Reads the data from the file.
  70. *
  71. * @throws IOException if an i/o exception occurred when reading
  72. * @throws InvalidConfigFileException if the config file isn't valid
  73. */
  74. public void read() throws IOException, InvalidConfigFileException {
  75. keydomains.clear();
  76. flatdomains.clear();
  77. domains.clear();
  78. readLines();
  79. String domain = null;
  80. boolean keydomain = false;
  81. for (String line : getLines()) {
  82. String tline = line;
  83. while (!tline.isEmpty() && (tline.charAt(0) == '\t'
  84. || tline.charAt(0) == ' ')) {
  85. tline = tline.substring(1);
  86. }
  87. if (tline.indexOf('#') == 0 || tline.isEmpty()) {
  88. continue;
  89. }
  90. final int offset;
  91. if (tline.endsWith(":") && !tline.endsWith("\\:") && findEquals(tline) == -1) {
  92. domain = unescape(tline.substring(0, tline.length() - 1));
  93. domains.add(domain);
  94. keydomain = keydomains.containsKey(domain)
  95. || hasFlatDomainValue("keysections", domain);
  96. if (keydomain && !keydomains.containsKey(domain)) {
  97. keydomains.put(domain, new HashMap<>());
  98. } else if (!keydomain && !flatdomains.containsKey(domain)) {
  99. flatdomains.put(domain, new ArrayList<>());
  100. }
  101. } else if (domain != null && keydomain
  102. && (offset = findEquals(tline)) != -1) {
  103. final String key = unescape(tline.substring(0, offset));
  104. final String value = unescape(tline.substring(offset + 1));
  105. keydomains.get(domain).put(key, value);
  106. } else if (domain != null && !keydomain) {
  107. addFlatDomainValue(domain, unescape(tline));
  108. } else {
  109. throw new InvalidConfigFileException("Unknown or unexpected"
  110. + " line encountered: " + tline);
  111. }
  112. }
  113. }
  114. /**
  115. * Writes the contents of this ConfigFile to disk.
  116. *
  117. * @throws IOException if the write operation fails
  118. */
  119. public void write() throws IOException {
  120. if (!isWritable()) {
  121. throw new UnsupportedOperationException("Cannot write to a file "
  122. + "that isn't writable");
  123. }
  124. final Collection<String> lines = new ArrayList<>();
  125. lines.add("# This is a DMDirc configuration file.");
  126. lines.add("# Written on: " + new GregorianCalendar().getTime());
  127. writeMeta(lines);
  128. for (String domain : domains) {
  129. if ("keysections".equals(domain)) {
  130. continue;
  131. }
  132. lines.add("");
  133. lines.add(escape(domain) + ':');
  134. if (flatdomains.containsKey(domain)) {
  135. lines.addAll(flatdomains.get(domain).stream()
  136. .map(entry -> " " + escape(entry))
  137. .collect(Collectors.toList()));
  138. } else {
  139. lines.addAll(keydomains.get(domain).entrySet().stream()
  140. .map(entry -> " " + escape(entry.getKey()) + '=' + escape(entry.getValue()))
  141. .collect(Collectors.toList()));
  142. }
  143. }
  144. writeLines(lines);
  145. }
  146. /**
  147. * Appends the meta-data (keysections) to the specified list of lines.
  148. *
  149. * @param lines The set of lines to be appended to
  150. */
  151. private void writeMeta(final Collection<String> lines) {
  152. lines.add("");
  153. lines.add("# This section indicates which sections below take "
  154. + "key/value");
  155. lines.add("# pairs, rather than a simple list. It should be "
  156. + "placed above");
  157. lines.add("# any sections that take key/values.");
  158. lines.add("keysections:");
  159. lines.addAll(domains.stream()
  160. .filter(domain -> !"keysections".equals(domain) && keydomains.containsKey(domain))
  161. .map(domain -> " " + domain)
  162. .collect(Collectors.toList()));
  163. }
  164. /**
  165. * Retrieves all the key domains for this config file.
  166. *
  167. * @return This config file's key domains
  168. */
  169. public Map<String, Map<String, String>> getKeyDomains() {
  170. return Collections.unmodifiableMap(keydomains);
  171. }
  172. /**
  173. * Retrieves the key/values of the specified key domain.
  174. *
  175. * @param domain The domain to be retrieved
  176. * @return A map of keys to values in the specified domain
  177. */
  178. public Map<String, String> getKeyDomain(final String domain) {
  179. if (automake && !isKeyDomain(domain)) {
  180. domains.add(domain);
  181. keydomains.put(domain, new HashMap<>());
  182. }
  183. return keydomains.get(domain);
  184. }
  185. /**
  186. * Retrieves the content of the specified flat domain.
  187. *
  188. * @param domain The domain to be retrieved
  189. * @return A list of lines in the specified domain
  190. */
  191. public List<String> getFlatDomain(final String domain) {
  192. return flatdomains.get(domain);
  193. }
  194. /**
  195. * Determines if this config file has the specified domain.
  196. *
  197. * @param domain The domain to check for
  198. * @return True if the domain is known, false otherwise
  199. */
  200. public boolean hasDomain(final String domain) {
  201. return keydomains.containsKey(domain)
  202. || flatdomains.containsKey(domain);
  203. }
  204. /**
  205. * Determines if this config file has the specified domain, and the domain
  206. * is a key domain.
  207. *
  208. * @param domain The domain to check for
  209. * @return True if the domain is known and keyed, false otherwise
  210. */
  211. public boolean isKeyDomain(final String domain) {
  212. return keydomains.containsKey(domain);
  213. }
  214. /**
  215. * Determines if this config file has the specified domain, and the domain
  216. * is a flat domain.
  217. *
  218. * @param domain The domain to check for
  219. * @return True if the domain is known and flat, false otherwise
  220. */
  221. public boolean isFlatDomain(final String domain) {
  222. return flatdomains.containsKey(domain);
  223. }
  224. /**
  225. * Adds a new key domain to this config file.
  226. *
  227. * @param name The name of the domain to be added
  228. * @param data The content of the domain
  229. */
  230. public void addDomain(final String name, final Map<String, String> data) {
  231. domains.add(name);
  232. keydomains.put(name, data);
  233. }
  234. private boolean hasFlatDomainValue(final String domain, final String value) {
  235. return flatdomains.containsKey(domain) && flatdomains.get(domain).contains(value);
  236. }
  237. private void addFlatDomainValue(final String domain, final String value) {
  238. if (!flatdomains.containsKey(domain)) {
  239. flatdomains.put(domain, new ArrayList<>());
  240. }
  241. flatdomains.get(domain).add(value);
  242. }
  243. /**
  244. * Unescapes any escaped characters in the specified input string.
  245. *
  246. * @param input The string to unescape
  247. * @return The string with all escape chars (\) resolved
  248. */
  249. protected static String unescape(final CharSequence input) {
  250. boolean escaped = false;
  251. final StringBuilder temp = new StringBuilder();
  252. for (int i = 0; i < input.length(); i++) {
  253. final char ch = input.charAt(i);
  254. if (escaped) {
  255. if (ch == 'n') {
  256. temp.append('\n');
  257. } else if (ch == 'r') {
  258. temp.append('\r');
  259. } else {
  260. temp.append(ch);
  261. }
  262. escaped = false;
  263. } else if (ch == '\\') {
  264. escaped = true;
  265. } else {
  266. temp.append(ch);
  267. }
  268. }
  269. return temp.toString();
  270. }
  271. /**
  272. * Escapes the specified input string by prefixing all occurances of
  273. * \, \n, \r, =, # and : with backslashes.
  274. *
  275. * @param input The string to be escaped
  276. * @return A backslash-armoured version of the string
  277. */
  278. protected static String escape(final String input) {
  279. return input.replace("\\", "\\\\").replace("\n", "\\n")
  280. .replace("\r", "\\r").replace("=", "\\=")
  281. .replace(":", "\\:").replace("#", "\\#");
  282. }
  283. /**
  284. * Finds the first non-escaped instance of '=' in the specified string.
  285. *
  286. * @param input The string to be searched
  287. * @return The offset of the first non-escaped instance of '=', or -1.
  288. */
  289. private static int findEquals(final CharSequence input) {
  290. boolean escaped = false;
  291. for (int i = 0; i < input.length(); i++) {
  292. if (escaped) {
  293. escaped = false;
  294. } else if (input.charAt(i) == '\\') {
  295. escaped = true;
  296. } else if (input.charAt(i) == '=') {
  297. return i;
  298. }
  299. }
  300. return -1;
  301. }
  302. }