Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ConfigFile.java 12KB

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