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

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