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

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