Properties.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. /* Properties.java -- a set of persistent properties
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  15. 02111-1307 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util;
  32. import java.io.IOException;
  33. import java.io.InputStream;
  34. import java.io.BufferedReader;
  35. import java.io.InputStreamReader;
  36. import java.io.OutputStream;
  37. import java.io.PrintWriter;
  38. import java.io.PrintStream;
  39. import java.io.OutputStreamWriter;
  40. /**
  41. * A set of persistent properties, which can be saved or loaded from a stream.
  42. * A property list may also contain defaults, searched if the main list
  43. * does not contain a property for a given key.
  44. *
  45. * An example of a properties file for the german language is given
  46. * here. This extends the example given in ListResourceBundle.
  47. * Create a file MyResource_de.properties with the following contents
  48. * and put it in the CLASSPATH. (The character
  49. * <code>\</code><code>u00e4</code> is the german &auml;)
  50. *
  51. *
  52. <pre>s1=3
  53. s2=MeineDisk
  54. s3=3. M\<code></code>u00e4rz 96
  55. s4=Die Diskette ''{1}'' enth\<code></code>u00e4lt {0} in {2}.
  56. s5=0
  57. s6=keine Dateien
  58. s7=1
  59. s8=eine Datei
  60. s9=2
  61. s10={0,number} Dateien
  62. s11=Das Formatieren schlug fehl mit folgender Exception: {0}
  63. s12=FEHLER
  64. s13=Ergebnis
  65. s14=Dialog
  66. s15=Auswahlkriterium
  67. s16=1,3</pre>
  68. *
  69. * <p>Although this is a sub class of a hash table, you should never
  70. * insert anything other than strings to this property, or several
  71. * methods, that need string keys and values, will fail. To ensure
  72. * this, you should use the <code>get/setProperty</code> method instead
  73. * of <code>get/put</code>.
  74. *
  75. * Properties are saved in ISO 8859-1 encoding, using Unicode escapes with
  76. * a single <code>u</code> for any character which cannot be represented.
  77. *
  78. * @author Jochen Hoenicke
  79. * @author Eric Blake <ebb9@email.byu.edu>
  80. * @see PropertyResourceBundle
  81. * @status updated to 1.4
  82. */
  83. public class Properties extends Hashtable
  84. {
  85. // WARNING: Properties is a CORE class in the bootstrap cycle. See the
  86. // comments in vm/reference/java/lang/Runtime for implications of this fact.
  87. /**
  88. * The property list that contains default values for any keys not
  89. * in this property list.
  90. *
  91. * @serial the default properties
  92. */
  93. protected Properties defaults;
  94. /**
  95. * Compatible with JDK 1.0+.
  96. */
  97. private static final long serialVersionUID = 4112578634029874840L;
  98. /**
  99. * Creates a new empty property list with no default values.
  100. */
  101. public Properties()
  102. {
  103. }
  104. /**
  105. * Create a new empty property list with the specified default values.
  106. *
  107. * @param defaults a Properties object containing the default values
  108. */
  109. public Properties(Properties defaults)
  110. {
  111. this.defaults = defaults;
  112. }
  113. /**
  114. * Adds the given key/value pair to this properties. This calls
  115. * the hashtable method put.
  116. *
  117. * @param key the key for this property
  118. * @param value the value for this property
  119. * @return The old value for the given key
  120. * @see #getProperty(String)
  121. * @since 1.2
  122. */
  123. public Object setProperty(String key, String value)
  124. {
  125. return put(key, value);
  126. }
  127. /**
  128. * Reads a property list from an input stream. The stream should
  129. * have the following format: <br>
  130. *
  131. * An empty line or a line starting with <code>#</code> or
  132. * <code>!</code> is ignored. An backslash (<code>\</code>) at the
  133. * end of the line makes the line continueing on the next line
  134. * (but make sure there is no whitespace after the backslash).
  135. * Otherwise, each line describes a key/value pair. <br>
  136. *
  137. * The chars up to the first whitespace, = or : are the key. You
  138. * can include this caracters in the key, if you precede them with
  139. * a backslash (<code>\</code>). The key is followed by optional
  140. * whitespaces, optionally one <code>=</code> or <code>:</code>,
  141. * and optionally some more whitespaces. The rest of the line is
  142. * the resource belonging to the key. <br>
  143. *
  144. * Escape sequences <code>\t, \n, \r, \\, \", \', \!, \#, \ </code>(a
  145. * space), and unicode characters with the
  146. * <code>\\u</code><em>xxxx</em> notation are detected, and
  147. * converted to the corresponding single character. <br>
  148. *
  149. *
  150. <pre># This is a comment
  151. key = value
  152. k\:5 \ a string starting with space and ending with newline\n
  153. # This is a multiline specification; note that the value contains
  154. # no white space.
  155. weekdays: Sunday,Monday,Tuesday,Wednesday,\\
  156. Thursday,Friday,Saturday
  157. # The safest way to include a space at the end of a value:
  158. label = Name:\\u0020</pre>
  159. *
  160. * @param in the input stream
  161. * @throws IOException if an error occurred when reading the input
  162. * @throws NullPointerException if in is null
  163. */
  164. public void load(InputStream inStream) throws IOException
  165. {
  166. // The spec says that the file must be encoded using ISO-8859-1.
  167. BufferedReader reader =
  168. new BufferedReader(new InputStreamReader(inStream, "ISO-8859-1"));
  169. String line;
  170. while ((line = reader.readLine()) != null)
  171. {
  172. char c = 0;
  173. int pos = 0;
  174. // If empty line or begins with a comment character, skip this line.
  175. if (line.length() == 0
  176. || line.charAt(0) == '#' || line.charAt(0) == '!')
  177. continue;
  178. while (pos < line.length()
  179. && Character.isWhitespace(c = line.charAt(pos)))
  180. pos++;
  181. // If line is empty skip this line.
  182. if (pos == line.length())
  183. continue;
  184. // The characters up to the next Whitespace, ':', or '='
  185. // describe the key. But look for escape sequences.
  186. StringBuffer key = new StringBuffer();
  187. while (pos < line.length()
  188. && ! Character.isWhitespace(c = line.charAt(pos++))
  189. && c != '=' && c != ':')
  190. {
  191. if (c == '\\')
  192. {
  193. if (pos == line.length())
  194. {
  195. // The line continues on the next line.
  196. line = reader.readLine();
  197. pos = 0;
  198. while (pos < line.length()
  199. && Character.isWhitespace(c = line.charAt(pos)))
  200. pos++;
  201. }
  202. else
  203. {
  204. c = line.charAt(pos++);
  205. switch (c)
  206. {
  207. case 'n':
  208. key.append('\n');
  209. break;
  210. case 't':
  211. key.append('\t');
  212. break;
  213. case 'r':
  214. key.append('\r');
  215. break;
  216. case 'u':
  217. if (pos + 4 <= line.length())
  218. {
  219. char uni = (char) Integer.parseInt
  220. (line.substring(pos, pos + 4), 16);
  221. key.append(uni);
  222. pos += 4;
  223. } // else throw exception?
  224. break;
  225. default:
  226. key.append(c);
  227. break;
  228. }
  229. }
  230. }
  231. else
  232. key.append(c);
  233. }
  234. boolean isDelim = (c == ':' || c == '=');
  235. while (pos < line.length()
  236. && Character.isWhitespace(c = line.charAt(pos)))
  237. pos++;
  238. if (! isDelim && (c == ':' || c == '='))
  239. {
  240. pos++;
  241. while (pos < line.length()
  242. && Character.isWhitespace(c = line.charAt(pos)))
  243. pos++;
  244. }
  245. StringBuffer element = new StringBuffer(line.length() - pos);
  246. while (pos < line.length())
  247. {
  248. c = line.charAt(pos++);
  249. if (c == '\\')
  250. {
  251. if (pos == line.length())
  252. {
  253. // The line continues on the next line.
  254. line = reader.readLine();
  255. // We might have seen a backslash at the end of
  256. // the file. The JDK ignores the backslash in
  257. // this case, so we follow for compatibility.
  258. if (line == null)
  259. break;
  260. pos = 0;
  261. while (pos < line.length()
  262. && Character.isWhitespace(c = line.charAt(pos)))
  263. pos++;
  264. element.ensureCapacity(line.length() - pos +
  265. element.length());
  266. }
  267. else
  268. {
  269. c = line.charAt(pos++);
  270. switch (c)
  271. {
  272. case 'n':
  273. element.append('\n');
  274. break;
  275. case 't':
  276. element.append('\t');
  277. break;
  278. case 'r':
  279. element.append('\r');
  280. break;
  281. case 'u':
  282. if (pos + 4 <= line.length())
  283. {
  284. char uni = (char) Integer.parseInt
  285. (line.substring(pos, pos + 4), 16);
  286. element.append(uni);
  287. pos += 4;
  288. } // else throw exception?
  289. break;
  290. default:
  291. element.append(c);
  292. break;
  293. }
  294. }
  295. }
  296. else
  297. element.append(c);
  298. }
  299. put(key.toString(), element.toString());
  300. }
  301. }
  302. /**
  303. * Calls <code>store(OutputStream out, String header)</code> and
  304. * ignores the IOException that may be thrown.
  305. *
  306. * @param out the stream to write to
  307. * @param header a description of the property list
  308. * @throws ClassCastException if this property contains any key or
  309. * value that are not strings
  310. * @deprecated use {@link #store(OutputStream, String)} instead
  311. */
  312. public void save(OutputStream out, String header)
  313. {
  314. try
  315. {
  316. store(out, header);
  317. }
  318. catch (IOException ex)
  319. {
  320. }
  321. }
  322. /**
  323. * Writes the key/value pairs to the given output stream, in a format
  324. * suitable for <code>load</code>.<br>
  325. *
  326. * If header is not null, this method writes a comment containing
  327. * the header as first line to the stream. The next line (or first
  328. * line if header is null) contains a comment with the current date.
  329. * Afterwards the key/value pairs are written to the stream in the
  330. * following format.<br>
  331. *
  332. * Each line has the form <code>key = value</code>. Newlines,
  333. * Returns and tabs are written as <code>\n,\t,\r</code> resp.
  334. * The characters <code>\, !, #, =</code> and <code>:</code> are
  335. * preceeded by a backslash. Spaces are preceded with a backslash,
  336. * if and only if they are at the beginning of the key. Characters
  337. * that are not in the ascii range 33 to 127 are written in the
  338. * <code>\</code><code>u</code>xxxx Form.<br>
  339. *
  340. * Following the listing, the output stream is flushed but left open.
  341. *
  342. * @param out the output stream
  343. * @param header the header written in the first line, may be null
  344. * @throws ClassCastException if this property contains any key or
  345. * value that isn't a string
  346. * @throws IOException if writing to the stream fails
  347. * @throws NullPointerException if out is null
  348. * @since 1.2
  349. */
  350. public void store(OutputStream out, String header) throws IOException
  351. {
  352. // The spec says that the file must be encoded using ISO-8859-1.
  353. PrintWriter writer
  354. = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1"));
  355. if (header != null)
  356. writer.println("#" + header);
  357. writer.println ("#" + Calendar.getInstance ().getTime ());
  358. Iterator iter = entrySet ().iterator ();
  359. int i = size ();
  360. StringBuffer s = new StringBuffer (); // Reuse the same buffer.
  361. while (--i >= 0)
  362. {
  363. Map.Entry entry = (Map.Entry) iter.next ();
  364. formatForOutput ((String) entry.getKey (), s, true);
  365. s.append ('=');
  366. formatForOutput ((String) entry.getValue (), s, false);
  367. writer.println (s);
  368. }
  369. writer.flush ();
  370. }
  371. /**
  372. * Gets the property with the specified key in this property list.
  373. * If the key is not found, the default property list is searched.
  374. * If the property is not found in the default, null is returned.
  375. *
  376. * @param key The key for this property
  377. * @return the value for the given key, or null if not found
  378. * @throws ClassCastException if this property contains any key or
  379. * value that isn't a string
  380. * @see #defaults
  381. * @see #setProperty(String, String)
  382. * @see #getProperty(String, String)
  383. */
  384. public String getProperty(String key)
  385. {
  386. return getProperty(key, null);
  387. }
  388. /**
  389. * Gets the property with the specified key in this property list. If
  390. * the key is not found, the default property list is searched. If the
  391. * property is not found in the default, the specified defaultValue is
  392. * returned.
  393. *
  394. * @param key The key for this property
  395. * @param defaultValue A default value
  396. * @return The value for the given key
  397. * @throws ClassCastException if this property contains any key or
  398. * value that isn't a string
  399. * @see #defaults
  400. * @see #setProperty(String, String)
  401. */
  402. public String getProperty(String key, String defaultValue)
  403. {
  404. Properties prop = this;
  405. // Eliminate tail recursion.
  406. do
  407. {
  408. String value = (String) prop.get(key);
  409. if (value != null)
  410. return value;
  411. prop = prop.defaults;
  412. }
  413. while (prop != null);
  414. return defaultValue;
  415. }
  416. /**
  417. * Returns an enumeration of all keys in this property list, including
  418. * the keys in the default property list.
  419. *
  420. * @return an Enumeration of all defined keys
  421. */
  422. public Enumeration propertyNames()
  423. {
  424. // We make a new Set that holds all the keys, then return an enumeration
  425. // for that. This prevents modifications from ruining the enumeration,
  426. // as well as ignoring duplicates.
  427. Properties prop = this;
  428. Set s = new HashSet();
  429. // Eliminate tail recursion.
  430. do
  431. {
  432. s.addAll(prop.keySet());
  433. prop = prop.defaults;
  434. }
  435. while (prop != null);
  436. return Collections.enumeration(s);
  437. }
  438. /**
  439. * Prints the key/value pairs to the given print stream. This is
  440. * mainly useful for debugging purposes.
  441. *
  442. * @param out the print stream, where the key/value pairs are written to
  443. * @throws ClassCastException if this property contains a key or a
  444. * value that isn't a string
  445. * @see #list(PrintWriter)
  446. */
  447. public void list(PrintStream out)
  448. {
  449. PrintWriter writer = new PrintWriter (out);
  450. list (writer);
  451. }
  452. /**
  453. * Prints the key/value pairs to the given print writer. This is
  454. * mainly useful for debugging purposes.
  455. *
  456. * @param out the print writer where the key/value pairs are written to
  457. * @throws ClassCastException if this property contains a key or a
  458. * value that isn't a string
  459. * @see #list(PrintStream)
  460. * @since 1.1
  461. */
  462. public void list(PrintWriter out)
  463. {
  464. out.println ("-- listing properties --");
  465. Iterator iter = entrySet ().iterator ();
  466. int i = size ();
  467. while (--i >= 0)
  468. {
  469. Map.Entry entry = (Map.Entry) iter.next ();
  470. out.print ((String) entry.getKey () + "=");
  471. // JDK 1.3/1.4 restrict the printed value, but not the key,
  472. // to 40 characters, including the truncating ellipsis.
  473. String s = (String ) entry.getValue ();
  474. if (s != null && s.length () > 40)
  475. out.println (s.substring (0, 37) + "...");
  476. else
  477. out.println (s);
  478. }
  479. out.flush ();
  480. }
  481. /**
  482. * Formats a key or value for output in a properties file.
  483. * See store for a description of the format.
  484. *
  485. * @param str the string to format
  486. * @param buffer the buffer to add it to
  487. * @param key true if all ' ' must be escaped for the key, false if only
  488. * leading spaces must be escaped for the value
  489. * @see #store(OutputStream, String)
  490. */
  491. private void formatForOutput(String str, StringBuffer buffer, boolean key)
  492. {
  493. if (key)
  494. {
  495. buffer.setLength(0);
  496. buffer.ensureCapacity(str.length());
  497. }
  498. else
  499. buffer.ensureCapacity(buffer.length() + str.length());
  500. boolean head = true;
  501. int size = str.length();
  502. for (int i = 0; i < size; i++)
  503. {
  504. char c = str.charAt(i);
  505. switch (c)
  506. {
  507. case '\n':
  508. buffer.append("\\n");
  509. break;
  510. case '\r':
  511. buffer.append("\\r");
  512. break;
  513. case '\t':
  514. buffer.append("\\t");
  515. break;
  516. case ' ':
  517. buffer.append(head ? "\\ " : " ");
  518. break;
  519. case '\\':
  520. case '!':
  521. case '#':
  522. case '=':
  523. case ':':
  524. buffer.append('\\').append(c);
  525. break;
  526. default:
  527. if (c < ' ' || c > '~')
  528. {
  529. String hex = Integer.toHexString(c);
  530. buffer.append("\\u0000".substring(0, 6 - hex.length()));
  531. buffer.append(hex);
  532. }
  533. else
  534. buffer.append(c);
  535. }
  536. if (c != ' ')
  537. head = key;
  538. }
  539. }
  540. } // class Properties