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

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