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

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