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