選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ConfigFile.java 12KB

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