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

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