1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 2000, 2010, 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
27package java.util.prefs;
28
29import java.util.*;
30import java.io.*;
31import java.security.AccessController;
32import java.security.PrivilegedAction;
33// These imports needed only as a workaround for a JavaDoc bug
34import java.lang.Integer;
35import java.lang.Long;
36import java.lang.Float;
37import 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 */
124public 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     */
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     */
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     */
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     */
309    public void remove(String key) {
310        synchronized(lock) {
311            if (removed)
312                throw new IllegalStateException("Node has been removed.");
313
314            removeSpi(key);
315            enqueuePreferenceChangeEvent(key, null);
316        }
317    }
318
319    /**
320     * Implements the <tt>clear</tt> method as per the specification in
321     * {@link Preferences#clear()}.
322     *
323     * <p>This implementation obtains this preference node's lock,
324     * invokes {@link #keys()} to obtain an array of keys, and
325     * iterates over the array invoking {@link #remove(String)} on each key.
326     *
327     * @throws BackingStoreException if this operation cannot be completed
328     *         due to a failure in the backing store, or inability to
329     *         communicate with it.
330     * @throws IllegalStateException if this node (or an ancestor) has been
331     *         removed with the {@link #removeNode()} method.
332     */
333    public void clear() throws BackingStoreException {
334        synchronized(lock) {
335            String[] keys = keys();
336            for (int i=0; i<keys.length; i++)
337                remove(keys[i]);
338        }
339    }
340
341    /**
342     * Implements the <tt>putInt</tt> method as per the specification in
343     * {@link Preferences#putInt(String,int)}.
344     *
345     * <p>This implementation translates <tt>value</tt> to a string with
346     * {@link Integer#toString(int)} and invokes {@link #put(String,String)}
347     * on the result.
348     *
349     * @param key key with which the string form of value is to be associated.
350     * @param value value whose string form is to be associated with key.
351     * @throws NullPointerException if key is <tt>null</tt>.
352     * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
353     *         <tt>MAX_KEY_LENGTH</tt>.
354     * @throws IllegalStateException if this node (or an ancestor) has been
355     *         removed with the {@link #removeNode()} method.
356     */
357    public void putInt(String key, int value) {
358        put(key, Integer.toString(value));
359    }
360
361    /**
362     * Implements the <tt>getInt</tt> method as per the specification in
363     * {@link Preferences#getInt(String,int)}.
364     *
365     * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
366     * null)</tt>}.  If the return value is non-null, the implementation
367     * attempts to translate it to an <tt>int</tt> with
368     * {@link Integer#parseInt(String)}.  If the attempt succeeds, the return
369     * value is returned by this method.  Otherwise, <tt>def</tt> is returned.
370     *
371     * @param key key whose associated value is to be returned as an int.
372     * @param def the value to be returned in the event that this
373     *        preference node has no value associated with <tt>key</tt>
374     *        or the associated value cannot be interpreted as an int.
375     * @return the int value represented by the string associated with
376     *         <tt>key</tt> in this preference node, or <tt>def</tt> if the
377     *         associated value does not exist or cannot be interpreted as
378     *         an int.
379     * @throws IllegalStateException if this node (or an ancestor) has been
380     *         removed with the {@link #removeNode()} method.
381     * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
382     */
383    public int getInt(String key, int def) {
384        int result = def;
385        try {
386            String value = get(key, null);
387            if (value != null)
388                result = Integer.parseInt(value);
389        } catch (NumberFormatException e) {
390            // Ignoring exception causes specified default to be returned
391        }
392
393        return result;
394    }
395
396    /**
397     * Implements the <tt>putLong</tt> method as per the specification in
398     * {@link Preferences#putLong(String,long)}.
399     *
400     * <p>This implementation translates <tt>value</tt> to a string with
401     * {@link Long#toString(long)} and invokes {@link #put(String,String)}
402     * on the result.
403     *
404     * @param key key with which the string form of value is to be associated.
405     * @param value value whose string form is to be associated with key.
406     * @throws NullPointerException if key is <tt>null</tt>.
407     * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
408     *         <tt>MAX_KEY_LENGTH</tt>.
409     * @throws IllegalStateException if this node (or an ancestor) has been
410     *         removed with the {@link #removeNode()} method.
411     */
412    public void putLong(String key, long value) {
413        put(key, Long.toString(value));
414    }
415
416    /**
417     * Implements the <tt>getLong</tt> method as per the specification in
418     * {@link Preferences#getLong(String,long)}.
419     *
420     * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
421     * null)</tt>}.  If the return value is non-null, the implementation
422     * attempts to translate it to a <tt>long</tt> with
423     * {@link Long#parseLong(String)}.  If the attempt succeeds, the return
424     * value is returned by this method.  Otherwise, <tt>def</tt> is returned.
425     *
426     * @param key key whose associated value is to be returned as a long.
427     * @param def the value to be returned in the event that this
428     *        preference node has no value associated with <tt>key</tt>
429     *        or the associated value cannot be interpreted as a long.
430     * @return the long value represented by the string associated with
431     *         <tt>key</tt> in this preference node, or <tt>def</tt> if the
432     *         associated value does not exist or cannot be interpreted as
433     *         a long.
434     * @throws IllegalStateException if this node (or an ancestor) has been
435     *         removed with the {@link #removeNode()} method.
436     * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
437     */
438    public long getLong(String key, long def) {
439        long result = def;
440        try {
441            String value = get(key, null);
442            if (value != null)
443                result = Long.parseLong(value);
444        } catch (NumberFormatException e) {
445            // Ignoring exception causes specified default to be returned
446        }
447
448        return result;
449    }
450
451    /**
452     * Implements the <tt>putBoolean</tt> method as per the specification in
453     * {@link Preferences#putBoolean(String,boolean)}.
454     *
455     * <p>This implementation translates <tt>value</tt> to a string with
456     * {@link String#valueOf(boolean)} and invokes {@link #put(String,String)}
457     * on the result.
458     *
459     * @param key key with which the string form of value is to be associated.
460     * @param value value whose string form is to be associated with key.
461     * @throws NullPointerException if key is <tt>null</tt>.
462     * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
463     *         <tt>MAX_KEY_LENGTH</tt>.
464     * @throws IllegalStateException if this node (or an ancestor) has been
465     *         removed with the {@link #removeNode()} method.
466     */
467    public void putBoolean(String key, boolean value) {
468        put(key, String.valueOf(value));
469    }
470
471    /**
472     * Implements the <tt>getBoolean</tt> method as per the specification in
473     * {@link Preferences#getBoolean(String,boolean)}.
474     *
475     * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
476     * null)</tt>}.  If the return value is non-null, it is compared with
477     * <tt>"true"</tt> using {@link String#equalsIgnoreCase(String)}.  If the
478     * comparison returns <tt>true</tt>, this invocation returns
479     * <tt>true</tt>.  Otherwise, the original return value is compared with
480     * <tt>"false"</tt>, again using {@link String#equalsIgnoreCase(String)}.
481     * If the comparison returns <tt>true</tt>, this invocation returns
482     * <tt>false</tt>.  Otherwise, this invocation returns <tt>def</tt>.
483     *
484     * @param key key whose associated value is to be returned as a boolean.
485     * @param def the value to be returned in the event that this
486     *        preference node has no value associated with <tt>key</tt>
487     *        or the associated value cannot be interpreted as a boolean.
488     * @return the boolean value represented by the string associated with
489     *         <tt>key</tt> in this preference node, or <tt>def</tt> if the
490     *         associated value does not exist or cannot be interpreted as
491     *         a boolean.
492     * @throws IllegalStateException if this node (or an ancestor) has been
493     *         removed with the {@link #removeNode()} method.
494     * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
495     */
496    public boolean getBoolean(String key, boolean def) {
497        boolean result = def;
498        String value = get(key, null);
499        if (value != null) {
500            if (value.equalsIgnoreCase("true"))
501                result = true;
502            else if (value.equalsIgnoreCase("false"))
503                result = false;
504        }
505
506        return result;
507    }
508
509    /**
510     * Implements the <tt>putFloat</tt> method as per the specification in
511     * {@link Preferences#putFloat(String,float)}.
512     *
513     * <p>This implementation translates <tt>value</tt> to a string with
514     * {@link Float#toString(float)} and invokes {@link #put(String,String)}
515     * on the result.
516     *
517     * @param key key with which the string form of value is to be associated.
518     * @param value value whose string form is to be associated with key.
519     * @throws NullPointerException if key is <tt>null</tt>.
520     * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
521     *         <tt>MAX_KEY_LENGTH</tt>.
522     * @throws IllegalStateException if this node (or an ancestor) has been
523     *         removed with the {@link #removeNode()} method.
524     */
525    public void putFloat(String key, float value) {
526        put(key, Float.toString(value));
527    }
528
529    /**
530     * Implements the <tt>getFloat</tt> method as per the specification in
531     * {@link Preferences#getFloat(String,float)}.
532     *
533     * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
534     * null)</tt>}.  If the return value is non-null, the implementation
535     * attempts to translate it to an <tt>float</tt> with
536     * {@link Float#parseFloat(String)}.  If the attempt succeeds, the return
537     * value is returned by this method.  Otherwise, <tt>def</tt> is returned.
538     *
539     * @param key key whose associated value is to be returned as a float.
540     * @param def the value to be returned in the event that this
541     *        preference node has no value associated with <tt>key</tt>
542     *        or the associated value cannot be interpreted as a float.
543     * @return the float value represented by the string associated with
544     *         <tt>key</tt> in this preference node, or <tt>def</tt> if the
545     *         associated value does not exist or cannot be interpreted as
546     *         a float.
547     * @throws IllegalStateException if this node (or an ancestor) has been
548     *         removed with the {@link #removeNode()} method.
549     * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
550     */
551    public float getFloat(String key, float def) {
552        float result = def;
553        try {
554            String value = get(key, null);
555            if (value != null)
556                result = Float.parseFloat(value);
557        } catch (NumberFormatException e) {
558            // Ignoring exception causes specified default to be returned
559        }
560
561        return result;
562    }
563
564    /**
565     * Implements the <tt>putDouble</tt> method as per the specification in
566     * {@link Preferences#putDouble(String,double)}.
567     *
568     * <p>This implementation translates <tt>value</tt> to a string with
569     * {@link Double#toString(double)} and invokes {@link #put(String,String)}
570     * on the result.
571     *
572     * @param key key with which the string form of value is to be associated.
573     * @param value value whose string form is to be associated with key.
574     * @throws NullPointerException if key is <tt>null</tt>.
575     * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
576     *         <tt>MAX_KEY_LENGTH</tt>.
577     * @throws IllegalStateException if this node (or an ancestor) has been
578     *         removed with the {@link #removeNode()} method.
579     */
580    public void putDouble(String key, double value) {
581        put(key, Double.toString(value));
582    }
583
584    /**
585     * Implements the <tt>getDouble</tt> method as per the specification in
586     * {@link Preferences#getDouble(String,double)}.
587     *
588     * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
589     * null)</tt>}.  If the return value is non-null, the implementation
590     * attempts to translate it to an <tt>double</tt> with
591     * {@link Double#parseDouble(String)}.  If the attempt succeeds, the return
592     * value is returned by this method.  Otherwise, <tt>def</tt> is returned.
593     *
594     * @param key key whose associated value is to be returned as a double.
595     * @param def the value to be returned in the event that this
596     *        preference node has no value associated with <tt>key</tt>
597     *        or the associated value cannot be interpreted as a double.
598     * @return the double value represented by the string associated with
599     *         <tt>key</tt> in this preference node, or <tt>def</tt> if the
600     *         associated value does not exist or cannot be interpreted as
601     *         a double.
602     * @throws IllegalStateException if this node (or an ancestor) has been
603     *         removed with the {@link #removeNode()} method.
604     * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
605     */
606    public double getDouble(String key, double def) {
607        double result = def;
608        try {
609            String value = get(key, null);
610            if (value != null)
611                result = Double.parseDouble(value);
612        } catch (NumberFormatException e) {
613            // Ignoring exception causes specified default to be returned
614        }
615
616        return result;
617    }
618
619    /**
620     * Implements the <tt>putByteArray</tt> method as per the specification in
621     * {@link Preferences#putByteArray(String,byte[])}.
622     *
623     * @param key key with which the string form of value is to be associated.
624     * @param value value whose string form is to be associated with key.
625     * @throws NullPointerException if key or value is <tt>null</tt>.
626     * @throws IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH
627     *         or if value.length exceeds MAX_VALUE_LENGTH*3/4.
628     * @throws IllegalStateException if this node (or an ancestor) has been
629     *         removed with the {@link #removeNode()} method.
630     */
631    public void putByteArray(String key, byte[] value) {
632        put(key, Base64.byteArrayToBase64(value));
633    }
634
635    /**
636     * Implements the <tt>getByteArray</tt> method as per the specification in
637     * {@link Preferences#getByteArray(String,byte[])}.
638     *
639     * @param key key whose associated value is to be returned as a byte array.
640     * @param def the value to be returned in the event that this
641     *        preference node has no value associated with <tt>key</tt>
642     *        or the associated value cannot be interpreted as a byte array.
643     * @return the byte array value represented by the string associated with
644     *         <tt>key</tt> in this preference node, or <tt>def</tt> if the
645     *         associated value does not exist or cannot be interpreted as
646     *         a byte array.
647     * @throws IllegalStateException if this node (or an ancestor) has been
648     *         removed with the {@link #removeNode()} method.
649     * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.  (A
650     *         <tt>null</tt> value for <tt>def</tt> <i>is</i> permitted.)
651     */
652    public byte[] getByteArray(String key, byte[] def) {
653        byte[] result = def;
654        String value = get(key, null);
655        try {
656            if (value != null)
657                result = Base64.base64ToByteArray(value);
658        }
659        catch (RuntimeException e) {
660            // Ignoring exception causes specified default to be returned
661        }
662
663        return result;
664    }
665
666    /**
667     * Implements the <tt>keys</tt> method as per the specification in
668     * {@link Preferences#keys()}.
669     *
670     * <p>This implementation obtains this preference node's lock, checks that
671     * the node has not been removed and invokes {@link #keysSpi()}.
672     *
673     * @return an array of the keys that have an associated value in this
674     *         preference node.
675     * @throws BackingStoreException if this operation cannot be completed
676     *         due to a failure in the backing store, or inability to
677     *         communicate with it.
678     * @throws IllegalStateException if this node (or an ancestor) has been
679     *         removed with the {@link #removeNode()} method.
680     */
681    public String[] keys() throws BackingStoreException {
682        synchronized(lock) {
683            if (removed)
684                throw new IllegalStateException("Node has been removed.");
685
686            return keysSpi();
687        }
688    }
689
690    /**
691     * Implements the <tt>children</tt> method as per the specification in
692     * {@link Preferences#childrenNames()}.
693     *
694     * <p>This implementation obtains this preference node's lock, checks that
695     * the node has not been removed, constructs a <tt>TreeSet</tt> initialized
696     * to the names of children already cached (the children in this node's
697     * "child-cache"), invokes {@link #childrenNamesSpi()}, and adds all of the
698     * returned child-names into the set.  The elements of the tree set are
699     * dumped into a <tt>String</tt> array using the <tt>toArray</tt> method,
700     * and this array is returned.
701     *
702     * @return the names of the children of this preference node.
703     * @throws BackingStoreException if this operation cannot be completed
704     *         due to a failure in the backing store, or inability to
705     *         communicate with it.
706     * @throws IllegalStateException if this node (or an ancestor) has been
707     *         removed with the {@link #removeNode()} method.
708     * @see #cachedChildren()
709     */
710    public String[] childrenNames() throws BackingStoreException {
711        synchronized(lock) {
712            if (removed)
713                throw new IllegalStateException("Node has been removed.");
714
715            Set<String> s = new TreeSet<>(kidCache.keySet());
716            for (String kid : childrenNamesSpi())
717                s.add(kid);
718            return s.toArray(EMPTY_STRING_ARRAY);
719        }
720    }
721
722    private static final String[] EMPTY_STRING_ARRAY = new String[0];
723
724    /**
725     * Returns all known unremoved children of this node.
726     *
727     * @return all known unremoved children of this node.
728     */
729    protected final AbstractPreferences[] cachedChildren() {
730        return kidCache.values().toArray(EMPTY_ABSTRACT_PREFS_ARRAY);
731    }
732
733    private static final AbstractPreferences[] EMPTY_ABSTRACT_PREFS_ARRAY
734        = new AbstractPreferences[0];
735
736    /**
737     * Implements the <tt>parent</tt> method as per the specification in
738     * {@link Preferences#parent()}.
739     *
740     * <p>This implementation obtains this preference node's lock, checks that
741     * the node has not been removed and returns the parent value that was
742     * passed to this node's constructor.
743     *
744     * @return the parent of this preference node.
745     * @throws IllegalStateException if this node (or an ancestor) has been
746     *         removed with the {@link #removeNode()} method.
747     */
748    public Preferences parent() {
749        synchronized(lock) {
750            if (removed)
751                throw new IllegalStateException("Node has been removed.");
752
753            return parent;
754        }
755    }
756
757    /**
758     * Implements the <tt>node</tt> method as per the specification in
759     * {@link Preferences#node(String)}.
760     *
761     * <p>This implementation obtains this preference node's lock and checks
762     * that the node has not been removed.  If <tt>path</tt> is <tt>""</tt>,
763     * this node is returned; if <tt>path</tt> is <tt>"/"</tt>, this node's
764     * root is returned.  If the first character in <tt>path</tt> is
765     * not <tt>'/'</tt>, the implementation breaks <tt>path</tt> into
766     * tokens and recursively traverses the path from this node to the
767     * named node, "consuming" a name and a slash from <tt>path</tt> at
768     * each step of the traversal.  At each step, the current node is locked
769     * and the node's child-cache is checked for the named node.  If it is
770     * not found, the name is checked to make sure its length does not
771     * exceed <tt>MAX_NAME_LENGTH</tt>.  Then the {@link #childSpi(String)}
772     * method is invoked, and the result stored in this node's child-cache.
773     * If the newly created <tt>Preferences</tt> object's {@link #newNode}
774     * field is <tt>true</tt> and there are any node change listeners,
775     * a notification event is enqueued for processing by the event dispatch
776     * thread.
777     *
778     * <p>When there are no more tokens, the last value found in the
779     * child-cache or returned by <tt>childSpi</tt> is returned by this
780     * method.  If during the traversal, two <tt>"/"</tt> tokens occur
781     * consecutively, or the final token is <tt>"/"</tt> (rather than a name),
782     * an appropriate <tt>IllegalArgumentException</tt> is thrown.
783     *
784     * <p> If the first character of <tt>path</tt> is <tt>'/'</tt>
785     * (indicating an absolute path name) this preference node's
786     * lock is dropped prior to breaking <tt>path</tt> into tokens, and
787     * this method recursively traverses the path starting from the root
788     * (rather than starting from this node).  The traversal is otherwise
789     * identical to the one described for relative path names.  Dropping
790     * the lock on this node prior to commencing the traversal at the root
791     * node is essential to avoid the possibility of deadlock, as per the
792     * {@link #lock locking invariant}.
793     *
794     * @param path the path name of the preference node to return.
795     * @return the specified preference node.
796     * @throws IllegalArgumentException if the path name is invalid (i.e.,
797     *         it contains multiple consecutive slash characters, or ends
798     *         with a slash character and is more than one character long).
799     * @throws IllegalStateException if this node (or an ancestor) has been
800     *         removed with the {@link #removeNode()} method.
801     */
802    public Preferences node(String path) {
803        synchronized(lock) {
804            if (removed)
805                throw new IllegalStateException("Node has been removed.");
806            if (path.equals(""))
807                return this;
808            if (path.equals("/"))
809                return root;
810            if (path.charAt(0) != '/')
811                return node(new StringTokenizer(path, "/", true));
812        }
813
814        // Absolute path.  Note that we've dropped our lock to avoid deadlock
815        return root.node(new StringTokenizer(path.substring(1), "/", true));
816    }
817
818    /**
819     * tokenizer contains <name> {'/' <name>}*
820     */
821    private Preferences node(StringTokenizer path) {
822        String token = path.nextToken();
823        if (token.equals("/"))  // Check for consecutive slashes
824            throw new IllegalArgumentException("Consecutive slashes in path");
825        synchronized(lock) {
826            AbstractPreferences child = kidCache.get(token);
827            if (child == null) {
828                if (token.length() > MAX_NAME_LENGTH)
829                    throw new IllegalArgumentException(
830                        "Node name " + token + " too long");
831                child = childSpi(token);
832                if (child.newNode)
833                    enqueueNodeAddedEvent(child);
834                kidCache.put(token, child);
835            }
836            if (!path.hasMoreTokens())
837                return child;
838            path.nextToken();  // Consume slash
839            if (!path.hasMoreTokens())
840                throw new IllegalArgumentException("Path ends with slash");
841            return child.node(path);
842        }
843    }
844
845    /**
846     * Implements the <tt>nodeExists</tt> method as per the specification in
847     * {@link Preferences#nodeExists(String)}.
848     *
849     * <p>This implementation is very similar to {@link #node(String)},
850     * except that {@link #getChild(String)} is used instead of {@link
851     * #childSpi(String)}.
852     *
853     * @param path the path name of the node whose existence is to be checked.
854     * @return true if the specified node exists.
855     * @throws BackingStoreException if this operation cannot be completed
856     *         due to a failure in the backing store, or inability to
857     *         communicate with it.
858     * @throws IllegalArgumentException if the path name is invalid (i.e.,
859     *         it contains multiple consecutive slash characters, or ends
860     *         with a slash character and is more than one character long).
861     * @throws IllegalStateException if this node (or an ancestor) has been
862     *         removed with the {@link #removeNode()} method and
863     *         <tt>pathname</tt> is not the empty string (<tt>""</tt>).
864     */
865    public boolean nodeExists(String path)
866        throws BackingStoreException
867    {
868        synchronized(lock) {
869            if (path.equals(""))
870                return !removed;
871            if (removed)
872                throw new IllegalStateException("Node has been removed.");
873            if (path.equals("/"))
874                return true;
875            if (path.charAt(0) != '/')
876                return nodeExists(new StringTokenizer(path, "/", true));
877        }
878
879        // Absolute path.  Note that we've dropped our lock to avoid deadlock
880        return root.nodeExists(new StringTokenizer(path.substring(1), "/",
881                                                   true));
882    }
883
884    /**
885     * tokenizer contains <name> {'/' <name>}*
886     */
887    private boolean nodeExists(StringTokenizer path)
888        throws BackingStoreException
889    {
890        String token = path.nextToken();
891        if (token.equals("/"))  // Check for consecutive slashes
892            throw new IllegalArgumentException("Consecutive slashes in path");
893        synchronized(lock) {
894            AbstractPreferences child = kidCache.get(token);
895            if (child == null)
896                child = getChild(token);
897            if (child==null)
898                return false;
899            if (!path.hasMoreTokens())
900                return true;
901            path.nextToken();  // Consume slash
902            if (!path.hasMoreTokens())
903                throw new IllegalArgumentException("Path ends with slash");
904            return child.nodeExists(path);
905        }
906    }
907
908    /**
909
910     * Implements the <tt>removeNode()</tt> method as per the specification in
911     * {@link Preferences#removeNode()}.
912     *
913     * <p>This implementation checks to see that this node is the root; if so,
914     * it throws an appropriate exception.  Then, it locks this node's parent,
915     * and calls a recursive helper method that traverses the subtree rooted at
916     * this node.  The recursive method locks the node on which it was called,
917     * checks that it has not already been removed, and then ensures that all
918     * of its children are cached: The {@link #childrenNamesSpi()} method is
919     * invoked and each returned child name is checked for containment in the
920     * child-cache.  If a child is not already cached, the {@link
921     * #childSpi(String)} method is invoked to create a <tt>Preferences</tt>
922     * instance for it, and this instance is put into the child-cache.  Then
923     * the helper method calls itself recursively on each node contained in its
924     * child-cache.  Next, it invokes {@link #removeNodeSpi()}, marks itself
925     * as removed, and removes itself from its parent's child-cache.  Finally,
926     * if there are any node change listeners, it enqueues a notification
927     * event for processing by the event dispatch thread.
928     *
929     * <p>Note that the helper method is always invoked with all ancestors up
930     * to the "closest non-removed ancestor" locked.
931     *
932     * @throws IllegalStateException if this node (or an ancestor) has already
933     *         been removed with the {@link #removeNode()} method.
934     * @throws UnsupportedOperationException if this method is invoked on
935     *         the root node.
936     * @throws BackingStoreException if this operation cannot be completed
937     *         due to a failure in the backing store, or inability to
938     *         communicate with it.
939     */
940    public void removeNode() throws BackingStoreException {
941        if (this==root)
942            throw new UnsupportedOperationException("Can't remove the root!");
943        synchronized(parent.lock) {
944            removeNode2();
945            parent.kidCache.remove(name);
946        }
947    }
948
949    /*
950     * Called with locks on all nodes on path from parent of "removal root"
951     * to this (including the former but excluding the latter).
952     */
953    private void removeNode2() throws BackingStoreException {
954        synchronized(lock) {
955            if (removed)
956                throw new IllegalStateException("Node already removed.");
957
958            // Ensure that all children are cached
959            String[] kidNames = childrenNamesSpi();
960            for (int i=0; i<kidNames.length; i++)
961                if (!kidCache.containsKey(kidNames[i]))
962                    kidCache.put(kidNames[i], childSpi(kidNames[i]));
963
964            // Recursively remove all cached children
965            for (Iterator<AbstractPreferences> i = kidCache.values().iterator();
966                 i.hasNext();) {
967                try {
968                    i.next().removeNode2();
969                    i.remove();
970                } catch (BackingStoreException x) { }
971            }
972
973            // Now we have no descendants - it's time to die!
974            removeNodeSpi();
975            removed = true;
976            parent.enqueueNodeRemovedEvent(this);
977        }
978    }
979
980    /**
981     * Implements the <tt>name</tt> method as per the specification in
982     * {@link Preferences#name()}.
983     *
984     * <p>This implementation merely returns the name that was
985     * passed to this node's constructor.
986     *
987     * @return this preference node's name, relative to its parent.
988     */
989    public String name() {
990        return name;
991    }
992
993    /**
994     * Implements the <tt>absolutePath</tt> method as per the specification in
995     * {@link Preferences#absolutePath()}.
996     *
997     * <p>This implementation merely returns the absolute path name that
998     * was computed at the time that this node was constructed (based on
999     * the name that was passed to this node's constructor, and the names
1000     * that were passed to this node's ancestors' constructors).
1001     *
1002     * @return this preference node's absolute path name.
1003     */
1004    public String absolutePath() {
1005        return absolutePath;
1006    }
1007
1008    /**
1009     * Implements the <tt>isUserNode</tt> method as per the specification in
1010     * {@link Preferences#isUserNode()}.
1011     *
1012     * <p>This implementation compares this node's root node (which is stored
1013     * in a private field) with the value returned by
1014     * {@link Preferences#userRoot()}.  If the two object references are
1015     * identical, this method returns true.
1016     *
1017     * @return <tt>true</tt> if this preference node is in the user
1018     *         preference tree, <tt>false</tt> if it's in the system
1019     *         preference tree.
1020     */
1021    public boolean isUserNode() {
1022        return AccessController.doPrivileged(
1023            new PrivilegedAction<Boolean>() {
1024                public Boolean run() {
1025                    return root == Preferences.userRoot();
1026            }
1027            }).booleanValue();
1028    }
1029
1030    public void addPreferenceChangeListener(PreferenceChangeListener pcl) {
1031        if (pcl==null)
1032            throw new NullPointerException("Change listener is null.");
1033        synchronized(lock) {
1034            if (removed)
1035                throw new IllegalStateException("Node has been removed.");
1036
1037            prefListeners.add(pcl);
1038        }
1039        startEventDispatchThreadIfNecessary();
1040    }
1041
1042    public void removePreferenceChangeListener(PreferenceChangeListener pcl) {
1043        synchronized(lock) {
1044            if (removed)
1045                throw new IllegalStateException("Node has been removed.");
1046
1047            if (!prefListeners.contains(pcl)) {
1048                throw new IllegalArgumentException("Listener not registered.");
1049            }
1050
1051            prefListeners.remove(pcl);
1052        }
1053    }
1054
1055    public void addNodeChangeListener(NodeChangeListener ncl) {
1056        if (ncl==null)
1057            throw new NullPointerException("Change listener is null.");
1058        synchronized(lock) {
1059            if (removed)
1060                throw new IllegalStateException("Node has been removed.");
1061
1062            nodeListeners.add(ncl);
1063        }
1064        startEventDispatchThreadIfNecessary();
1065    }
1066
1067    public void removeNodeChangeListener(NodeChangeListener ncl) {
1068        synchronized(lock) {
1069            if (removed)
1070                throw new IllegalStateException("Node has been removed.");
1071
1072            if (!nodeListeners.contains(ncl)) {
1073                throw new IllegalArgumentException("Listener not registered.");
1074            }
1075
1076            nodeListeners.remove(ncl);
1077        }
1078    }
1079
1080    // "SPI" METHODS
1081
1082    /**
1083     * Put the given key-value association into this preference node.  It is
1084     * guaranteed that <tt>key</tt> and <tt>value</tt> are non-null and of
1085     * legal length.  Also, it is guaranteed that this node has not been
1086     * removed.  (The implementor needn't check for any of these things.)
1087     *
1088     * <p>This method is invoked with the lock on this node held.
1089     */
1090    protected abstract void putSpi(String key, String value);
1091
1092    /**
1093     * Return the value associated with the specified key at this preference
1094     * node, or <tt>null</tt> if there is no association for this key, or the
1095     * association cannot be determined at this time.  It is guaranteed that
1096     * <tt>key</tt> is non-null.  Also, it is guaranteed that this node has
1097     * not been removed.  (The implementor needn't check for either of these
1098     * things.)
1099     *
1100     * <p> Generally speaking, this method should not throw an exception
1101     * under any circumstances.  If, however, if it does throw an exception,
1102     * the exception will be intercepted and treated as a <tt>null</tt>
1103     * return value.
1104     *
1105     * <p>This method is invoked with the lock on this node held.
1106     *
1107     * @return the value associated with the specified key at this preference
1108     *          node, or <tt>null</tt> if there is no association for this
1109     *          key, or the association cannot be determined at this time.
1110     */
1111    protected abstract String getSpi(String key);
1112
1113    /**
1114     * Remove the association (if any) for the specified key at this
1115     * preference node.  It is guaranteed that <tt>key</tt> is non-null.
1116     * Also, it is guaranteed that this node has not been removed.
1117     * (The implementor needn't check for either of these things.)
1118     *
1119     * <p>This method is invoked with the lock on this node held.
1120     */
1121    protected abstract void removeSpi(String key);
1122
1123    /**
1124     * Removes this preference node, invalidating it and any preferences that
1125     * it contains.  The named child will have no descendants at the time this
1126     * invocation is made (i.e., the {@link Preferences#removeNode()} method
1127     * invokes this method repeatedly in a bottom-up fashion, removing each of
1128     * a node's descendants before removing the node itself).
1129     *
1130     * <p>This method is invoked with the lock held on this node and its
1131     * parent (and all ancestors that are being removed as a
1132     * result of a single invocation to {@link Preferences#removeNode()}).
1133     *
1134     * <p>The removal of a node needn't become persistent until the
1135     * <tt>flush</tt> method is invoked on this node (or an ancestor).
1136     *
1137     * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
1138     * will propagate out beyond the enclosing {@link #removeNode()}
1139     * invocation.
1140     *
1141     * @throws BackingStoreException if this operation cannot be completed
1142     *         due to a failure in the backing store, or inability to
1143     *         communicate with it.
1144     */
1145    protected abstract void removeNodeSpi() throws BackingStoreException;
1146
1147    /**
1148     * Returns all of the keys that have an associated value in this
1149     * preference node.  (The returned array will be of size zero if
1150     * this node has no preferences.)  It is guaranteed that this node has not
1151     * been removed.
1152     *
1153     * <p>This method is invoked with the lock on this node held.
1154     *
1155     * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
1156     * will propagate out beyond the enclosing {@link #keys()} invocation.
1157     *
1158     * @return an array of the keys that have an associated value in this
1159     *         preference node.
1160     * @throws BackingStoreException if this operation cannot be completed
1161     *         due to a failure in the backing store, or inability to
1162     *         communicate with it.
1163     */
1164    protected abstract String[] keysSpi() throws BackingStoreException;
1165
1166    /**
1167     * Returns the names of the children of this preference node.  (The
1168     * returned array will be of size zero if this node has no children.)
1169     * This method need not return the names of any nodes already cached,
1170     * but may do so without harm.
1171     *
1172     * <p>This method is invoked with the lock on this node held.
1173     *
1174     * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
1175     * will propagate out beyond the enclosing {@link #childrenNames()}
1176     * invocation.
1177     *
1178     * @return an array containing the names of the children of this
1179     *         preference node.
1180     * @throws BackingStoreException if this operation cannot be completed
1181     *         due to a failure in the backing store, or inability to
1182     *         communicate with it.
1183     */
1184    protected abstract String[] childrenNamesSpi()
1185        throws BackingStoreException;
1186
1187    /**
1188     * Returns the named child if it exists, or <tt>null</tt> if it does not.
1189     * It is guaranteed that <tt>nodeName</tt> is non-null, non-empty,
1190     * does not contain the slash character ('/'), and is no longer than
1191     * {@link #MAX_NAME_LENGTH} characters.  Also, it is guaranteed
1192     * that this node has not been removed.  (The implementor needn't check
1193     * for any of these things if he chooses to override this method.)
1194     *
1195     * <p>Finally, it is guaranteed that the named node has not been returned
1196     * by a previous invocation of this method or {@link #childSpi} after the
1197     * last time that it was removed.  In other words, a cached value will
1198     * always be used in preference to invoking this method.  (The implementor
1199     * needn't maintain his own cache of previously returned children if he
1200     * chooses to override this method.)
1201     *
1202     * <p>This implementation obtains this preference node's lock, invokes
1203     * {@link #childrenNames()} to get an array of the names of this node's
1204     * children, and iterates over the array comparing the name of each child
1205     * with the specified node name.  If a child node has the correct name,
1206     * the {@link #childSpi(String)} method is invoked and the resulting
1207     * node is returned.  If the iteration completes without finding the
1208     * specified name, <tt>null</tt> is returned.
1209     *
1210     * @param nodeName name of the child to be searched for.
1211     * @return the named child if it exists, or null if it does not.
1212     * @throws BackingStoreException if this operation cannot be completed
1213     *         due to a failure in the backing store, or inability to
1214     *         communicate with it.
1215     */
1216    protected AbstractPreferences getChild(String nodeName)
1217            throws BackingStoreException {
1218        synchronized(lock) {
1219            // assert kidCache.get(nodeName)==null;
1220            String[] kidNames = childrenNames();
1221            for (int i=0; i<kidNames.length; i++)
1222                if (kidNames[i].equals(nodeName))
1223                    return childSpi(kidNames[i]);
1224        }
1225        return null;
1226    }
1227
1228    /**
1229     * Returns the named child of this preference node, creating it if it does
1230     * not already exist.  It is guaranteed that <tt>name</tt> is non-null,
1231     * non-empty, does not contain the slash character ('/'), and is no longer
1232     * than {@link #MAX_NAME_LENGTH} characters.  Also, it is guaranteed that
1233     * this node has not been removed.  (The implementor needn't check for any
1234     * of these things.)
1235     *
1236     * <p>Finally, it is guaranteed that the named node has not been returned
1237     * by a previous invocation of this method or {@link #getChild(String)}
1238     * after the last time that it was removed.  In other words, a cached
1239     * value will always be used in preference to invoking this method.
1240     * Subclasses need not maintain their own cache of previously returned
1241     * children.
1242     *
1243     * <p>The implementer must ensure that the returned node has not been
1244     * removed.  If a like-named child of this node was previously removed, the
1245     * implementer must return a newly constructed <tt>AbstractPreferences</tt>
1246     * node; once removed, an <tt>AbstractPreferences</tt> node
1247     * cannot be "resuscitated."
1248     *
1249     * <p>If this method causes a node to be created, this node is not
1250     * guaranteed to be persistent until the <tt>flush</tt> method is
1251     * invoked on this node or one of its ancestors (or descendants).
1252     *
1253     * <p>This method is invoked with the lock on this node held.
1254     *
1255     * @param name The name of the child node to return, relative to
1256     *        this preference node.
1257     * @return The named child node.
1258     */
1259    protected abstract AbstractPreferences childSpi(String name);
1260
1261    /**
1262     * Returns the absolute path name of this preferences node.
1263     */
1264    public String toString() {
1265        return (this.isUserNode() ? "User" : "System") +
1266               " Preference Node: " + this.absolutePath();
1267    }
1268
1269    /**
1270     * Implements the <tt>sync</tt> method as per the specification in
1271     * {@link Preferences#sync()}.
1272     *
1273     * <p>This implementation calls a recursive helper method that locks this
1274     * node, invokes syncSpi() on it, unlocks this node, and recursively
1275     * invokes this method on each "cached child."  A cached child is a child
1276     * of this node that has been created in this VM and not subsequently
1277     * removed.  In effect, this method does a depth first traversal of the
1278     * "cached subtree" rooted at this node, calling syncSpi() on each node in
1279     * the subTree while only that node is locked. Note that syncSpi() is
1280     * invoked top-down.
1281     *
1282     * @throws BackingStoreException if this operation cannot be completed
1283     *         due to a failure in the backing store, or inability to
1284     *         communicate with it.
1285     * @throws IllegalStateException if this node (or an ancestor) has been
1286     *         removed with the {@link #removeNode()} method.
1287     * @see #flush()
1288     */
1289    public void sync() throws BackingStoreException {
1290        sync2();
1291    }
1292
1293    private void sync2() throws BackingStoreException {
1294        AbstractPreferences[] cachedKids;
1295
1296        synchronized(lock) {
1297            if (removed)
1298                throw new IllegalStateException("Node has been removed");
1299            syncSpi();
1300            cachedKids = cachedChildren();
1301        }
1302
1303        for (int i=0; i<cachedKids.length; i++)
1304            cachedKids[i].sync2();
1305    }
1306
1307    /**
1308     * This method is invoked with this node locked.  The contract of this
1309     * method is to synchronize any cached preferences stored at this node
1310     * with any stored in the backing store.  (It is perfectly possible that
1311     * this node does not exist on the backing store, either because it has
1312     * been deleted by another VM, or because it has not yet been created.)
1313     * Note that this method should <i>not</i> synchronize the preferences in
1314     * any subnodes of this node.  If the backing store naturally syncs an
1315     * entire subtree at once, the implementer is encouraged to override
1316     * sync(), rather than merely overriding this method.
1317     *
1318     * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
1319     * will propagate out beyond the enclosing {@link #sync()} invocation.
1320     *
1321     * @throws BackingStoreException if this operation cannot be completed
1322     *         due to a failure in the backing store, or inability to
1323     *         communicate with it.
1324     */
1325    protected abstract void syncSpi() throws BackingStoreException;
1326
1327    /**
1328     * Implements the <tt>flush</tt> method as per the specification in
1329     * {@link Preferences#flush()}.
1330     *
1331     * <p>This implementation calls a recursive helper method that locks this
1332     * node, invokes flushSpi() on it, unlocks this node, and recursively
1333     * invokes this method on each "cached child."  A cached child is a child
1334     * of this node that has been created in this VM and not subsequently
1335     * removed.  In effect, this method does a depth first traversal of the
1336     * "cached subtree" rooted at this node, calling flushSpi() on each node in
1337     * the subTree while only that node is locked. Note that flushSpi() is
1338     * invoked top-down.
1339     *
1340     * <p> If this method is invoked on a node that has been removed with
1341     * the {@link #removeNode()} method, flushSpi() is invoked on this node,
1342     * but not on others.
1343     *
1344     * @throws BackingStoreException if this operation cannot be completed
1345     *         due to a failure in the backing store, or inability to
1346     *         communicate with it.
1347     * @see #flush()
1348     */
1349    public void flush() throws BackingStoreException {
1350        flush2();
1351    }
1352
1353    private void flush2() throws BackingStoreException {
1354        AbstractPreferences[] cachedKids;
1355
1356        synchronized(lock) {
1357            flushSpi();
1358            if(removed)
1359                return;
1360            cachedKids = cachedChildren();
1361        }
1362
1363        for (int i = 0; i < cachedKids.length; i++)
1364            cachedKids[i].flush2();
1365    }
1366
1367    /**
1368     * This method is invoked with this node locked.  The contract of this
1369     * method is to force any cached changes in the contents of this
1370     * preference node to the backing store, guaranteeing their persistence.
1371     * (It is perfectly possible that this node does not exist on the backing
1372     * store, either because it has been deleted by another VM, or because it
1373     * has not yet been created.)  Note that this method should <i>not</i>
1374     * flush the preferences in any subnodes of this node.  If the backing
1375     * store naturally flushes an entire subtree at once, the implementer is
1376     * encouraged to override flush(), rather than merely overriding this
1377     * method.
1378     *
1379     * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
1380     * will propagate out beyond the enclosing {@link #flush()} invocation.
1381     *
1382     * @throws BackingStoreException if this operation cannot be completed
1383     *         due to a failure in the backing store, or inability to
1384     *         communicate with it.
1385     */
1386    protected abstract void flushSpi() throws BackingStoreException;
1387
1388    /**
1389     * Returns <tt>true</tt> iff this node (or an ancestor) has been
1390     * removed with the {@link #removeNode()} method.  This method
1391     * locks this node prior to returning the contents of the private
1392     * field used to track this state.
1393     *
1394     * @return <tt>true</tt> iff this node (or an ancestor) has been
1395     *       removed with the {@link #removeNode()} method.
1396     */
1397    protected boolean isRemoved() {
1398        synchronized(lock) {
1399            return removed;
1400        }
1401    }
1402
1403    /**
1404     * Queue of pending notification events.  When a preference or node
1405     * change event for which there are one or more listeners occurs,
1406     * it is placed on this queue and the queue is notified.  A background
1407     * thread waits on this queue and delivers the events.  This decouples
1408     * event delivery from preference activity, greatly simplifying
1409     * locking and reducing opportunity for deadlock.
1410     */
1411    private static final List<EventObject> eventQueue = new LinkedList<>();
1412
1413    /**
1414     * These two classes are used to distinguish NodeChangeEvents on
1415     * eventQueue so the event dispatch thread knows whether to call
1416     * childAdded or childRemoved.
1417     */
1418    private class NodeAddedEvent extends NodeChangeEvent {
1419        private static final long serialVersionUID = -6743557530157328528L;
1420        NodeAddedEvent(Preferences parent, Preferences child) {
1421            super(parent, child);
1422        }
1423    }
1424    private class NodeRemovedEvent extends NodeChangeEvent {
1425        private static final long serialVersionUID = 8735497392918824837L;
1426        NodeRemovedEvent(Preferences parent, Preferences child) {
1427            super(parent, child);
1428        }
1429    }
1430
1431    /**
1432     * A single background thread ("the event notification thread") monitors
1433     * the event queue and delivers events that are placed on the queue.
1434     */
1435    private static class EventDispatchThread extends Thread {
1436        public void run() {
1437            while(true) {
1438                // Wait on eventQueue till an event is present
1439                EventObject event = null;
1440                synchronized(eventQueue) {
1441                    try {
1442                        while (eventQueue.isEmpty())
1443                            eventQueue.wait();
1444                        event = eventQueue.remove(0);
1445                    } catch (InterruptedException e) {
1446                        // XXX Log "Event dispatch thread interrupted. Exiting"
1447                        return;
1448                    }
1449                }
1450
1451                // Now we have event & hold no locks; deliver evt to listeners
1452                AbstractPreferences src=(AbstractPreferences)event.getSource();
1453                if (event instanceof PreferenceChangeEvent) {
1454                    PreferenceChangeEvent pce = (PreferenceChangeEvent)event;
1455                    PreferenceChangeListener[] listeners = src.prefListeners();
1456                    for (int i=0; i<listeners.length; i++)
1457                        listeners[i].preferenceChange(pce);
1458                } else {
1459                    NodeChangeEvent nce = (NodeChangeEvent)event;
1460                    NodeChangeListener[] listeners = src.nodeListeners();
1461                    if (nce instanceof NodeAddedEvent) {
1462                        for (int i=0; i<listeners.length; i++)
1463                            listeners[i].childAdded(nce);
1464                    } else {
1465                        // assert nce instanceof NodeRemovedEvent;
1466                        for (int i=0; i<listeners.length; i++)
1467                            listeners[i].childRemoved(nce);
1468                    }
1469                }
1470            }
1471        }
1472    }
1473
1474    private static Thread eventDispatchThread = null;
1475
1476    /**
1477     * This method starts the event dispatch thread the first time it
1478     * is called.  The event dispatch thread will be started only
1479     * if someone registers a listener.
1480     */
1481    private static synchronized void startEventDispatchThreadIfNecessary() {
1482        if (eventDispatchThread == null) {
1483            // XXX Log "Starting event dispatch thread"
1484            eventDispatchThread = new EventDispatchThread();
1485            eventDispatchThread.setDaemon(true);
1486            eventDispatchThread.start();
1487        }
1488    }
1489
1490    /**
1491     * Return this node's preference/node change listeners. All accesses to prefListeners
1492     * and nodeListeners are guarded by |lock|. We return a copy of the list so that the
1493     * EventQueue thread will iterate over a fixed snapshot of the listeners at the time of
1494     * this call.
1495     */
1496    PreferenceChangeListener[] prefListeners() {
1497        synchronized(lock) {
1498            return prefListeners.toArray(new PreferenceChangeListener[prefListeners.size()]);
1499        }
1500    }
1501    NodeChangeListener[] nodeListeners() {
1502        synchronized(lock) {
1503            return nodeListeners.toArray(new NodeChangeListener[nodeListeners.size()]);
1504        }
1505    }
1506
1507    /**
1508     * Enqueue a preference change event for delivery to registered
1509     * preference change listeners unless there are no registered
1510     * listeners.  Invoked with this.lock held.
1511     */
1512    private void enqueuePreferenceChangeEvent(String key, String newValue) {
1513        if (!prefListeners.isEmpty()) {
1514            synchronized(eventQueue) {
1515                eventQueue.add(new PreferenceChangeEvent(this, key, newValue));
1516                eventQueue.notify();
1517            }
1518        }
1519    }
1520
1521    /**
1522     * Enqueue a "node added" event for delivery to registered node change
1523     * listeners unless there are no registered listeners.  Invoked with
1524     * this.lock held.
1525     */
1526    private void enqueueNodeAddedEvent(Preferences child) {
1527        if (!nodeListeners.isEmpty()) {
1528            synchronized(eventQueue) {
1529                eventQueue.add(new NodeAddedEvent(this, child));
1530                eventQueue.notify();
1531            }
1532        }
1533    }
1534
1535    /**
1536     * Enqueue a "node removed" event for delivery to registered node change
1537     * listeners unless there are no registered listeners.  Invoked with
1538     * this.lock held.
1539     */
1540    private void enqueueNodeRemovedEvent(Preferences child) {
1541        if (!nodeListeners.isEmpty()) {
1542            synchronized(eventQueue) {
1543                eventQueue.add(new NodeRemovedEvent(this, child));
1544                eventQueue.notify();
1545            }
1546        }
1547    }
1548
1549    /**
1550     * Implements the <tt>exportNode</tt> method as per the specification in
1551     * {@link Preferences#exportNode(OutputStream)}.
1552     *
1553     * @param os the output stream on which to emit the XML document.
1554     * @throws IOException if writing to the specified output stream
1555     *         results in an <tt>IOException</tt>.
1556     * @throws BackingStoreException if preference data cannot be read from
1557     *         backing store.
1558     */
1559    public void exportNode(OutputStream os)
1560        throws IOException, BackingStoreException
1561    {
1562        XmlSupport.export(os, this, false);
1563    }
1564
1565    /**
1566     * Implements the <tt>exportSubtree</tt> method as per the specification in
1567     * {@link Preferences#exportSubtree(OutputStream)}.
1568     *
1569     * @param os the output stream on which to emit the XML document.
1570     * @throws IOException if writing to the specified output stream
1571     *         results in an <tt>IOException</tt>.
1572     * @throws BackingStoreException if preference data cannot be read from
1573     *         backing store.
1574     */
1575    public void exportSubtree(OutputStream os)
1576        throws IOException, BackingStoreException
1577    {
1578        XmlSupport.export(os, this, true);
1579    }
1580}
1581