1. /*
  2. * @(#)AbstractPreferences.java 1.20 04/01/12
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util.prefs;
  8. import java.util.*;
  9. import java.io.*;
  10. import java.security.AccessController;
  11. import java.security.PrivilegedAction;
  12. // These imports needed only as a workaround for a JavaDoc bug
  13. import java.lang.Integer;
  14. import java.lang.Long;
  15. import java.lang.Float;
  16. import java.lang.Double;
  17. /**
  18. * This class provides a skeletal implementation of the {@link Preferences}
  19. * class, greatly easing the task of implementing it.
  20. *
  21. * <p><strong>This class is for <tt>Preferences</tt> implementers only.
  22. * Normal users of the <tt>Preferences</tt> facility should have no need to
  23. * consult this documentation. The {@link Preferences} documentation
  24. * should suffice.</strong>
  25. *
  26. * <p>Implementors must override the nine abstract service-provider interface
  27. * (SPI) methods: {@link #getSpi(String)}, {@link #putSpi(String,String)},
  28. * {@link #removeSpi(String)}, {@link #childSpi(String)}, {@link
  29. * #removeNodeSpi()}, {@link #keysSpi()}, {@link #childrenNamesSpi()}, {@link
  30. * #syncSpi()} and {@link #flushSpi()}. All of the concrete methods specify
  31. * precisely how they are implemented atop these SPI methods. The implementor
  32. * may, at his discretion, override one or more of the concrete methods if the
  33. * default implementation is unsatisfactory for any reason, such as
  34. * performance.
  35. *
  36. * <p>The SPI methods fall into three groups concerning exception
  37. * behavior. The <tt>getSpi</tt> method should never throw exceptions, but it
  38. * doesn't really matter, as any exception thrown by this method will be
  39. * intercepted by {@link #get(String,String)}, which will return the specified
  40. * default value to the caller. The <tt>removeNodeSpi, keysSpi,
  41. * childrenNamesSpi, syncSpi</tt> and <tt>flushSpi</tt> methods are specified
  42. * to throw {@link BackingStoreException}, and the implementation is required
  43. * to throw this checked exception if it is unable to perform the operation.
  44. * The exception propagates outward, causing the corresponding API method
  45. * to fail.
  46. *
  47. * <p>The remaining SPI methods {@link #putSpi(String,String)}, {@link
  48. * #removeSpi(String)} and {@link #childSpi(String)} have more complicated
  49. * exception behavior. They are not specified to throw
  50. * <tt>BackingStoreException</tt>, as they can generally obey their contracts
  51. * even if the backing store is unavailable. This is true because they return
  52. * no information and their effects are not required to become permanent until
  53. * a subsequent call to {Preferences#flush()} or
  54. * {Preferences#sync()}. Generally speaking, these SPI methods should not
  55. * throw exceptions. In some implementations, there may be circumstances
  56. * under which these calls cannot even enqueue the requested operation for
  57. * later processing. Even under these circumstances it is generally better to
  58. * simply ignore the invocation and return, rather than throwing an
  59. * exception. Under these circumstances, however, all subsequent invocations
  60. * of <tt>flush()</tt> and <tt>sync</tt> should return <tt>false</tt>, as
  61. * returning <tt>true</tt> would imply that all previous operations had
  62. * successfully been made permanent.
  63. *
  64. * <p>There is one circumstance under which <tt>putSpi, removeSpi and
  65. * childSpi</tt> <i>should</i> throw an exception: if the caller lacks
  66. * sufficient privileges on the underlying operating system to perform the
  67. * requested operation. This will, for instance, occur on most systems
  68. * if a non-privileged user attempts to modify system preferences.
  69. * (The required privileges will vary from implementation to
  70. * implementation. On some implementations, they are the right to modify the
  71. * contents of some directory in the file system; on others they are the right
  72. * to modify contents of some key in a registry.) Under any of these
  73. * circumstances, it would generally be undesirable to let the program
  74. * continue executing as if these operations would become permanent at a later
  75. * time. While implementations are not required to throw an exception under
  76. * these circumstances, they are encouraged to do so. A {@link
  77. * SecurityException} would be appropriate.
  78. *
  79. * <p>Most of the SPI methods require the implementation to read or write
  80. * information at a preferences node. The implementor should beware of the
  81. * fact that another VM may have concurrently deleted this node from the
  82. * backing store. It is the implementation's responsibility to recreate the
  83. * node if it has been deleted.
  84. *
  85. * <p>Implementation note: In Sun's default <tt>Preferences</tt>
  86. * implementations, the user's identity is inherited from the underlying
  87. * operating system and does not change for the lifetime of the virtual
  88. * machine. It is recognized that server-side <tt>Preferences</tt>
  89. * implementations may have the user identity change from request to request,
  90. * implicitly passed to <tt>Preferences</tt> methods via the use of a
  91. * static {@link ThreadLocal} instance. Authors of such implementations are
  92. * <i>strongly</i> encouraged to determine the user at the time preferences
  93. * are accessed (for example by the {@link #get(String,String)} or {@link
  94. * #put(String,String)} method) rather than permanently associating a user
  95. * with each <tt>Preferences</tt> instance. The latter behavior conflicts
  96. * with normal <tt>Preferences</tt> usage and would lead to great confusion.
  97. *
  98. * @author Josh Bloch
  99. * @version 1.20, 01/12/04
  100. * @see Preferences
  101. * @since 1.4
  102. */
  103. public abstract class AbstractPreferences extends Preferences {
  104. /**
  105. * Our name relative to parent.
  106. */
  107. private final String name;
  108. /**
  109. * Our absolute path name.
  110. */
  111. private final String absolutePath;
  112. /**
  113. * Our parent node.
  114. */
  115. final AbstractPreferences parent;
  116. /**
  117. * Our root node.
  118. */
  119. private final AbstractPreferences root; // Relative to this node
  120. /**
  121. * This field should be <tt>true</tt> if this node did not exist in the
  122. * backing store prior to the creation of this object. The field
  123. * is initialized to false, but may be set to true by a subclass
  124. * constructor (and should not be modified thereafter). This field
  125. * indicates whether a node change event should be fired when
  126. * creation is complete.
  127. */
  128. protected boolean newNode = false;
  129. /**
  130. * All known unremoved children of this node. (This "cache" is consulted
  131. * prior to calling childSpi() or getChild().
  132. */
  133. private Map kidCache = new HashMap();
  134. /**
  135. * This field is used to keep track of whether or not this node has
  136. * been removed. Once it's set to true, it will never be reset to false.
  137. */
  138. private boolean removed = false;
  139. /**
  140. * Registered preference change listeners.
  141. */
  142. private PreferenceChangeListener[] prefListeners =
  143. new PreferenceChangeListener[0];
  144. /**
  145. * Registered node change listeners.
  146. */
  147. private NodeChangeListener[] nodeListeners = new NodeChangeListener[0];
  148. /**
  149. * An object whose monitor is used to lock this node. This object
  150. * is used in preference to the node itself to reduce the likelihood of
  151. * intentional or unintentional denial of service due to a locked node.
  152. * To avoid deadlock, a node is <i>never</i> locked by a thread that
  153. * holds a lock on a descendant of that node.
  154. */
  155. protected final Object lock = new Object();
  156. /**
  157. * Creates a preference node with the specified parent and the specified
  158. * name relative to its parent.
  159. *
  160. * @param parent the parent of this preference node, or null if this
  161. * is the root.
  162. * @param name the name of this preference node, relative to its parent,
  163. * or <tt>""</tt> if this is the root.
  164. * @throws IllegalArgumentException if <tt>name</tt> contains a slash
  165. * (<tt>'/'</tt>), or <tt>parent</tt> is <tt>null</tt> and
  166. * name isn't <tt>""</tt>.
  167. */
  168. protected AbstractPreferences(AbstractPreferences parent, String name) {
  169. if (parent==null) {
  170. if (!name.equals(""))
  171. throw new IllegalArgumentException("Root name '"+name+
  172. "' must be \"\"");
  173. this.absolutePath = "/";
  174. root = this;
  175. } else {
  176. if (name.indexOf('/') != -1)
  177. throw new IllegalArgumentException("Name '" + name +
  178. "' contains '/'");
  179. if (name.equals(""))
  180. throw new IllegalArgumentException("Illegal name: empty string");
  181. root = parent.root;
  182. absolutePath = (parent==root ? "/" + name
  183. : parent.absolutePath() + "/" + name);
  184. }
  185. this.name = name;
  186. this.parent = parent;
  187. }
  188. /**
  189. * Implements the <tt>put</tt> method as per the specification in
  190. * {@link Preferences#put(String,String)}.
  191. *
  192. * <p>This implementation checks that the key and value are legal,
  193. * obtains this preference node's lock, checks that the node
  194. * has not been removed, invokes {@link #putSpi(String,String)}, and if
  195. * there are any preference change listeners, enqueues a notification
  196. * event for processing by the event dispatch thread.
  197. *
  198. * @param key key with which the specified value is to be associated.
  199. * @param value value to be associated with the specified key.
  200. * @throws NullPointerException if key or value is <tt>null</tt>.
  201. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
  202. * <tt>MAX_KEY_LENGTH</tt> or if <tt>value.length</tt> exceeds
  203. * <tt>MAX_VALUE_LENGTH</tt>.
  204. * @throws IllegalStateException if this node (or an ancestor) has been
  205. * removed with the {@link #removeNode()} method.
  206. */
  207. public void put(String key, String value) {
  208. if (key==null || value==null)
  209. throw new NullPointerException();
  210. if (key.length() > MAX_KEY_LENGTH)
  211. throw new IllegalArgumentException("Key too long: "+key);
  212. if (value.length() > MAX_VALUE_LENGTH)
  213. throw new IllegalArgumentException("Value too long: "+value);
  214. synchronized(lock) {
  215. if (removed)
  216. throw new IllegalStateException("Node has been removed.");
  217. putSpi(key, value);
  218. enqueuePreferenceChangeEvent(key, value);
  219. }
  220. }
  221. /**
  222. * Implements the <tt>get</tt> method as per the specification in
  223. * {@link Preferences#get(String,String)}.
  224. *
  225. * <p>This implementation first checks to see if <tt>key</tt> is
  226. * <tt>null</tt> throwing a <tt>NullPointerException</tt> if this is
  227. * the case. Then it obtains this preference node's lock,
  228. * checks that the node has not been removed, invokes {@link
  229. * #getSpi(String)}, and returns the result, unless the <tt>getSpi</tt>
  230. * invocation returns <tt>null</tt> or throws an exception, in which case
  231. * this invocation returns <tt>def</tt>.
  232. *
  233. * @param key key whose associated value is to be returned.
  234. * @param def the value to be returned in the event that this
  235. * preference node has no value associated with <tt>key</tt>.
  236. * @return the value associated with <tt>key</tt>, or <tt>def</tt>
  237. * if no value is associated with <tt>key</tt>.
  238. * @throws IllegalStateException if this node (or an ancestor) has been
  239. * removed with the {@link #removeNode()} method.
  240. * @throws NullPointerException if key is <tt>null</tt>. (A
  241. * <tt>null</tt> default <i>is</i> permitted.)
  242. */
  243. public String get(String key, String def) {
  244. if (key==null)
  245. throw new NullPointerException("Null key");
  246. synchronized(lock) {
  247. if (removed)
  248. throw new IllegalStateException("Node has been removed.");
  249. String result = null;
  250. try {
  251. result = getSpi(key);
  252. } catch (Exception e) {
  253. // Ignoring exception causes default to be returned
  254. }
  255. return (result==null ? def : result);
  256. }
  257. }
  258. /**
  259. * Implements the <tt>remove(String)</tt> method as per the specification
  260. * in {@link Preferences#remove(String)}.
  261. *
  262. * <p>This implementation obtains this preference node's lock,
  263. * checks that the node has not been removed, invokes
  264. * {@link #removeSpi(String)} and if there are any preference
  265. * change listeners, enqueues a notification event for processing by the
  266. * event dispatch thread.
  267. *
  268. * @param key key whose mapping is to be removed from the preference node.
  269. * @throws IllegalStateException if this node (or an ancestor) has been
  270. * removed with the {@link #removeNode()} method.
  271. */
  272. public void remove(String key) {
  273. synchronized(lock) {
  274. if (removed)
  275. throw new IllegalStateException("Node has been removed.");
  276. removeSpi(key);
  277. enqueuePreferenceChangeEvent(key, null);
  278. }
  279. }
  280. /**
  281. * Implements the <tt>clear</tt> method as per the specification in
  282. * {@link Preferences#clear()}.
  283. *
  284. * <p>This implementation obtains this preference node's lock,
  285. * invokes {@link #keys()} to obtain an array of keys, and
  286. * iterates over the array invoking {@link #remove(String)} on each key.
  287. *
  288. * @throws BackingStoreException if this operation cannot be completed
  289. * due to a failure in the backing store, or inability to
  290. * communicate with it.
  291. * @throws IllegalStateException if this node (or an ancestor) has been
  292. * removed with the {@link #removeNode()} method.
  293. */
  294. public void clear() throws BackingStoreException {
  295. synchronized(lock) {
  296. String[] keys = keys();
  297. for (int i=0; i<keys.length; i++)
  298. remove(keys[i]);
  299. }
  300. }
  301. /**
  302. * Implements the <tt>putInt</tt> method as per the specification in
  303. * {@link Preferences#putInt(String,int)}.
  304. *
  305. * <p>This implementation translates <tt>value</tt> to a string with
  306. * {@link Integer#toString(int)} and invokes {@link #put(String,String)}
  307. * on the result.
  308. *
  309. * @param key key with which the string form of value is to be associated.
  310. * @param value value whose string form is to be associated with key.
  311. * @throws NullPointerException if key is <tt>null</tt>.
  312. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
  313. * <tt>MAX_KEY_LENGTH</tt>.
  314. * @throws IllegalStateException if this node (or an ancestor) has been
  315. * removed with the {@link #removeNode()} method.
  316. */
  317. public void putInt(String key, int value) {
  318. put(key, Integer.toString(value));
  319. }
  320. /**
  321. * Implements the <tt>getInt</tt> method as per the specification in
  322. * {@link Preferences#getInt(String,int)}.
  323. *
  324. * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
  325. * null)</tt>}. If the return value is non-null, the implementation
  326. * attempts to translate it to an <tt>int</tt> with
  327. * {@link Integer#parseInt(String)}. If the attempt succeeds, the return
  328. * value is returned by this method. Otherwise, <tt>def</tt> is returned.
  329. *
  330. * @param key key whose associated value is to be returned as an int.
  331. * @param def the value to be returned in the event that this
  332. * preference node has no value associated with <tt>key</tt>
  333. * or the associated value cannot be interpreted as an int.
  334. * @return the int value represented by the string associated with
  335. * <tt>key</tt> in this preference node, or <tt>def</tt> if the
  336. * associated value does not exist or cannot be interpreted as
  337. * an int.
  338. * @throws IllegalStateException if this node (or an ancestor) has been
  339. * removed with the {@link #removeNode()} method.
  340. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
  341. */
  342. public int getInt(String key, int def) {
  343. int result = def;
  344. try {
  345. String value = get(key, null);
  346. if (value != null)
  347. result = Integer.parseInt(value);
  348. } catch (NumberFormatException e) {
  349. // Ignoring exception causes specified default to be returned
  350. }
  351. return result;
  352. }
  353. /**
  354. * Implements the <tt>putLong</tt> method as per the specification in
  355. * {@link Preferences#putLong(String,long)}.
  356. *
  357. * <p>This implementation translates <tt>value</tt> to a string with
  358. * {@link Long#toString(long)} and invokes {@link #put(String,String)}
  359. * on the result.
  360. *
  361. * @param key key with which the string form of value is to be associated.
  362. * @param value value whose string form is to be associated with key.
  363. * @throws NullPointerException if key is <tt>null</tt>.
  364. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
  365. * <tt>MAX_KEY_LENGTH</tt>.
  366. * @throws IllegalStateException if this node (or an ancestor) has been
  367. * removed with the {@link #removeNode()} method.
  368. */
  369. public void putLong(String key, long value) {
  370. put(key, Long.toString(value));
  371. }
  372. /**
  373. * Implements the <tt>getLong</tt> method as per the specification in
  374. * {@link Preferences#getLong(String,long)}.
  375. *
  376. * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
  377. * null)</tt>}. If the return value is non-null, the implementation
  378. * attempts to translate it to a <tt>long</tt> with
  379. * {@link Long#parseLong(String)}. If the attempt succeeds, the return
  380. * value is returned by this method. Otherwise, <tt>def</tt> is returned.
  381. *
  382. * @param key key whose associated value is to be returned as a long.
  383. * @param def the value to be returned in the event that this
  384. * preference node has no value associated with <tt>key</tt>
  385. * or the associated value cannot be interpreted as a long.
  386. * @return the long value represented by the string associated with
  387. * <tt>key</tt> in this preference node, or <tt>def</tt> if the
  388. * associated value does not exist or cannot be interpreted as
  389. * a long.
  390. * @throws IllegalStateException if this node (or an ancestor) has been
  391. * removed with the {@link #removeNode()} method.
  392. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
  393. */
  394. public long getLong(String key, long def) {
  395. long result = def;
  396. try {
  397. String value = get(key, null);
  398. if (value != null)
  399. result = Long.parseLong(value);
  400. } catch (NumberFormatException e) {
  401. // Ignoring exception causes specified default to be returned
  402. }
  403. return result;
  404. }
  405. /**
  406. * Implements the <tt>putBoolean</tt> method as per the specification in
  407. * {@link Preferences#putBoolean(String,boolean)}.
  408. *
  409. * <p>This implementation translates <tt>value</tt> to a string with
  410. * {@link String#valueOf(boolean)} and invokes {@link #put(String,String)}
  411. * on the result.
  412. *
  413. * @param key key with which the string form of value is to be associated.
  414. * @param value value whose string form is to be associated with key.
  415. * @throws NullPointerException if key is <tt>null</tt>.
  416. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
  417. * <tt>MAX_KEY_LENGTH</tt>.
  418. * @throws IllegalStateException if this node (or an ancestor) has been
  419. * removed with the {@link #removeNode()} method.
  420. */
  421. public void putBoolean(String key, boolean value) {
  422. put(key, String.valueOf(value));
  423. }
  424. /**
  425. * Implements the <tt>getBoolean</tt> method as per the specification in
  426. * {@link Preferences#getBoolean(String,boolean)}.
  427. *
  428. * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
  429. * null)</tt>}. If the return value is non-null, it is compared with
  430. * <tt>"true"</tt> using {@link String#equalsIgnoreCase(String)}. If the
  431. * comparison returns <tt>true</tt>, this invocation returns
  432. * <tt>true</tt>. Otherwise, the original return value is compared with
  433. * <tt>"false"</tt>, again using {@link String#equalsIgnoreCase(String)}.
  434. * If the comparison returns <tt>true</tt>, this invocation returns
  435. * <tt>false</tt>. Otherwise, this invocation returns <tt>def</tt>.
  436. *
  437. * @param key key whose associated value is to be returned as a boolean.
  438. * @param def the value to be returned in the event that this
  439. * preference node has no value associated with <tt>key</tt>
  440. * or the associated value cannot be interpreted as a boolean.
  441. * @return the boolean value represented by the string associated with
  442. * <tt>key</tt> in this preference node, or <tt>def</tt> if the
  443. * associated value does not exist or cannot be interpreted as
  444. * a boolean.
  445. * @throws IllegalStateException if this node (or an ancestor) has been
  446. * removed with the {@link #removeNode()} method.
  447. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
  448. */
  449. public boolean getBoolean(String key, boolean def) {
  450. boolean result = def;
  451. String value = get(key, null);
  452. if (value != null) {
  453. if (value.equalsIgnoreCase("true"))
  454. result = true;
  455. else if (value.equalsIgnoreCase("false"))
  456. result = false;
  457. }
  458. return result;
  459. }
  460. /**
  461. * Implements the <tt>putFloat</tt> method as per the specification in
  462. * {@link Preferences#putFloat(String,float)}.
  463. *
  464. * <p>This implementation translates <tt>value</tt> to a string with
  465. * {@link Float#toString(float)} and invokes {@link #put(String,String)}
  466. * on the result.
  467. *
  468. * @param key key with which the string form of value is to be associated.
  469. * @param value value whose string form is to be associated with key.
  470. * @throws NullPointerException if key is <tt>null</tt>.
  471. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
  472. * <tt>MAX_KEY_LENGTH</tt>.
  473. * @throws IllegalStateException if this node (or an ancestor) has been
  474. * removed with the {@link #removeNode()} method.
  475. */
  476. public void putFloat(String key, float value) {
  477. put(key, Float.toString(value));
  478. }
  479. /**
  480. * Implements the <tt>getFloat</tt> method as per the specification in
  481. * {@link Preferences#getFloat(String,float)}.
  482. *
  483. * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
  484. * null)</tt>}. If the return value is non-null, the implementation
  485. * attempts to translate it to an <tt>float</tt> with
  486. * {@link Float#parseFloat(String)}. If the attempt succeeds, the return
  487. * value is returned by this method. Otherwise, <tt>def</tt> is returned.
  488. *
  489. * @param key key whose associated value is to be returned as a float.
  490. * @param def the value to be returned in the event that this
  491. * preference node has no value associated with <tt>key</tt>
  492. * or the associated value cannot be interpreted as a float.
  493. * @return the float value represented by the string associated with
  494. * <tt>key</tt> in this preference node, or <tt>def</tt> if the
  495. * associated value does not exist or cannot be interpreted as
  496. * a float.
  497. * @throws IllegalStateException if this node (or an ancestor) has been
  498. * removed with the {@link #removeNode()} method.
  499. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
  500. */
  501. public float getFloat(String key, float def) {
  502. float result = def;
  503. try {
  504. String value = get(key, null);
  505. if (value != null)
  506. result = Float.parseFloat(value);
  507. } catch (NumberFormatException e) {
  508. // Ignoring exception causes specified default to be returned
  509. }
  510. return result;
  511. }
  512. /**
  513. * Implements the <tt>putDouble</tt> method as per the specification in
  514. * {@link Preferences#putDouble(String,double)}.
  515. *
  516. * <p>This implementation translates <tt>value</tt> to a string with
  517. * {@link Double#toString(double)} and invokes {@link #put(String,String)}
  518. * on the result.
  519. *
  520. * @param key key with which the string form of value is to be associated.
  521. * @param value value whose string form is to be associated with key.
  522. * @throws NullPointerException if key is <tt>null</tt>.
  523. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
  524. * <tt>MAX_KEY_LENGTH</tt>.
  525. * @throws IllegalStateException if this node (or an ancestor) has been
  526. * removed with the {@link #removeNode()} method.
  527. */
  528. public void putDouble(String key, double value) {
  529. put(key, Double.toString(value));
  530. }
  531. /**
  532. * Implements the <tt>getDouble</tt> method as per the specification in
  533. * {@link Preferences#getDouble(String,double)}.
  534. *
  535. * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
  536. * null)</tt>}. If the return value is non-null, the implementation
  537. * attempts to translate it to an <tt>double</tt> with
  538. * {@link Double#parseDouble(String)}. If the attempt succeeds, the return
  539. * value is returned by this method. Otherwise, <tt>def</tt> is returned.
  540. *
  541. * @param key key whose associated value is to be returned as a double.
  542. * @param def the value to be returned in the event that this
  543. * preference node has no value associated with <tt>key</tt>
  544. * or the associated value cannot be interpreted as a double.
  545. * @return the double value represented by the string associated with
  546. * <tt>key</tt> in this preference node, or <tt>def</tt> if the
  547. * associated value does not exist or cannot be interpreted as
  548. * a double.
  549. * @throws IllegalStateException if this node (or an ancestor) has been
  550. * removed with the {@link #removeNode()} method.
  551. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
  552. */
  553. public double getDouble(String key, double def) {
  554. double result = def;
  555. try {
  556. String value = get(key, null);
  557. if (value != null)
  558. result = Double.parseDouble(value);
  559. } catch (NumberFormatException e) {
  560. // Ignoring exception causes specified default to be returned
  561. }
  562. return result;
  563. }
  564. /**
  565. * Implements the <tt>putByteArray</tt> method as per the specification in
  566. * {@link Preferences#putByteArray(String,byte[])}.
  567. *
  568. * @param key key with which the string form of value is to be associated.
  569. * @param value value whose string form is to be associated with key.
  570. * @throws NullPointerException if key or value is <tt>null</tt>.
  571. * @throws IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH
  572. * or if value.length exceeds MAX_VALUE_LENGTH*3/4.
  573. * @throws IllegalStateException if this node (or an ancestor) has been
  574. * removed with the {@link #removeNode()} method.
  575. */
  576. public void putByteArray(String key, byte[] value) {
  577. put(key, Base64.byteArrayToBase64(value));
  578. }
  579. /**
  580. * Implements the <tt>getByteArray</tt> method as per the specification in
  581. * {@link Preferences#getByteArray(String,byte[])}.
  582. *
  583. * @param key key whose associated value is to be returned as a byte array.
  584. * @param def the value to be returned in the event that this
  585. * preference node has no value associated with <tt>key</tt>
  586. * or the associated value cannot be interpreted as a byte array.
  587. * @return the byte array value represented by the string associated with
  588. * <tt>key</tt> in this preference node, or <tt>def</tt> if the
  589. * associated value does not exist or cannot be interpreted as
  590. * a byte array.
  591. * @throws IllegalStateException if this node (or an ancestor) has been
  592. * removed with the {@link #removeNode()} method.
  593. * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. (A
  594. * <tt>null</tt> value for <tt>def</tt> <i>is</i> permitted.)
  595. */
  596. public byte[] getByteArray(String key, byte[] def) {
  597. byte[] result = def;
  598. String value = get(key, null);
  599. try {
  600. if (value != null)
  601. result = Base64.base64ToByteArray(value);
  602. }
  603. catch (RuntimeException e) {
  604. // Ignoring exception causes specified default to be returned
  605. }
  606. return result;
  607. }
  608. /**
  609. * Implements the <tt>keys</tt> method as per the specification in
  610. * {@link Preferences#keys()}.
  611. *
  612. * <p>This implementation obtains this preference node's lock, checks that
  613. * the node has not been removed and invokes {@link #keysSpi()}.
  614. *
  615. * @return an array of the keys that have an associated value in this
  616. * preference node.
  617. * @throws BackingStoreException if this operation cannot be completed
  618. * due to a failure in the backing store, or inability to
  619. * communicate with it.
  620. * @throws IllegalStateException if this node (or an ancestor) has been
  621. * removed with the {@link #removeNode()} method.
  622. */
  623. public String[] keys() throws BackingStoreException {
  624. synchronized(lock) {
  625. if (removed)
  626. throw new IllegalStateException("Node has been removed.");
  627. return keysSpi();
  628. }
  629. }
  630. /**
  631. * Implements the <tt>children</tt> method as per the specification in
  632. * {@link Preferences#childrenNames()}.
  633. *
  634. * <p>This implementation obtains this preference node's lock, checks that
  635. * the node has not been removed, constructs a <tt>TreeSet</tt> initialized
  636. * to the names of children already cached (the children in this node's
  637. * "child-cache"), invokes {@link #childrenNamesSpi()}, and adds all of the
  638. * returned child-names into the set. The elements of the tree set are
  639. * dumped into a <tt>String</tt> array using the <tt>toArray</tt> method,
  640. * and this array is returned.
  641. *
  642. * @return the names of the children of this preference node.
  643. * @throws BackingStoreException if this operation cannot be completed
  644. * due to a failure in the backing store, or inability to
  645. * communicate with it.
  646. * @throws IllegalStateException if this node (or an ancestor) has been
  647. * removed with the {@link #removeNode()} method.
  648. * @see #cachedChildren()
  649. */
  650. public String[] childrenNames() throws BackingStoreException {
  651. synchronized(lock) {
  652. if (removed)
  653. throw new IllegalStateException("Node has been removed.");
  654. Set s = new TreeSet(kidCache.keySet());
  655. String[] kids = childrenNamesSpi();
  656. for(int i=0; i<kids.length; i++)
  657. s.add(kids[i]);
  658. return (String[]) s.toArray(EMPTY_STRING_ARRAY);
  659. }
  660. }
  661. private static final String[] EMPTY_STRING_ARRAY = new String[0];
  662. /**
  663. * Returns all known unremoved children of this node.
  664. *
  665. * @return all known unremoved children of this node.
  666. */
  667. protected final AbstractPreferences[] cachedChildren() {
  668. return (AbstractPreferences[]) kidCache.values().
  669. toArray(EMPTY_ABSTRACT_PREFS_ARRAY);
  670. }
  671. private static final AbstractPreferences[] EMPTY_ABSTRACT_PREFS_ARRAY
  672. = new AbstractPreferences[0];
  673. /**
  674. * Implements the <tt>parent</tt> method as per the specification in
  675. * {@link Preferences#parent()}.
  676. *
  677. * <p>This implementation obtains this preference node's lock, checks that
  678. * the node has not been removed and returns the parent value that was
  679. * passed to this node's constructor.
  680. *
  681. * @return the parent of this preference node.
  682. * @throws IllegalStateException if this node (or an ancestor) has been
  683. * removed with the {@link #removeNode()} method.
  684. */
  685. public Preferences parent() {
  686. synchronized(lock) {
  687. if (removed)
  688. throw new IllegalStateException("Node has been removed.");
  689. return parent;
  690. }
  691. }
  692. /**
  693. * Implements the <tt>node</tt> method as per the specification in
  694. * {@link Preferences#node(String)}.
  695. *
  696. * <p>This implementation obtains this preference node's lock and checks
  697. * that the node has not been removed. If <tt>path</tt> is <tt>""</tt>,
  698. * this node is returned; if <tt>path</tt> is <tt>"/"</tt>, this node's
  699. * root is returned. If the first character in <tt>path</tt> is
  700. * not <tt>'/'</tt>, the implementation breaks <tt>path</tt> into
  701. * tokens and recursively traverses the path from this node to the
  702. * named node, "consuming" a name and a slash from <tt>path</tt> at
  703. * each step of the traversal. At each step, the current node is locked
  704. * and the node's child-cache is checked for the named node. If it is
  705. * not found, the name is checked to make sure its length does not
  706. * exceed <tt>MAX_NAME_LENGTH</tt>. Then the {@link #childSpi(String)}
  707. * method is invoked, and the result stored in this node's child-cache.
  708. * If the newly created <tt>Preferences</tt> object's {@link #newNode}
  709. * field is <tt>true</tt> and there are any node change listeners,
  710. * a notification event is enqueued for processing by the event dispatch
  711. * thread.
  712. *
  713. * <p>When there are no more tokens, the last value found in the
  714. * child-cache or returned by <tt>childSpi</tt> is returned by this
  715. * method. If during the traversal, two <tt>"/"</tt> tokens occur
  716. * consecutively, or the final token is <tt>"/"</tt> (rather than a name),
  717. * an appropriate <tt>IllegalArgumentException</tt> is thrown.
  718. *
  719. * <p> If the first character of <tt>path</tt> is <tt>'/'</tt>
  720. * (indicating an absolute path name name) this preference node's
  721. * lock is dropped prior to breaking <tt>path</tt> into tokens, and
  722. * this method recursively traverses the path starting from the root
  723. * (rather than starting from this node). The traversal is otherwise
  724. * identical to the one described for relative path names. Dropping
  725. * the lock on this node prior to commencing the traversal at the root
  726. * node is essential to avoid the possibility of deadlock, as per the
  727. * {@link #lock locking invariant}.
  728. *
  729. * @param path the path name of the preference node to return.
  730. * @return the specified preference node.
  731. * @throws IllegalArgumentException if the path name is invalid (i.e.,
  732. * it contains multiple consecutive slash characters, or ends
  733. * with a slash character and is more than one character long).
  734. * @throws IllegalStateException if this node (or an ancestor) has been
  735. * removed with the {@link #removeNode()} method.
  736. */
  737. public Preferences node(String path) {
  738. synchronized(lock) {
  739. if (removed)
  740. throw new IllegalStateException("Node has been removed.");
  741. if (path.equals(""))
  742. return this;
  743. if (path.equals("/"))
  744. return root;
  745. if (path.charAt(0) != '/')
  746. return node(new StringTokenizer(path, "/", true));
  747. }
  748. // Absolute path. Note that we've dropped our lock to avoid deadlock
  749. return root.node(new StringTokenizer(path.substring(1), "/", true));
  750. }
  751. /**
  752. * tokenizer contains <name> {'/' <name>}*
  753. */
  754. private Preferences node(StringTokenizer path) {
  755. String token = path.nextToken();
  756. if (token.equals("/")) // Check for consecutive slashes
  757. throw new IllegalArgumentException("Consecutive slashes in path");
  758. synchronized(lock) {
  759. AbstractPreferences child=(AbstractPreferences)kidCache.get(token);
  760. if (child == null) {
  761. if (token.length() > MAX_NAME_LENGTH)
  762. throw new IllegalArgumentException(
  763. "Node name " + token + " too long");
  764. child = childSpi(token);
  765. if (child.newNode)
  766. enqueueNodeAddedEvent(child);
  767. kidCache.put(token, child);
  768. }
  769. if (!path.hasMoreTokens())
  770. return child;
  771. path.nextToken(); // Consume slash
  772. if (!path.hasMoreTokens())
  773. throw new IllegalArgumentException("Path ends with slash");
  774. return child.node(path);
  775. }
  776. }
  777. /**
  778. * Implements the <tt>nodeExists</tt> method as per the specification in
  779. * {@link Preferences#nodeExists(String)}.
  780. *
  781. * <p>This implementation is very similar to {@link #node(String)},
  782. * except that {@link #getChild(String)} is used instead of {@link
  783. * #childSpi(String)}.
  784. *
  785. * @param path the path name of the node whose existence is to be checked.
  786. * @return true if the specified node exists.
  787. * @throws BackingStoreException if this operation cannot be completed
  788. * due to a failure in the backing store, or inability to
  789. * communicate with it.
  790. * @throws IllegalArgumentException if the path name is invalid (i.e.,
  791. * it contains multiple consecutive slash characters, or ends
  792. * with a slash character and is more than one character long).
  793. * @throws IllegalStateException if this node (or an ancestor) has been
  794. * removed with the {@link #removeNode()} method and
  795. * <tt>pathname</tt> is not the empty string (<tt>""</tt>).
  796. */
  797. public boolean nodeExists(String path)
  798. throws BackingStoreException
  799. {
  800. synchronized(lock) {
  801. if (path.equals(""))
  802. return !removed;
  803. if (removed)
  804. throw new IllegalStateException("Node has been removed.");
  805. if (path.equals("/"))
  806. return true;
  807. if (path.charAt(0) != '/')
  808. return nodeExists(new StringTokenizer(path, "/", true));
  809. }
  810. // Absolute path. Note that we've dropped our lock to avoid deadlock
  811. return root.nodeExists(new StringTokenizer(path.substring(1), "/",
  812. true));
  813. }
  814. /**
  815. * tokenizer contains <name> {'/' <name>}*
  816. */
  817. private boolean nodeExists(StringTokenizer path)
  818. throws BackingStoreException
  819. {
  820. String token = path.nextToken();
  821. if (token.equals("/")) // Check for consecutive slashes
  822. throw new IllegalArgumentException("Consecutive slashes in path");
  823. synchronized(lock) {
  824. AbstractPreferences child=(AbstractPreferences)kidCache.get(token);
  825. if (child == null)
  826. child = getChild(token);
  827. if (child==null)
  828. return false;
  829. if (!path.hasMoreTokens())
  830. return true;
  831. path.nextToken(); // Consume slash
  832. if (!path.hasMoreTokens())
  833. throw new IllegalArgumentException("Path ends with slash");
  834. return child.nodeExists(path);
  835. }
  836. }
  837. /**
  838. * Implements the <tt>removeNode()</tt> method as per the specification in
  839. * {@link Preferences#removeNode()}.
  840. *
  841. * <p>This implementation checks to see that this node is the root; if so,
  842. * it throws an appropriate exception. Then, it locks this node's parent,
  843. * and calls a recursive helper method that traverses the subtree rooted at
  844. * this node. The recursive method locks the node on which it was called,
  845. * checks that it has not already been removed, and then ensures that all
  846. * of its children are cached: The {@link #childrenNamesSpi()} method is
  847. * invoked and each returned child name is checked for containment in the
  848. * child-cache. If a child is not already cached, the {@link
  849. * #childSpi(String)} method is invoked to create a <tt>Preferences</tt>
  850. * instance for it, and this instance is put into the child-cache. Then
  851. * the helper method calls itself recursively on each node contained in its
  852. * child-cache. Next, it invokes {@link #removeNodeSpi()}, marks itself
  853. * as removed, and removes itself from its parent's child-cache. Finally,
  854. * if there are any node change listeners, it enqueues a notification
  855. * event for processing by the event dispatch thread.
  856. *
  857. * <p>Note that the helper method is always invoked with all ancestors up
  858. * to the "closest non-removed ancestor" locked.
  859. *
  860. * @throws IllegalStateException if this node (or an ancestor) has already
  861. * been removed with the {@link #removeNode()} method.
  862. * @throws UnsupportedOperationException if this method is invoked on
  863. * the root node.
  864. * @throws BackingStoreException if this operation cannot be completed
  865. * due to a failure in the backing store, or inability to
  866. * communicate with it.
  867. */
  868. public void removeNode() throws BackingStoreException {
  869. if (this==root)
  870. throw new UnsupportedOperationException("Can't remove the root!");
  871. synchronized(parent.lock) {
  872. removeNode2();
  873. parent.kidCache.remove(name);
  874. }
  875. }
  876. /*
  877. * Called with locks on all nodes on path from parent of "removal root"
  878. * to this (including the former but excluding the latter).
  879. */
  880. private void removeNode2() throws BackingStoreException {
  881. synchronized(lock) {
  882. if (removed)
  883. throw new IllegalStateException("Node already removed.");
  884. // Ensure that all children are cached
  885. String[] kidNames = childrenNamesSpi();
  886. for (int i=0; i<kidNames.length; i++)
  887. if (!kidCache.containsKey(kidNames[i]))
  888. kidCache.put(kidNames[i], childSpi(kidNames[i]));
  889. // Recursively remove all cached children
  890. for (Iterator i=kidCache.values().iterator(); i.hasNext(); )
  891. ((AbstractPreferences)i.next()).removeNode2();
  892. kidCache.clear();
  893. // Now we have no descendants - it's time to die!
  894. removeNodeSpi();
  895. removed = true;
  896. parent.enqueueNodeRemovedEvent(this);
  897. }
  898. }
  899. /**
  900. * Implements the <tt>name</tt> method as per the specification in
  901. * {@link Preferences#name()}.
  902. *
  903. * <p>This implementation merely returns the name that was
  904. * passed to this node's constructor.
  905. *
  906. * @return this preference node's name, relative to its parent.
  907. */
  908. public String name() {
  909. return name;
  910. }
  911. /**
  912. * Implements the <tt>absolutePath</tt> method as per the specification in
  913. * {@link Preferences#absolutePath()}.
  914. *
  915. * <p>This implementation merely returns the absolute path name that
  916. * was computed at the time that this node was constructed (based on
  917. * the name that was passed to this node's constructor, and the names
  918. * that were passed to this node's ancestors' constructors).
  919. *
  920. * @return this preference node's absolute path name.
  921. */
  922. public String absolutePath() {
  923. return absolutePath;
  924. }
  925. /**
  926. * Implements the <tt>isUserNode</tt> method as per the specification in
  927. * {@link Preferences#isUserNode()}.
  928. *
  929. * <p>This implementation compares this node's root node (which is stored
  930. * in a private field) with the value returned by
  931. * {@link Preferences#userRoot()}. If the two object references are
  932. * identical, this method returns true.
  933. *
  934. * @return <tt>true</tt> if this preference node is in the user
  935. * preference tree, <tt>false</tt> if it's in the system
  936. * preference tree.
  937. */
  938. public boolean isUserNode() {
  939. Boolean result = (Boolean)
  940. AccessController.doPrivileged( new PrivilegedAction() {
  941. public Object run() {
  942. return new Boolean(root == Preferences.userRoot());
  943. }
  944. });
  945. return result.booleanValue();
  946. }
  947. public void addPreferenceChangeListener(PreferenceChangeListener pcl) {
  948. if (pcl==null)
  949. throw new NullPointerException("Change listener is null.");
  950. synchronized(lock) {
  951. if (removed)
  952. throw new IllegalStateException("Node has been removed.");
  953. // Copy-on-write
  954. PreferenceChangeListener[] old = prefListeners;
  955. prefListeners = new PreferenceChangeListener[old.length + 1];
  956. System.arraycopy(old, 0, prefListeners, 0, old.length);
  957. prefListeners[old.length] = pcl;
  958. }
  959. startEventDispatchThreadIfNecessary();
  960. }
  961. public void removePreferenceChangeListener(PreferenceChangeListener pcl) {
  962. synchronized(lock) {
  963. if (removed)
  964. throw new IllegalStateException("Node has been removed.");
  965. if ((prefListeners == null) || (prefListeners.length == 0))
  966. throw new IllegalArgumentException("Listener not registered.");
  967. // Copy-on-write
  968. PreferenceChangeListener[] newPl =
  969. new PreferenceChangeListener[prefListeners.length - 1];
  970. int i = 0;
  971. while (i < newPl.length && prefListeners[i] != pcl)
  972. newPl[i] = prefListeners[i++];
  973. if (i == newPl.length && prefListeners[i] != pcl)
  974. throw new IllegalArgumentException("Listener not registered.");
  975. while (i < newPl.length)
  976. newPl[i] = prefListeners[++i];
  977. prefListeners = newPl;
  978. }
  979. }
  980. public void addNodeChangeListener(NodeChangeListener ncl) {
  981. if (ncl==null)
  982. throw new NullPointerException("Change listener is null.");
  983. synchronized(lock) {
  984. if (removed)
  985. throw new IllegalStateException("Node has been removed.");
  986. // Copy-on-write
  987. if (nodeListeners == null) {
  988. nodeListeners = new NodeChangeListener[1];
  989. nodeListeners[0] = ncl;
  990. } else {
  991. NodeChangeListener[] old = nodeListeners;
  992. nodeListeners = new NodeChangeListener[old.length + 1];
  993. System.arraycopy(old, 0, nodeListeners, 0, old.length);
  994. nodeListeners[old.length] = ncl;
  995. }
  996. }
  997. startEventDispatchThreadIfNecessary();
  998. }
  999. public void removeNodeChangeListener(NodeChangeListener ncl) {
  1000. synchronized(lock) {
  1001. if (removed)
  1002. throw new IllegalStateException("Node has been removed.");
  1003. if ((nodeListeners == null) || (nodeListeners.length == 0))
  1004. throw new IllegalArgumentException("Listener not registered.");
  1005. // Copy-on-write
  1006. NodeChangeListener[] newNl =
  1007. new NodeChangeListener[nodeListeners.length - 1];
  1008. int i = 0;
  1009. while (i < nodeListeners.length && nodeListeners[i] != ncl)
  1010. newNl[i] = nodeListeners[i++];
  1011. if (i == nodeListeners.length)
  1012. throw new IllegalArgumentException("Listener not registered.");
  1013. while (i < newNl.length)
  1014. newNl[i] = nodeListeners[++i];
  1015. nodeListeners = newNl;
  1016. }
  1017. }
  1018. // "SPI" METHODS
  1019. /**
  1020. * Put the given key-value association into this preference node. It is
  1021. * guaranteed that <tt>key</tt> and <tt>value</tt> are non-null and of
  1022. * legal length. Also, it is guaranteed that this node has not been
  1023. * removed. (The implementor needn't check for any of these things.)
  1024. *
  1025. * <p>This method is invoked with the lock on this node held.
  1026. */
  1027. protected abstract void putSpi(String key, String value);
  1028. /**
  1029. * Return the value associated with the specified key at this preference
  1030. * node, or <tt>null</tt> if there is no association for this key, or the
  1031. * association cannot be determined at this time. It is guaranteed that
  1032. * <tt>key</tt> is non-null. Also, it is guaranteed that this node has
  1033. * not been removed. (The implementor needn't check for either of these
  1034. * things.)
  1035. *
  1036. * <p> Generally speaking, this method should not throw an exception
  1037. * under any circumstances. If, however, if it does throw an exception,
  1038. * the exception will be intercepted and treated as a <tt>null</tt>
  1039. * return value.
  1040. *
  1041. * <p>This method is invoked with the lock on this node held.
  1042. *
  1043. * @return the value associated with the specified key at this preference
  1044. * node, or <tt>null</tt> if there is no association for this
  1045. * key, or the association cannot be determined at this time.
  1046. */
  1047. protected abstract String getSpi(String key);
  1048. /**
  1049. * Remove the association (if any) for the specified key at this
  1050. * preference node. It is guaranteed that <tt>key</tt> is non-null.
  1051. * Also, it is guaranteed that this node has not been removed.
  1052. * (The implementor needn't check for either of these things.)
  1053. *
  1054. * <p>This method is invoked with the lock on this node held.
  1055. */
  1056. protected abstract void removeSpi(String key);
  1057. /**
  1058. * Removes this preference node, invalidating it and any preferences that
  1059. * it contains. The named child will have no descendants at the time this
  1060. * invocation is made (i.e., the {@link Preferences#removeNode()} method
  1061. * invokes this method repeatedly in a bottom-up fashion, removing each of
  1062. * a node's descendants before removing the node itself).
  1063. *
  1064. * <p>This method is invoked with the lock held on this node and its
  1065. * parent (and all ancestors that are being removed as a
  1066. * result of a single invocation to {@link Preferences#removeNode()}).
  1067. *
  1068. * <p>The removal of a node needn't become persistent until the
  1069. * <tt>flush</tt> method is invoked on this node (or an ancestor).
  1070. *
  1071. * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
  1072. * will propagate out beyond the enclosing {@link #removeNode()}
  1073. * invocation.
  1074. *
  1075. * @throws BackingStoreException if this operation cannot be completed
  1076. * due to a failure in the backing store, or inability to
  1077. * communicate with it.
  1078. */
  1079. protected abstract void removeNodeSpi() throws BackingStoreException;
  1080. /**
  1081. * Returns all of the keys that have an associated value in this
  1082. * preference node. (The returned array will be of size zero if
  1083. * this node has no preferences.) It is guaranteed that this node has not
  1084. * been removed.
  1085. *
  1086. * <p>This method is invoked with the lock on this node held.
  1087. *
  1088. * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
  1089. * will propagate out beyond the enclosing {@link #keys()} invocation.
  1090. *
  1091. * @return an array of the keys that have an associated value in this
  1092. * preference node.
  1093. * @throws BackingStoreException if this operation cannot be completed
  1094. * due to a failure in the backing store, or inability to
  1095. * communicate with it.
  1096. */
  1097. protected abstract String[] keysSpi() throws BackingStoreException;
  1098. /**
  1099. * Returns the names of the children of this preference node. (The
  1100. * returned array will be of size zero if this node has no children.)
  1101. * This method need not return the names of any nodes already cached,
  1102. * but may do so without harm.
  1103. *
  1104. * <p>This method is invoked with the lock on this node held.
  1105. *
  1106. * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
  1107. * will propagate out beyond the enclosing {@link #childrenNames()}
  1108. * invocation.
  1109. *
  1110. * @return an array containing the names of the children of this
  1111. * preference node.
  1112. * @throws BackingStoreException if this operation cannot be completed
  1113. * due to a failure in the backing store, or inability to
  1114. * communicate with it.
  1115. */
  1116. protected abstract String[] childrenNamesSpi()
  1117. throws BackingStoreException;
  1118. /**
  1119. * Returns the named child if it exists, or <tt>null</tt> if it does not.
  1120. * It is guaranteed that <tt>nodeName</tt> is non-null, non-empty,
  1121. * does not contain the slash character ('/'), and is no longer than
  1122. * {@link #MAX_NAME_LENGTH} characters. Also, it is guaranteed
  1123. * that this node has not been removed. (The implementor needn't check
  1124. * for any of these things if he chooses to override this method.)
  1125. *
  1126. * <p>Finally, it is guaranteed that the named node has not been returned
  1127. * by a previous invocation of this method or {@link #childSpi} after the
  1128. * last time that it was removed. In other words, a cached value will
  1129. * always be used in preference to invoking this method. (The implementor
  1130. * needn't maintain his own cache of previously returned children if he
  1131. * chooses to override this method.)
  1132. *
  1133. * <p>This implementation obtains this preference node's lock, invokes
  1134. * {@link #childrenNames()} to get an array of the names of this node's
  1135. * children, and iterates over the array comparing the name of each child
  1136. * with the specified node name. If a child node has the correct name,
  1137. * the {@link #childSpi(String)} method is invoked and the resulting
  1138. * node is returned. If the iteration completes without finding the
  1139. * specified name, <tt>null</tt> is returned.
  1140. *
  1141. * @param nodeName name of the child to be searched for.
  1142. * @return the named child if it exists, or null if it does not.
  1143. * @throws BackingStoreException if this operation cannot be completed
  1144. * due to a failure in the backing store, or inability to
  1145. * communicate with it.
  1146. */
  1147. protected AbstractPreferences getChild(String nodeName)
  1148. throws BackingStoreException {
  1149. synchronized(lock) {
  1150. // assert kidCache.get(nodeName)==null;
  1151. String[] kidNames = childrenNames();
  1152. for (int i=0; i<kidNames.length; i++)
  1153. if (kidNames[i].equals(nodeName))
  1154. return childSpi(kidNames[i]);
  1155. }
  1156. return null;
  1157. }
  1158. /**
  1159. * Returns the named child of this preference node, creating it if it does
  1160. * not already exist. It is guaranteed that <tt>name</tt> is non-null,
  1161. * non-empty, does not contain the slash character ('/'), and is no longer
  1162. * than {@link #MAX_NAME_LENGTH} characters. Also, it is guaranteed that
  1163. * this node has not been removed. (The implementor needn't check for any
  1164. * of these things.)
  1165. *
  1166. * <p>Finally, it is guaranteed that the named node has not been returned
  1167. * by a previous invocation of this method or {@link #getChild(String)}
  1168. * after the last time that it was removed. In other words, a cached
  1169. * value will always be used in preference to invoking this method.
  1170. * Subclasses need not maintain their own cache of previously returned
  1171. * children.
  1172. *
  1173. * <p>The implementer must ensure that the returned node has not been
  1174. * removed. If a like-named child of this node was previously removed, the
  1175. * implementer must return a newly constructed <tt>AbstractPreferences</tt>
  1176. * node; once removed, an <tt>AbstractPreferences</tt> node
  1177. * cannot be "resuscitated."
  1178. *
  1179. * <p>If this method causes a node to be created, this node is not
  1180. * guaranteed to be persistent until the <tt>flush</tt> method is
  1181. * invoked on this node or one of its ancestors (or descendants).
  1182. *
  1183. * <p>This method is invoked with the lock on this node held.
  1184. *
  1185. * @param name The name of the child node to return, relative to
  1186. * this preference node.
  1187. * @return The named child node.
  1188. */
  1189. protected abstract AbstractPreferences childSpi(String name);
  1190. /**
  1191. * Returns the absolute path name of this preferences node.
  1192. */
  1193. public String toString() {
  1194. return (this.isUserNode() ? "User" : "System") +
  1195. " Preference Node: " + this.absolutePath();
  1196. }
  1197. /**
  1198. * Implements the <tt>sync</tt> method as per the specification in
  1199. * {@link Preferences#sync()}.
  1200. *
  1201. * <p>This implementation calls a recursive helper method that locks this
  1202. * node, invokes syncSpi() on it, unlocks this node, and recursively
  1203. * invokes this method on each "cached child." A cached child is a child
  1204. * of this node that has been created in this VM and not subsequently
  1205. * removed. In effect, this method does a depth first traversal of the
  1206. * "cached subtree" rooted at this node, calling syncSpi() on each node in
  1207. * the subTree while only that node is locked. Note that syncSpi() is
  1208. * invoked top-down.
  1209. *
  1210. * @throws BackingStoreException if this operation cannot be completed
  1211. * due to a failure in the backing store, or inability to
  1212. * communicate with it.
  1213. * @throws IllegalStateException if this node (or an ancestor) has been
  1214. * removed with the {@link #removeNode()} method.
  1215. * @see #flush()
  1216. */
  1217. public void sync() throws BackingStoreException {
  1218. sync2();
  1219. }
  1220. private void sync2() throws BackingStoreException {
  1221. AbstractPreferences[] cachedKids;
  1222. synchronized(lock) {
  1223. if (removed)
  1224. throw new IllegalStateException("Node has been removed");
  1225. syncSpi();
  1226. cachedKids = cachedChildren();
  1227. }
  1228. for (int i=0; i<cachedKids.length; i++)
  1229. cachedKids[i].sync2();
  1230. }
  1231. /**
  1232. * This method is invoked with this node locked. The contract of this
  1233. * method is to synchronize any cached preferences stored at this node
  1234. * with any stored in the backing store. (It is perfectly possible that
  1235. * this node does not exist on the backing store, either because it has
  1236. * been deleted by another VM, or because it has not yet been created.)
  1237. * Note that this method should <i>not</i> synchronize the preferences in
  1238. * any subnodes of this node. If the backing store naturally syncs an
  1239. * entire subtree at once, the implementer is encouraged to override
  1240. * sync(), rather than merely overriding this method.
  1241. *
  1242. * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
  1243. * will propagate out beyond the enclosing {@link #sync()} invocation.
  1244. *
  1245. * @throws BackingStoreException if this operation cannot be completed
  1246. * due to a failure in the backing store, or inability to
  1247. * communicate with it.
  1248. */
  1249. protected abstract void syncSpi() throws BackingStoreException;
  1250. /**
  1251. * Implements the <tt>flush</tt> method as per the specification in
  1252. * {@link Preferences#flush()}.
  1253. *
  1254. * <p>This implementation calls a recursive helper method that locks this
  1255. * node, invokes flushSpi() on it, unlocks this node, and recursively
  1256. * invokes this method on each "cached child." A cached child is a child
  1257. * of this node that has been created in this VM and not subsequently
  1258. * removed. In effect, this method does a depth first traversal of the
  1259. * "cached subtree" rooted at this node, calling flushSpi() on each node in
  1260. * the subTree while only that node is locked. Note that flushSpi() is
  1261. * invoked top-down.
  1262. *
  1263. * <p> If this method is invoked on a node that has been removed with
  1264. * the {@link #removeNode()} method, flushSpi() is invoked on this node,
  1265. * but not on others.
  1266. *
  1267. * @throws BackingStoreException if this operation cannot be completed
  1268. * due to a failure in the backing store, or inability to
  1269. * communicate with it.
  1270. * @see #flush()
  1271. */
  1272. public void flush() throws BackingStoreException {
  1273. flush2();
  1274. }
  1275. private void flush2() throws BackingStoreException {
  1276. AbstractPreferences[] cachedKids;
  1277. synchronized(lock) {
  1278. flushSpi();
  1279. if(removed)
  1280. return;
  1281. cachedKids = cachedChildren();
  1282. }
  1283. for (int i = 0; i < cachedKids.length; i++)
  1284. cachedKids[i].flush2();
  1285. }
  1286. /**
  1287. * This method is invoked with this node locked. The contract of this
  1288. * method is to force any cached changes in the contents of this
  1289. * preference node to the backing store, guaranteeing their persistence.
  1290. * (It is perfectly possible that this node does not exist on the backing
  1291. * store, either because it has been deleted by another VM, or because it
  1292. * has not yet been created.) Note that this method should <i>not</i>
  1293. * flush the preferences in any subnodes of this node. If the backing
  1294. * store naturally flushes an entire subtree at once, the implementer is
  1295. * encouraged to override flush(), rather than merely overriding this
  1296. * method.
  1297. *
  1298. * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
  1299. * will propagate out beyond the enclosing {@link #flush()} invocation.
  1300. *
  1301. * @throws BackingStoreException if this operation cannot be completed
  1302. * due to a failure in the backing store, or inability to
  1303. * communicate with it.
  1304. */
  1305. protected abstract void flushSpi() throws BackingStoreException;
  1306. /**
  1307. * Returns <tt>true</tt> iff this node (or an ancestor) has been
  1308. * removed with the {@link #removeNode()} method. This method
  1309. * locks this node prior to returning the contents of the private
  1310. * field used to track this state.
  1311. *
  1312. * @return <tt>true</tt> iff this node (or an ancestor) has been
  1313. * removed with the {@link #removeNode()} method.
  1314. */
  1315. protected boolean isRemoved() {
  1316. synchronized(lock) {
  1317. return removed;
  1318. }
  1319. }
  1320. /**
  1321. * Queue of pending notification events. When a preference or node
  1322. * change event for which there are one or more listeners occurs,
  1323. * it is placed on this queue and the queue is notified. A background
  1324. * thread waits on this queue and delivers the events. This decouples
  1325. * event delivery from preference activity, greatly simplifying
  1326. * locking and reducing opportunity for deadlock.
  1327. */
  1328. private static final List eventQueue = new LinkedList();
  1329. /**
  1330. * These two classes are used to distinguish NodeChangeEvents on
  1331. * eventQueue so the event dispatch thread knows whether to call
  1332. * childAdded or childRemoved.
  1333. */
  1334. private class NodeAddedEvent extends NodeChangeEvent {
  1335. private static final long serialVersionUID = -6743557530157328528L;
  1336. NodeAddedEvent(Preferences parent, Preferences child) {
  1337. super(parent, child);
  1338. }
  1339. }
  1340. private class NodeRemovedEvent extends NodeChangeEvent {
  1341. private static final long serialVersionUID = 8735497392918824837L;
  1342. NodeRemovedEvent(Preferences parent, Preferences child) {
  1343. super(parent, child);
  1344. }
  1345. }
  1346. /**
  1347. * A single background thread ("the event notification thread") monitors
  1348. * the event queue and delivers events that are placed on the queue.
  1349. */
  1350. private static class EventDispatchThread extends Thread {
  1351. public void run() {
  1352. while(true) {
  1353. // Wait on eventQueue till an event is present
  1354. EventObject event = null;
  1355. synchronized(eventQueue) {
  1356. try {
  1357. while (eventQueue.isEmpty())
  1358. eventQueue.wait();
  1359. event = (EventObject) eventQueue.remove(0);
  1360. } catch (InterruptedException e) {
  1361. // XXX Log "Event dispatch thread interrupted. Exiting"
  1362. return;
  1363. }
  1364. }
  1365. // Now we have event & hold no locks; deliver evt to listeners
  1366. AbstractPreferences src=(AbstractPreferences)event.getSource();
  1367. if (event instanceof PreferenceChangeEvent) {
  1368. PreferenceChangeEvent pce = (PreferenceChangeEvent)event;
  1369. PreferenceChangeListener[] listeners = src.prefListeners();
  1370. for (int i=0; i<listeners.length; i++)
  1371. listeners[i].preferenceChange(pce);
  1372. } else {
  1373. NodeChangeEvent nce = (NodeChangeEvent)event;
  1374. NodeChangeListener[] listeners = src.nodeListeners();
  1375. if (nce instanceof NodeAddedEvent) {
  1376. for (int i=0; i<listeners.length; i++)
  1377. listeners[i].childAdded(nce);
  1378. } else {
  1379. // assert nce instanceof NodeRemovedEvent;
  1380. for (int i=0; i<listeners.length; i++)
  1381. listeners[i].childRemoved(nce);
  1382. }
  1383. }
  1384. }
  1385. }
  1386. }
  1387. private static Thread eventDispatchThread = null;
  1388. /**
  1389. * This method starts the event dispatch thread the first time it
  1390. * is called. The event dispatch thread will be started only
  1391. * if someone registers a listener.
  1392. */
  1393. private static synchronized void startEventDispatchThreadIfNecessary() {
  1394. if (eventDispatchThread == null) {
  1395. // XXX Log "Starting event dispatch thread"
  1396. eventDispatchThread = new EventDispatchThread();
  1397. eventDispatchThread.setDaemon(true);
  1398. eventDispatchThread.start();
  1399. }
  1400. }
  1401. /**
  1402. * Return this node's preference/node change listeners. Even though
  1403. * we're using a copy-on-write lists, we use synchronized accessors to
  1404. * ensure information transmission from the writing thread to the
  1405. * reading thread.
  1406. */
  1407. PreferenceChangeListener[] prefListeners() {
  1408. synchronized(lock) {
  1409. return prefListeners;
  1410. }
  1411. }
  1412. NodeChangeListener[] nodeListeners() {
  1413. synchronized(lock) {
  1414. return nodeListeners;
  1415. }
  1416. }
  1417. /**
  1418. * Enqueue a preference change event for delivery to registered
  1419. * preference change listeners unless there are no registered
  1420. * listeners. Invoked with this.lock held.
  1421. */
  1422. private void enqueuePreferenceChangeEvent(String key, String newValue) {
  1423. if (prefListeners.length != 0) {
  1424. synchronized(eventQueue) {
  1425. eventQueue.add(new PreferenceChangeEvent(this, key, newValue));
  1426. eventQueue.notify();
  1427. }
  1428. }
  1429. }
  1430. /**
  1431. * Enqueue a "node added" event for delivery to registered node change
  1432. * listeners unless there are no registered listeners. Invoked with
  1433. * this.lock held.
  1434. */
  1435. private void enqueueNodeAddedEvent(Preferences child) {
  1436. if (nodeListeners.length != 0) {
  1437. synchronized(eventQueue) {
  1438. eventQueue.add(new NodeAddedEvent(this, child));
  1439. eventQueue.notify();
  1440. }
  1441. }
  1442. }
  1443. /**
  1444. * Enqueue a "node removed" event for delivery to registered node change
  1445. * listeners unless there are no registered listeners. Invoked with
  1446. * this.lock held.
  1447. */
  1448. private void enqueueNodeRemovedEvent(Preferences child) {
  1449. if (nodeListeners.length != 0) {
  1450. synchronized(eventQueue) {
  1451. eventQueue.add(new NodeRemovedEvent(this, child));
  1452. eventQueue.notify();
  1453. }
  1454. }
  1455. }
  1456. /**
  1457. * Implements the <tt>exportNode</tt> method as per the specification in
  1458. * {@link Preferences#exportNode(OutputStream)}.
  1459. *
  1460. * @param os the output stream on which to emit the XML document.
  1461. * @throws IOException if writing to the specified output stream
  1462. * results in an <tt>IOException</tt>.
  1463. * @throws BackingStoreException if preference data cannot be read from
  1464. * backing store.
  1465. */
  1466. public void exportNode(OutputStream os)
  1467. throws IOException, BackingStoreException
  1468. {
  1469. XmlSupport.export(os, this, false);
  1470. }
  1471. /**
  1472. * Implements the <tt>exportSubtree</tt> method as per the specification in
  1473. * {@link Preferences#exportSubtree(OutputStream)}.
  1474. *
  1475. * @param os the output stream on which to emit the XML document.
  1476. * @throws IOException if writing to the specified output stream
  1477. * results in an <tt>IOException</tt>.
  1478. * @throws BackingStoreException if preference data cannot be read from
  1479. * backing store.
  1480. */
  1481. public void exportSubtree(OutputStream os)
  1482. throws IOException, BackingStoreException
  1483. {
  1484. XmlSupport.export(os, this, true);
  1485. }
  1486. }