Properties.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. /* Properties.java -- a set of persistent properties
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 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., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 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 gnu.java.lang.CPStringBuilder;
  33. import java.io.BufferedReader;
  34. import java.io.IOException;
  35. import java.io.InputStream;
  36. import java.io.InputStreamReader;
  37. import java.io.OutputStream;
  38. import java.io.OutputStreamWriter;
  39. import java.io.PrintStream;
  40. import java.io.PrintWriter;
  41. import java.io.Reader;
  42. import javax.xml.stream.XMLInputFactory;
  43. import javax.xml.stream.XMLStreamConstants;
  44. import javax.xml.stream.XMLStreamException;
  45. import javax.xml.stream.XMLStreamReader;
  46. import org.w3c.dom.Document;
  47. import org.w3c.dom.DocumentType;
  48. import org.w3c.dom.DOMImplementation;
  49. import org.w3c.dom.Element;
  50. import org.w3c.dom.bootstrap.DOMImplementationRegistry;
  51. import org.w3c.dom.ls.DOMImplementationLS;
  52. import org.w3c.dom.ls.LSOutput;
  53. import org.w3c.dom.ls.LSSerializer;
  54. /**
  55. * A set of persistent properties, which can be saved or loaded from a stream.
  56. * A property list may also contain defaults, searched if the main list
  57. * does not contain a property for a given key.
  58. *
  59. * An example of a properties file for the german language is given
  60. * here. This extends the example given in ListResourceBundle.
  61. * Create a file MyResource_de.properties with the following contents
  62. * and put it in the CLASSPATH. (The character
  63. * <code>\</code><code>u00e4</code> is the german umlaut)
  64. *
  65. *
  66. <pre>s1=3
  67. s2=MeineDisk
  68. s3=3. M\<code></code>u00e4rz 96
  69. s4=Die Diskette ''{1}'' enth\<code></code>u00e4lt {0} in {2}.
  70. s5=0
  71. s6=keine Dateien
  72. s7=1
  73. s8=eine Datei
  74. s9=2
  75. s10={0,number} Dateien
  76. s11=Das Formatieren schlug fehl mit folgender Exception: {0}
  77. s12=FEHLER
  78. s13=Ergebnis
  79. s14=Dialog
  80. s15=Auswahlkriterium
  81. s16=1,3</pre>
  82. *
  83. * <p>Although this is a sub class of a hash table, you should never
  84. * insert anything other than strings to this property, or several
  85. * methods, that need string keys and values, will fail. To ensure
  86. * this, you should use the <code>get/setProperty</code> method instead
  87. * of <code>get/put</code>.
  88. *
  89. * Properties are saved in ISO 8859-1 encoding, using Unicode escapes with
  90. * a single <code>u</code> for any character which cannot be represented.
  91. *
  92. * @author Jochen Hoenicke
  93. * @author Eric Blake (ebb9@email.byu.edu)
  94. * @see PropertyResourceBundle
  95. * @status updated to 1.4
  96. */
  97. public class Properties extends Hashtable<Object, Object>
  98. {
  99. // WARNING: Properties is a CORE class in the bootstrap cycle. See the
  100. // comments in vm/reference/java/lang/Runtime for implications of this fact.
  101. /**
  102. * The property list that contains default values for any keys not
  103. * in this property list.
  104. *
  105. * @serial the default properties
  106. */
  107. protected Properties defaults;
  108. /**
  109. * Compatible with JDK 1.0+.
  110. */
  111. private static final long serialVersionUID = 4112578634029874840L;
  112. /**
  113. * Creates a new empty property list with no default values.
  114. */
  115. public Properties()
  116. {
  117. }
  118. /**
  119. * Create a new empty property list with the specified default values.
  120. *
  121. * @param defaults a Properties object containing the default values
  122. */
  123. public Properties(Properties defaults)
  124. {
  125. this.defaults = defaults;
  126. }
  127. /**
  128. * Adds the given key/value pair to this properties. This calls
  129. * the hashtable method put.
  130. *
  131. * @param key the key for this property
  132. * @param value the value for this property
  133. * @return The old value for the given key
  134. * @see #getProperty(String)
  135. * @since 1.2
  136. */
  137. public Object setProperty(String key, String value)
  138. {
  139. return put(key, value);
  140. }
  141. /**
  142. * Reads a property list from a character stream. The stream should
  143. * have the following format: <br>
  144. *
  145. * An empty line or a line starting with <code>#</code> or
  146. * <code>!</code> is ignored. An backslash (<code>\</code>) at the
  147. * end of the line makes the line continueing on the next line
  148. * (but make sure there is no whitespace after the backslash).
  149. * Otherwise, each line describes a key/value pair. <br>
  150. *
  151. * The chars up to the first whitespace, = or : are the key. You
  152. * can include this caracters in the key, if you precede them with
  153. * a backslash (<code>\</code>). The key is followed by optional
  154. * whitespaces, optionally one <code>=</code> or <code>:</code>,
  155. * and optionally some more whitespaces. The rest of the line is
  156. * the resource belonging to the key. <br>
  157. *
  158. * Escape sequences <code>\t, \n, \r, \\, \", \', \!, \#, \ </code>(a
  159. * space), and unicode characters with the
  160. * <code>\\u</code><em>xxxx</em> notation are detected, and
  161. * converted to the corresponding single character. <br>
  162. *
  163. *
  164. <pre># This is a comment
  165. key = value
  166. k\:5 \ a string starting with space and ending with newline\n
  167. # This is a multiline specification; note that the value contains
  168. # no white space.
  169. weekdays: Sunday,Monday,Tuesday,Wednesday,\\
  170. Thursday,Friday,Saturday
  171. # The safest way to include a space at the end of a value:
  172. label = Name:\\u0020</pre>
  173. *
  174. * @param inReader the input {@link java.io.Reader}.
  175. * @throws IOException if an error occurred when reading the input
  176. * @throws NullPointerException if in is null
  177. * @since 1.6
  178. */
  179. public void load(Reader inReader) throws IOException
  180. {
  181. BufferedReader reader = new BufferedReader(inReader);
  182. String line;
  183. while ((line = reader.readLine()) != null)
  184. {
  185. char c = 0;
  186. int pos = 0;
  187. // Leading whitespaces must be deleted first.
  188. while (pos < line.length()
  189. && Character.isWhitespace(c = line.charAt(pos)))
  190. pos++;
  191. // If empty line or begins with a comment character, skip this line.
  192. if ((line.length() - pos) == 0
  193. || line.charAt(pos) == '#' || line.charAt(pos) == '!')
  194. continue;
  195. // The characters up to the next Whitespace, ':', or '='
  196. // describe the key. But look for escape sequences.
  197. // Try to short-circuit when there is no escape char.
  198. int start = pos;
  199. boolean needsEscape = line.indexOf('\\', pos) != -1;
  200. CPStringBuilder key = needsEscape ? new CPStringBuilder() : null;
  201. while (pos < line.length()
  202. && ! Character.isWhitespace(c = line.charAt(pos++))
  203. && c != '=' && c != ':')
  204. {
  205. if (needsEscape && c == '\\')
  206. {
  207. if (pos == line.length())
  208. {
  209. // The line continues on the next line. If there
  210. // is no next line, just treat it as a key with an
  211. // empty value.
  212. line = reader.readLine();
  213. if (line == null)
  214. line = "";
  215. pos = 0;
  216. while (pos < line.length()
  217. && Character.isWhitespace(c = line.charAt(pos)))
  218. pos++;
  219. }
  220. else
  221. {
  222. c = line.charAt(pos++);
  223. switch (c)
  224. {
  225. case 'n':
  226. key.append('\n');
  227. break;
  228. case 't':
  229. key.append('\t');
  230. break;
  231. case 'r':
  232. key.append('\r');
  233. break;
  234. case 'u':
  235. if (pos + 4 <= line.length())
  236. {
  237. char uni = (char) Integer.parseInt
  238. (line.substring(pos, pos + 4), 16);
  239. key.append(uni);
  240. pos += 4;
  241. } // else throw exception?
  242. break;
  243. default:
  244. key.append(c);
  245. break;
  246. }
  247. }
  248. }
  249. else if (needsEscape)
  250. key.append(c);
  251. }
  252. boolean isDelim = (c == ':' || c == '=');
  253. String keyString;
  254. if (needsEscape)
  255. keyString = key.toString();
  256. else if (isDelim || Character.isWhitespace(c))
  257. keyString = line.substring(start, pos - 1);
  258. else
  259. keyString = line.substring(start, pos);
  260. while (pos < line.length()
  261. && Character.isWhitespace(c = line.charAt(pos)))
  262. pos++;
  263. if (! isDelim && (c == ':' || c == '='))
  264. {
  265. pos++;
  266. while (pos < line.length()
  267. && Character.isWhitespace(c = line.charAt(pos)))
  268. pos++;
  269. }
  270. // Short-circuit if no escape chars found.
  271. if (!needsEscape)
  272. {
  273. put(keyString, line.substring(pos));
  274. continue;
  275. }
  276. // Escape char found so iterate through the rest of the line.
  277. StringBuilder element = new StringBuilder(line.length() - pos);
  278. while (pos < line.length())
  279. {
  280. c = line.charAt(pos++);
  281. if (c == '\\')
  282. {
  283. if (pos == line.length())
  284. {
  285. // The line continues on the next line.
  286. line = reader.readLine();
  287. // We might have seen a backslash at the end of
  288. // the file. The JDK ignores the backslash in
  289. // this case, so we follow for compatibility.
  290. if (line == null)
  291. break;
  292. pos = 0;
  293. while (pos < line.length()
  294. && Character.isWhitespace(c = line.charAt(pos)))
  295. pos++;
  296. element.ensureCapacity(line.length() - pos +
  297. element.length());
  298. }
  299. else
  300. {
  301. c = line.charAt(pos++);
  302. switch (c)
  303. {
  304. case 'n':
  305. element.append('\n');
  306. break;
  307. case 't':
  308. element.append('\t');
  309. break;
  310. case 'r':
  311. element.append('\r');
  312. break;
  313. case 'u':
  314. if (pos + 4 <= line.length())
  315. {
  316. char uni = (char) Integer.parseInt
  317. (line.substring(pos, pos + 4), 16);
  318. element.append(uni);
  319. pos += 4;
  320. } // else throw exception?
  321. break;
  322. default:
  323. element.append(c);
  324. break;
  325. }
  326. }
  327. }
  328. else
  329. element.append(c);
  330. }
  331. put(keyString, element.toString());
  332. }
  333. }
  334. /**
  335. * Reads a property list from the supplied input stream.
  336. * This method has the same functionality as {@link #load(Reader)}
  337. * but the character encoding is assumed to be ISO-8859-1.
  338. * Unicode characters not within the Latin1 set supplied by
  339. * ISO-8859-1 should be escaped using '\\uXXXX' where XXXX
  340. * is the UTF-16 code unit in hexadecimal.
  341. *
  342. * @param inStream the byte stream to read the property list from.
  343. * @throws IOException if an I/O error occurs.
  344. * @see #load(Reader)
  345. * @since 1.2
  346. */
  347. public void load(InputStream inStream) throws IOException
  348. {
  349. load(new InputStreamReader(inStream, "ISO-8859-1"));
  350. }
  351. /**
  352. * Calls <code>store(OutputStream out, String header)</code> and
  353. * ignores the IOException that may be thrown.
  354. *
  355. * @param out the stream to write to
  356. * @param header a description of the property list
  357. * @throws ClassCastException if this property contains any key or
  358. * value that are not strings
  359. * @deprecated use {@link #store(OutputStream, String)} instead
  360. */
  361. @Deprecated
  362. public void save(OutputStream out, String header)
  363. {
  364. try
  365. {
  366. store(out, header);
  367. }
  368. catch (IOException ex)
  369. {
  370. }
  371. }
  372. /**
  373. * Writes the key/value pairs to the given output stream, in a format
  374. * suitable for <code>load</code>.<br>
  375. *
  376. * If header is not null, this method writes a comment containing
  377. * the header as first line to the stream. The next line (or first
  378. * line if header is null) contains a comment with the current date.
  379. * Afterwards the key/value pairs are written to the stream in the
  380. * following format.<br>
  381. *
  382. * Each line has the form <code>key = value</code>. Newlines,
  383. * Returns and tabs are written as <code>\n,\t,\r</code> resp.
  384. * The characters <code>\, !, #, =</code> and <code>:</code> are
  385. * preceeded by a backslash. Spaces are preceded with a backslash,
  386. * if and only if they are at the beginning of the key. Characters
  387. * that are not in the ascii range 33 to 127 are written in the
  388. * <code>\</code><code>u</code>xxxx Form.<br>
  389. *
  390. * Following the listing, the output stream is flushed but left open.
  391. *
  392. * @param out the output stream
  393. * @param header the header written in the first line, may be null
  394. * @throws ClassCastException if this property contains any key or
  395. * value that isn't a string
  396. * @throws IOException if writing to the stream fails
  397. * @throws NullPointerException if out is null
  398. * @since 1.2
  399. */
  400. public void store(OutputStream out, String header) throws IOException
  401. {
  402. // The spec says that the file must be encoded using ISO-8859-1.
  403. PrintWriter writer
  404. = new PrintWriter(new OutputStreamWriter(out, "ISO-8859-1"));
  405. if (header != null)
  406. writer.println("#" + header);
  407. writer.println ("#" + Calendar.getInstance ().getTime ());
  408. Iterator iter = entrySet ().iterator ();
  409. int i = size ();
  410. CPStringBuilder s = new CPStringBuilder (); // Reuse the same buffer.
  411. while (--i >= 0)
  412. {
  413. Map.Entry entry = (Map.Entry) iter.next ();
  414. formatForOutput ((String) entry.getKey (), s, true);
  415. s.append ('=');
  416. formatForOutput ((String) entry.getValue (), s, false);
  417. writer.println (s);
  418. }
  419. writer.flush ();
  420. }
  421. /**
  422. * Gets the property with the specified key in this property list.
  423. * If the key is not found, the default property list is searched.
  424. * If the property is not found in the default, null is returned.
  425. *
  426. * @param key The key for this property
  427. * @return the value for the given key, or null if not found
  428. * @throws ClassCastException if this property contains any key or
  429. * value that isn't a string
  430. * @see #defaults
  431. * @see #setProperty(String, String)
  432. * @see #getProperty(String, String)
  433. */
  434. public String getProperty(String key)
  435. {
  436. Properties prop = this;
  437. // Eliminate tail recursion.
  438. do
  439. {
  440. String value = (String) prop.get(key);
  441. if (value != null)
  442. return value;
  443. prop = prop.defaults;
  444. }
  445. while (prop != null);
  446. return null;
  447. }
  448. /**
  449. * Gets the property with the specified key in this property list. If
  450. * the key is not found, the default property list is searched. If the
  451. * property is not found in the default, the specified defaultValue is
  452. * returned.
  453. *
  454. * @param key The key for this property
  455. * @param defaultValue A default value
  456. * @return The value for the given key
  457. * @throws ClassCastException if this property contains any key or
  458. * value that isn't a string
  459. * @see #defaults
  460. * @see #setProperty(String, String)
  461. */
  462. public String getProperty(String key, String defaultValue)
  463. {
  464. String prop = getProperty(key);
  465. if (prop == null)
  466. prop = defaultValue;
  467. return prop;
  468. }
  469. /**
  470. * Returns an enumeration of all keys in this property list, including
  471. * the keys in the default property list.
  472. *
  473. * @return an Enumeration of all defined keys
  474. */
  475. public Enumeration<?> propertyNames()
  476. {
  477. // We make a new Set that holds all the keys, then return an enumeration
  478. // for that. This prevents modifications from ruining the enumeration,
  479. // as well as ignoring duplicates.
  480. Properties prop = this;
  481. Set s = new HashSet();
  482. // Eliminate tail recursion.
  483. do
  484. {
  485. s.addAll(prop.keySet());
  486. prop = prop.defaults;
  487. }
  488. while (prop != null);
  489. return Collections.enumeration(s);
  490. }
  491. /**
  492. * Prints the key/value pairs to the given print stream. This is
  493. * mainly useful for debugging purposes.
  494. *
  495. * @param out the print stream, where the key/value pairs are written to
  496. * @throws ClassCastException if this property contains a key or a
  497. * value that isn't a string
  498. * @see #list(PrintWriter)
  499. */
  500. public void list(PrintStream out)
  501. {
  502. PrintWriter writer = new PrintWriter (out);
  503. list (writer);
  504. }
  505. /**
  506. * Prints the key/value pairs to the given print writer. This is
  507. * mainly useful for debugging purposes.
  508. *
  509. * @param out the print writer where the key/value pairs are written to
  510. * @throws ClassCastException if this property contains a key or a
  511. * value that isn't a string
  512. * @see #list(PrintStream)
  513. * @since 1.1
  514. */
  515. public void list(PrintWriter out)
  516. {
  517. out.println ("-- listing properties --");
  518. Iterator iter = entrySet ().iterator ();
  519. int i = size ();
  520. while (--i >= 0)
  521. {
  522. Map.Entry entry = (Map.Entry) iter.next ();
  523. out.print ((String) entry.getKey () + "=");
  524. // JDK 1.3/1.4 restrict the printed value, but not the key,
  525. // to 40 characters, including the truncating ellipsis.
  526. String s = (String ) entry.getValue ();
  527. if (s != null && s.length () > 40)
  528. out.println (s.substring (0, 37) + "...");
  529. else
  530. out.println (s);
  531. }
  532. out.flush ();
  533. }
  534. /**
  535. * Formats a key or value for output in a properties file.
  536. * See store for a description of the format.
  537. *
  538. * @param str the string to format
  539. * @param buffer the buffer to add it to
  540. * @param key true if all ' ' must be escaped for the key, false if only
  541. * leading spaces must be escaped for the value
  542. * @see #store(OutputStream, String)
  543. */
  544. private void formatForOutput(String str, CPStringBuilder buffer, boolean key)
  545. {
  546. if (key)
  547. {
  548. buffer.setLength(0);
  549. buffer.ensureCapacity(str.length());
  550. }
  551. else
  552. buffer.ensureCapacity(buffer.length() + str.length());
  553. boolean head = true;
  554. int size = str.length();
  555. for (int i = 0; i < size; i++)
  556. {
  557. char c = str.charAt(i);
  558. switch (c)
  559. {
  560. case '\n':
  561. buffer.append("\\n");
  562. break;
  563. case '\r':
  564. buffer.append("\\r");
  565. break;
  566. case '\t':
  567. buffer.append("\\t");
  568. break;
  569. case ' ':
  570. buffer.append(head ? "\\ " : " ");
  571. break;
  572. case '\\':
  573. case '!':
  574. case '#':
  575. case '=':
  576. case ':':
  577. buffer.append('\\').append(c);
  578. break;
  579. default:
  580. if (c < ' ' || c > '~')
  581. {
  582. String hex = Integer.toHexString(c);
  583. buffer.append("\\u0000".substring(0, 6 - hex.length()));
  584. buffer.append(hex);
  585. }
  586. else
  587. buffer.append(c);
  588. }
  589. if (c != ' ')
  590. head = key;
  591. }
  592. }
  593. /**
  594. * <p>
  595. * Encodes the properties as an XML file using the UTF-8 encoding.
  596. * The format of the XML file matches the DTD
  597. * <a href="http://java.sun.com/dtd/properties.dtd">
  598. * http://java.sun.com/dtd/properties.dtd</a>.
  599. * </p>
  600. * <p>
  601. * Invoking this method provides the same behaviour as invoking
  602. * <code>storeToXML(os, comment, "UTF-8")</code>.
  603. * </p>
  604. *
  605. * @param os the stream to output to.
  606. * @param comment a comment to include at the top of the XML file, or
  607. * <code>null</code> if one is not required.
  608. * @throws IOException if the serialization fails.
  609. * @throws NullPointerException if <code>os</code> is null.
  610. * @since 1.5
  611. */
  612. public void storeToXML(OutputStream os, String comment)
  613. throws IOException
  614. {
  615. storeToXML(os, comment, "UTF-8");
  616. }
  617. /**
  618. * <p>
  619. * Encodes the properties as an XML file using the supplied encoding.
  620. * The format of the XML file matches the DTD
  621. * <a href="http://java.sun.com/dtd/properties.dtd">
  622. * http://java.sun.com/dtd/properties.dtd</a>.
  623. * </p>
  624. *
  625. * @param os the stream to output to.
  626. * @param comment a comment to include at the top of the XML file, or
  627. * <code>null</code> if one is not required.
  628. * @param encoding the encoding to use for the XML output.
  629. * @throws IOException if the serialization fails.
  630. * @throws NullPointerException if <code>os</code> or <code>encoding</code>
  631. * is null.
  632. * @since 1.5
  633. */
  634. public void storeToXML(OutputStream os, String comment, String encoding)
  635. throws IOException
  636. {
  637. if (os == null)
  638. throw new NullPointerException("Null output stream supplied.");
  639. if (encoding == null)
  640. throw new NullPointerException("Null encoding supplied.");
  641. try
  642. {
  643. DOMImplementationRegistry registry =
  644. DOMImplementationRegistry.newInstance();
  645. DOMImplementation domImpl = registry.getDOMImplementation("LS 3.0");
  646. DocumentType doctype =
  647. domImpl.createDocumentType("properties", null,
  648. "http://java.sun.com/dtd/properties.dtd");
  649. Document doc = domImpl.createDocument(null, "properties", doctype);
  650. Element root = doc.getDocumentElement();
  651. if (comment != null)
  652. {
  653. Element commentElement = doc.createElement("comment");
  654. commentElement.appendChild(doc.createTextNode(comment));
  655. root.appendChild(commentElement);
  656. }
  657. Iterator iterator = entrySet().iterator();
  658. while (iterator.hasNext())
  659. {
  660. Map.Entry entry = (Map.Entry) iterator.next();
  661. Element entryElement = doc.createElement("entry");
  662. entryElement.setAttribute("key", (String) entry.getKey());
  663. entryElement.appendChild(doc.createTextNode((String)
  664. entry.getValue()));
  665. root.appendChild(entryElement);
  666. }
  667. DOMImplementationLS loadAndSave = (DOMImplementationLS) domImpl;
  668. LSSerializer serializer = loadAndSave.createLSSerializer();
  669. LSOutput output = loadAndSave.createLSOutput();
  670. output.setByteStream(os);
  671. output.setEncoding(encoding);
  672. serializer.write(doc, output);
  673. }
  674. catch (ClassNotFoundException e)
  675. {
  676. throw (IOException)
  677. new IOException("The XML classes could not be found.").initCause(e);
  678. }
  679. catch (InstantiationException e)
  680. {
  681. throw (IOException)
  682. new IOException("The XML classes could not be instantiated.")
  683. .initCause(e);
  684. }
  685. catch (IllegalAccessException e)
  686. {
  687. throw (IOException)
  688. new IOException("The XML classes could not be accessed.")
  689. .initCause(e);
  690. }
  691. }
  692. /**
  693. * <p>
  694. * Decodes the contents of the supplied <code>InputStream</code> as
  695. * an XML file, which represents a set of properties. The format of
  696. * the XML file must match the DTD
  697. * <a href="http://java.sun.com/dtd/properties.dtd">
  698. * http://java.sun.com/dtd/properties.dtd</a>.
  699. * </p>
  700. *
  701. * @param in the input stream from which to receive the XML data.
  702. * @throws IOException if an I/O error occurs in reading the input data.
  703. * @throws InvalidPropertiesFormatException if the input data does not
  704. * constitute an XML properties
  705. * file.
  706. * @throws NullPointerException if <code>in</code> is null.
  707. * @since 1.5
  708. */
  709. public void loadFromXML(InputStream in)
  710. throws IOException, InvalidPropertiesFormatException
  711. {
  712. if (in == null)
  713. throw new NullPointerException("Null input stream supplied.");
  714. try
  715. {
  716. XMLInputFactory factory = XMLInputFactory.newInstance();
  717. // Don't resolve external entity references
  718. factory.setProperty("javax.xml.stream.isSupportingExternalEntities",
  719. Boolean.FALSE);
  720. XMLStreamReader reader = factory.createXMLStreamReader(in);
  721. String name, key = null;
  722. CPStringBuilder buf = null;
  723. while (reader.hasNext())
  724. {
  725. switch (reader.next())
  726. {
  727. case XMLStreamConstants.START_ELEMENT:
  728. name = reader.getLocalName();
  729. if (buf == null && "entry".equals(name))
  730. {
  731. key = reader.getAttributeValue(null, "key");
  732. if (key == null)
  733. {
  734. String msg = "missing 'key' attribute";
  735. throw new InvalidPropertiesFormatException(msg);
  736. }
  737. buf = new CPStringBuilder();
  738. }
  739. else if (!"properties".equals(name) && !"comment".equals(name))
  740. {
  741. String msg = "unexpected element name '" + name + "'";
  742. throw new InvalidPropertiesFormatException(msg);
  743. }
  744. break;
  745. case XMLStreamConstants.END_ELEMENT:
  746. name = reader.getLocalName();
  747. if (buf != null && "entry".equals(name))
  748. {
  749. put(key, buf.toString());
  750. buf = null;
  751. }
  752. else if (!"properties".equals(name) && !"comment".equals(name))
  753. {
  754. String msg = "unexpected element name '" + name + "'";
  755. throw new InvalidPropertiesFormatException(msg);
  756. }
  757. break;
  758. case XMLStreamConstants.CHARACTERS:
  759. case XMLStreamConstants.SPACE:
  760. case XMLStreamConstants.CDATA:
  761. if (buf != null)
  762. buf.append(reader.getText());
  763. break;
  764. }
  765. }
  766. reader.close();
  767. }
  768. catch (XMLStreamException e)
  769. {
  770. throw (InvalidPropertiesFormatException)
  771. new InvalidPropertiesFormatException("Error in parsing XML.").
  772. initCause(e);
  773. }
  774. }
  775. } // class Properties