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