KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > prefs > AbstractPreferences


1 /*
2  * @(#)AbstractPreferences.java 1.20 04/01/12
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package java.util.prefs;
9
10 import java.util.*;
11 import java.io.*;
12 import java.security.AccessController JavaDoc;
13 import java.security.PrivilegedAction JavaDoc;
14 // These imports needed only as a workaround for a JavaDoc bug
15
import java.lang.Integer JavaDoc;
16 import java.lang.Long JavaDoc;
17 import java.lang.Float JavaDoc;
18 import java.lang.Double JavaDoc;
19
20 /**
21  * This class provides a skeletal implementation of the {@link Preferences}
22  * class, greatly easing the task of implementing it.
23  *
24  * <p><strong>This class is for <tt>Preferences</tt> implementers only.
25  * Normal users of the <tt>Preferences</tt> facility should have no need to
26  * consult this documentation. The {@link Preferences} documentation
27  * should suffice.</strong>
28  *
29  * <p>Implementors must override the nine abstract service-provider interface
30  * (SPI) methods: {@link #getSpi(String)}, {@link #putSpi(String,String)},
31  * {@link #removeSpi(String)}, {@link #childSpi(String)}, {@link
32  * #removeNodeSpi()}, {@link #keysSpi()}, {@link #childrenNamesSpi()}, {@link
33  * #syncSpi()} and {@link #flushSpi()}. All of the concrete methods specify
34  * precisely how they are implemented atop these SPI methods. The implementor
35  * may, at his discretion, override one or more of the concrete methods if the
36  * default implementation is unsatisfactory for any reason, such as
37  * performance.
38  *
39  * <p>The SPI methods fall into three groups concerning exception
40  * behavior. The <tt>getSpi</tt> method should never throw exceptions, but it
41  * doesn't really matter, as any exception thrown by this method will be
42  * intercepted by {@link #get(String,String)}, which will return the specified
43  * default value to the caller. The <tt>removeNodeSpi, keysSpi,
44  * childrenNamesSpi, syncSpi</tt> and <tt>flushSpi</tt> methods are specified
45  * to throw {@link BackingStoreException}, and the implementation is required
46  * to throw this checked exception if it is unable to perform the operation.
47  * The exception propagates outward, causing the corresponding API method
48  * to fail.
49  *
50  * <p>The remaining SPI methods {@link #putSpi(String,String)}, {@link
51  * #removeSpi(String)} and {@link #childSpi(String)} have more complicated
52  * exception behavior. They are not specified to throw
53  * <tt>BackingStoreException</tt>, as they can generally obey their contracts
54  * even if the backing store is unavailable. This is true because they return
55  * no information and their effects are not required to become permanent until
56  * a subsequent call to {Preferences#flush()} or
57  * {Preferences#sync()}. Generally speaking, these SPI methods should not
58  * throw exceptions. In some implementations, there may be circumstances
59  * under which these calls cannot even enqueue the requested operation for
60  * later processing. Even under these circumstances it is generally better to
61  * simply ignore the invocation and return, rather than throwing an
62  * exception. Under these circumstances, however, all subsequent invocations
63  * of <tt>flush()</tt> and <tt>sync</tt> should return <tt>false</tt>, as
64  * returning <tt>true</tt> would imply that all previous operations had
65  * successfully been made permanent.
66  *
67  * <p>There is one circumstance under which <tt>putSpi, removeSpi and
68  * childSpi</tt> <i>should</i> throw an exception: if the caller lacks
69  * sufficient privileges on the underlying operating system to perform the
70  * requested operation. This will, for instance, occur on most systems
71  * if a non-privileged user attempts to modify system preferences.
72  * (The required privileges will vary from implementation to
73  * implementation. On some implementations, they are the right to modify the
74  * contents of some directory in the file system; on others they are the right
75  * to modify contents of some key in a registry.) Under any of these
76  * circumstances, it would generally be undesirable to let the program
77  * continue executing as if these operations would become permanent at a later
78  * time. While implementations are not required to throw an exception under
79  * these circumstances, they are encouraged to do so. A {@link
80  * SecurityException} would be appropriate.
81  *
82  * <p>Most of the SPI methods require the implementation to read or write
83  * information at a preferences node. The implementor should beware of the
84  * fact that another VM may have concurrently deleted this node from the
85  * backing store. It is the implementation's responsibility to recreate the
86  * node if it has been deleted.
87  *
88  * <p>Implementation note: In Sun's default <tt>Preferences</tt>
89  * implementations, the user's identity is inherited from the underlying
90  * operating system and does not change for the lifetime of the virtual
91  * machine. It is recognized that server-side <tt>Preferences</tt>
92  * implementations may have the user identity change from request to request,
93  * implicitly passed to <tt>Preferences</tt> methods via the use of a
94  * static {@link ThreadLocal} instance. Authors of such implementations are
95  * <i>strongly</i> encouraged to determine the user at the time preferences
96  * are accessed (for example by the {@link #get(String,String)} or {@link
97  * #put(String,String)} method) rather than permanently associating a user
98  * with each <tt>Preferences</tt> instance. The latter behavior conflicts
99  * with normal <tt>Preferences</tt> usage and would lead to great confusion.
100  *
101  * @author Josh Bloch
102  * @version 1.20, 01/12/04
103  * @see Preferences
104  * @since 1.4
105  */

106 public abstract class AbstractPreferences extends Preferences JavaDoc {
107     /**
108      * Our name relative to parent.
109      */

110     private final String JavaDoc name;
111
112     /**
113      * Our absolute path name.
114      */

115     private final String JavaDoc absolutePath;
116
117     /**
118      * Our parent node.
119      */

120     final AbstractPreferences JavaDoc parent;
121
122     /**
123      * Our root node.
124      */

125     private final AbstractPreferences JavaDoc root; // Relative to this node
126

127     /**
128      * This field should be <tt>true</tt> if this node did not exist in the
129      * backing store prior to the creation of this object. The field
130      * is initialized to false, but may be set to true by a subclass
131      * constructor (and should not be modified thereafter). This field
132      * indicates whether a node change event should be fired when
133      * creation is complete.
134      */

135     protected boolean newNode = false;
136
137     /**
138      * All known unremoved children of this node. (This "cache" is consulted
139      * prior to calling childSpi() or getChild().
140      */

141     private Map kidCache = new HashMap();
142
143     /**
144      * This field is used to keep track of whether or not this node has
145      * been removed. Once it's set to true, it will never be reset to false.
146      */

147     private boolean removed = false;
148
149     /**
150      * Registered preference change listeners.
151      */

152     private PreferenceChangeListener JavaDoc[] prefListeners =
153         new PreferenceChangeListener JavaDoc[0];
154
155     /**
156      * Registered node change listeners.
157      */

158     private NodeChangeListener JavaDoc[] nodeListeners = new NodeChangeListener JavaDoc[0];
159
160     /**
161      * An object whose monitor is used to lock this node. This object
162      * is used in preference to the node itself to reduce the likelihood of
163      * intentional or unintentional denial of service due to a locked node.
164      * To avoid deadlock, a node is <i>never</i> locked by a thread that
165      * holds a lock on a descendant of that node.
166      */

167     protected final Object JavaDoc lock = new Object JavaDoc();
168
169     /**
170      * Creates a preference node with the specified parent and the specified
171      * name relative to its parent.
172      *
173      * @param parent the parent of this preference node, or null if this
174      * is the root.
175      * @param name the name of this preference node, relative to its parent,
176      * or <tt>""</tt> if this is the root.
177      * @throws IllegalArgumentException if <tt>name</tt> contains a slash
178      * (<tt>'/'</tt>), or <tt>parent</tt> is <tt>null</tt> and
179      * name isn't <tt>""</tt>.
180      */

181     protected AbstractPreferences(AbstractPreferences JavaDoc parent, String JavaDoc name) {
182         if (parent==null) {
183             if (!name.equals(""))
184                 throw new IllegalArgumentException JavaDoc("Root name '"+name+
185                                                    "' must be \"\"");
186             this.absolutePath = "/";
187             root = this;
188         } else {
189             if (name.indexOf('/') != -1)
190                 throw new IllegalArgumentException JavaDoc("Name '" + name +
191                                                  "' contains '/'");
192             if (name.equals(""))
193               throw new IllegalArgumentException JavaDoc("Illegal name: empty string");
194
195             root = parent.root;
196             absolutePath = (parent==root ? "/" + name
197                                      : parent.absolutePath() + "/" + name);
198         }
199         this.name = name;
200         this.parent = parent;
201     }
202
203     /**
204      * Implements the <tt>put</tt> method as per the specification in
205      * {@link Preferences#put(String,String)}.
206      *
207      * <p>This implementation checks that the key and value are legal,
208      * obtains this preference node's lock, checks that the node
209      * has not been removed, invokes {@link #putSpi(String,String)}, and if
210      * there are any preference change listeners, enqueues a notification
211      * event for processing by the event dispatch thread.
212      *
213      * @param key key with which the specified value is to be associated.
214      * @param value value to be associated with the specified key.
215      * @throws NullPointerException if key or value is <tt>null</tt>.
216      * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
217      * <tt>MAX_KEY_LENGTH</tt> or if <tt>value.length</tt> exceeds
218      * <tt>MAX_VALUE_LENGTH</tt>.
219      * @throws IllegalStateException if this node (or an ancestor) has been
220      * removed with the {@link #removeNode()} method.
221      */

222     public void put(String JavaDoc key, String JavaDoc value) {
223         if (key==null || value==null)
224             throw new NullPointerException JavaDoc();
225         if (key.length() > MAX_KEY_LENGTH)
226             throw new IllegalArgumentException JavaDoc("Key too long: "+key);
227         if (value.length() > MAX_VALUE_LENGTH)
228             throw new IllegalArgumentException JavaDoc("Value too long: "+value);
229
230         synchronized(lock) {
231             if (removed)
232                 throw new IllegalStateException JavaDoc("Node has been removed.");
233
234             putSpi(key, value);
235             enqueuePreferenceChangeEvent(key, value);
236         }
237     }
238
239     /**
240      * Implements the <tt>get</tt> method as per the specification in
241      * {@link Preferences#get(String,String)}.
242      *
243      * <p>This implementation first checks to see if <tt>key</tt> is
244      * <tt>null</tt> throwing a <tt>NullPointerException</tt> if this is
245      * the case. Then it obtains this preference node's lock,
246      * checks that the node has not been removed, invokes {@link
247      * #getSpi(String)}, and returns the result, unless the <tt>getSpi</tt>
248      * invocation returns <tt>null</tt> or throws an exception, in which case
249      * this invocation returns <tt>def</tt>.
250      *
251      * @param key key whose associated value is to be returned.
252      * @param def the value to be returned in the event that this
253      * preference node has no value associated with <tt>key</tt>.
254      * @return the value associated with <tt>key</tt>, or <tt>def</tt>
255      * if no value is associated with <tt>key</tt>.
256      * @throws IllegalStateException if this node (or an ancestor) has been
257      * removed with the {@link #removeNode()} method.
258      * @throws NullPointerException if key is <tt>null</tt>. (A
259      * <tt>null</tt> default <i>is</i> permitted.)
260      */

261     public String JavaDoc get(String JavaDoc key, String JavaDoc def) {
262         if (key==null)
263             throw new NullPointerException JavaDoc("Null key");
264         synchronized(lock) {
265             if (removed)
266                 throw new IllegalStateException JavaDoc("Node has been removed.");
267
268             String JavaDoc result = null;
269             try {
270                 result = getSpi(key);
271             } catch (Exception JavaDoc e) {
272                 // Ignoring exception causes default to be returned
273
}
274             return (result==null ? def : result);
275         }
276     }
277
278     /**
279      * Implements the <tt>remove(String)</tt> method as per the specification
280      * in {@link Preferences#remove(String)}.
281      *
282      * <p>This implementation obtains this preference node's lock,
283      * checks that the node has not been removed, invokes
284      * {@link #removeSpi(String)} and if there are any preference
285      * change listeners, enqueues a notification event for processing by the
286      * event dispatch thread.
287      *
288      * @param key key whose mapping is to be removed from the preference node.
289      * @throws IllegalStateException if this node (or an ancestor) has been
290      * removed with the {@link #removeNode()} method.
291      */

292     public void remove(String JavaDoc key) {
293         synchronized(lock) {
294             if (removed)
295                 throw new IllegalStateException JavaDoc("Node has been removed.");
296
297             removeSpi(key);
298             enqueuePreferenceChangeEvent(key, null);
299         }
300     }
301
302     /**
303      * Implements the <tt>clear</tt> method as per the specification in
304      * {@link Preferences#clear()}.
305      *
306      * <p>This implementation obtains this preference node's lock,
307      * invokes {@link #keys()} to obtain an array of keys, and
308      * iterates over the array invoking {@link #remove(String)} on each key.
309      *
310      * @throws BackingStoreException if this operation cannot be completed
311      * due to a failure in the backing store, or inability to
312      * communicate with it.
313      * @throws IllegalStateException if this node (or an ancestor) has been
314      * removed with the {@link #removeNode()} method.
315      */

316     public void clear() throws BackingStoreException JavaDoc {
317         synchronized(lock) {
318             String JavaDoc[] keys = keys();
319             for (int i=0; i<keys.length; i++)
320                 remove(keys[i]);
321         }
322     }
323
324     /**
325      * Implements the <tt>putInt</tt> method as per the specification in
326      * {@link Preferences#putInt(String,int)}.
327      *
328      * <p>This implementation translates <tt>value</tt> to a string with
329      * {@link Integer#toString(int)} and invokes {@link #put(String,String)}
330      * on the result.
331      *
332      * @param key key with which the string form of value is to be associated.
333      * @param value value whose string form is to be associated with key.
334      * @throws NullPointerException if key is <tt>null</tt>.
335      * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
336      * <tt>MAX_KEY_LENGTH</tt>.
337      * @throws IllegalStateException if this node (or an ancestor) has been
338      * removed with the {@link #removeNode()} method.
339      */

340     public void putInt(String JavaDoc key, int value) {
341         put(key, Integer.toString(value));
342     }
343
344     /**
345      * Implements the <tt>getInt</tt> method as per the specification in
346      * {@link Preferences#getInt(String,int)}.
347      *
348      * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
349      * null)</tt>}. If the return value is non-null, the implementation
350      * attempts to translate it to an <tt>int</tt> with
351      * {@link Integer#parseInt(String)}. If the attempt succeeds, the return
352      * value is returned by this method. Otherwise, <tt>def</tt> is returned.
353      *
354      * @param key key whose associated value is to be returned as an int.
355      * @param def the value to be returned in the event that this
356      * preference node has no value associated with <tt>key</tt>
357      * or the associated value cannot be interpreted as an int.
358      * @return the int value represented by the string associated with
359      * <tt>key</tt> in this preference node, or <tt>def</tt> if the
360      * associated value does not exist or cannot be interpreted as
361      * an int.
362      * @throws IllegalStateException if this node (or an ancestor) has been
363      * removed with the {@link #removeNode()} method.
364      * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
365      */

366     public int getInt(String JavaDoc key, int def) {
367         int result = def;
368         try {
369             String JavaDoc value = get(key, null);
370             if (value != null)
371                 result = Integer.parseInt(value);
372         } catch (NumberFormatException JavaDoc e) {
373             // Ignoring exception causes specified default to be returned
374
}
375
376         return result;
377     }
378
379     /**
380      * Implements the <tt>putLong</tt> method as per the specification in
381      * {@link Preferences#putLong(String,long)}.
382      *
383      * <p>This implementation translates <tt>value</tt> to a string with
384      * {@link Long#toString(long)} and invokes {@link #put(String,String)}
385      * on the result.
386      *
387      * @param key key with which the string form of value is to be associated.
388      * @param value value whose string form is to be associated with key.
389      * @throws NullPointerException if key is <tt>null</tt>.
390      * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
391      * <tt>MAX_KEY_LENGTH</tt>.
392      * @throws IllegalStateException if this node (or an ancestor) has been
393      * removed with the {@link #removeNode()} method.
394      */

395     public void putLong(String JavaDoc key, long value) {
396         put(key, Long.toString(value));
397     }
398
399     /**
400      * Implements the <tt>getLong</tt> method as per the specification in
401      * {@link Preferences#getLong(String,long)}.
402      *
403      * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
404      * null)</tt>}. If the return value is non-null, the implementation
405      * attempts to translate it to a <tt>long</tt> with
406      * {@link Long#parseLong(String)}. If the attempt succeeds, the return
407      * value is returned by this method. Otherwise, <tt>def</tt> is returned.
408      *
409      * @param key key whose associated value is to be returned as a long.
410      * @param def the value to be returned in the event that this
411      * preference node has no value associated with <tt>key</tt>
412      * or the associated value cannot be interpreted as a long.
413      * @return the long value represented by the string associated with
414      * <tt>key</tt> in this preference node, or <tt>def</tt> if the
415      * associated value does not exist or cannot be interpreted as
416      * a long.
417      * @throws IllegalStateException if this node (or an ancestor) has been
418      * removed with the {@link #removeNode()} method.
419      * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
420      */

421     public long getLong(String JavaDoc key, long def) {
422         long result = def;
423         try {
424             String JavaDoc value = get(key, null);
425             if (value != null)
426                 result = Long.parseLong(value);
427         } catch (NumberFormatException JavaDoc e) {
428             // Ignoring exception causes specified default to be returned
429
}
430
431         return result;
432     }
433
434     /**
435      * Implements the <tt>putBoolean</tt> method as per the specification in
436      * {@link Preferences#putBoolean(String,boolean)}.
437      *
438      * <p>This implementation translates <tt>value</tt> to a string with
439      * {@link String#valueOf(boolean)} and invokes {@link #put(String,String)}
440      * on the result.
441      *
442      * @param key key with which the string form of value is to be associated.
443      * @param value value whose string form is to be associated with key.
444      * @throws NullPointerException if key is <tt>null</tt>.
445      * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
446      * <tt>MAX_KEY_LENGTH</tt>.
447      * @throws IllegalStateException if this node (or an ancestor) has been
448      * removed with the {@link #removeNode()} method.
449      */

450     public void putBoolean(String JavaDoc key, boolean value) {
451         put(key, String.valueOf(value));
452     }
453
454     /**
455      * Implements the <tt>getBoolean</tt> method as per the specification in
456      * {@link Preferences#getBoolean(String,boolean)}.
457      *
458      * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
459      * null)</tt>}. If the return value is non-null, it is compared with
460      * <tt>"true"</tt> using {@link String#equalsIgnoreCase(String)}. If the
461      * comparison returns <tt>true</tt>, this invocation returns
462      * <tt>true</tt>. Otherwise, the original return value is compared with
463      * <tt>"false"</tt>, again using {@link String#equalsIgnoreCase(String)}.
464      * If the comparison returns <tt>true</tt>, this invocation returns
465      * <tt>false</tt>. Otherwise, this invocation returns <tt>def</tt>.
466      *
467      * @param key key whose associated value is to be returned as a boolean.
468      * @param def the value to be returned in the event that this
469      * preference node has no value associated with <tt>key</tt>
470      * or the associated value cannot be interpreted as a boolean.
471      * @return the boolean value represented by the string associated with
472      * <tt>key</tt> in this preference node, or <tt>def</tt> if the
473      * associated value does not exist or cannot be interpreted as
474      * a boolean.
475      * @throws IllegalStateException if this node (or an ancestor) has been
476      * removed with the {@link #removeNode()} method.
477      * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
478      */

479     public boolean getBoolean(String JavaDoc key, boolean def) {
480         boolean result = def;
481         String JavaDoc value = get(key, null);
482         if (value != null) {
483             if (value.equalsIgnoreCase("true"))
484                 result = true;
485             else if (value.equalsIgnoreCase("false"))
486                 result = false;
487         }
488
489         return result;
490     }
491
492     /**
493      * Implements the <tt>putFloat</tt> method as per the specification in
494      * {@link Preferences#putFloat(String,float)}.
495      *
496      * <p>This implementation translates <tt>value</tt> to a string with
497      * {@link Float#toString(float)} and invokes {@link #put(String,String)}
498      * on the result.
499      *
500      * @param key key with which the string form of value is to be associated.
501      * @param value value whose string form is to be associated with key.
502      * @throws NullPointerException if key is <tt>null</tt>.
503      * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
504      * <tt>MAX_KEY_LENGTH</tt>.
505      * @throws IllegalStateException if this node (or an ancestor) has been
506      * removed with the {@link #removeNode()} method.
507      */

508     public void putFloat(String JavaDoc key, float value) {
509         put(key, Float.toString(value));
510     }
511
512     /**
513      * Implements the <tt>getFloat</tt> method as per the specification in
514      * {@link Preferences#getFloat(String,float)}.
515      *
516      * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
517      * null)</tt>}. If the return value is non-null, the implementation
518      * attempts to translate it to an <tt>float</tt> with
519      * {@link Float#parseFloat(String)}. If the attempt succeeds, the return
520      * value is returned by this method. Otherwise, <tt>def</tt> is returned.
521      *
522      * @param key key whose associated value is to be returned as a float.
523      * @param def the value to be returned in the event that this
524      * preference node has no value associated with <tt>key</tt>
525      * or the associated value cannot be interpreted as a float.
526      * @return the float value represented by the string associated with
527      * <tt>key</tt> in this preference node, or <tt>def</tt> if the
528      * associated value does not exist or cannot be interpreted as
529      * a float.
530      * @throws IllegalStateException if this node (or an ancestor) has been
531      * removed with the {@link #removeNode()} method.
532      * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
533      */

534     public float getFloat(String JavaDoc key, float def) {
535         float result = def;
536         try {
537             String JavaDoc value = get(key, null);
538             if (value != null)
539                 result = Float.parseFloat(value);
540         } catch (NumberFormatException JavaDoc e) {
541             // Ignoring exception causes specified default to be returned
542
}
543
544         return result;
545     }
546
547     /**
548      * Implements the <tt>putDouble</tt> method as per the specification in
549      * {@link Preferences#putDouble(String,double)}.
550      *
551      * <p>This implementation translates <tt>value</tt> to a string with
552      * {@link Double#toString(double)} and invokes {@link #put(String,String)}
553      * on the result.
554      *
555      * @param key key with which the string form of value is to be associated.
556      * @param value value whose string form is to be associated with key.
557      * @throws NullPointerException if key is <tt>null</tt>.
558      * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds
559      * <tt>MAX_KEY_LENGTH</tt>.
560      * @throws IllegalStateException if this node (or an ancestor) has been
561      * removed with the {@link #removeNode()} method.
562      */

563     public void putDouble(String JavaDoc key, double value) {
564         put(key, Double.toString(value));
565     }
566
567     /**
568      * Implements the <tt>getDouble</tt> method as per the specification in
569      * {@link Preferences#getDouble(String,double)}.
570      *
571      * <p>This implementation invokes {@link #get(String,String) <tt>get(key,
572      * null)</tt>}. If the return value is non-null, the implementation
573      * attempts to translate it to an <tt>double</tt> with
574      * {@link Double#parseDouble(String)}. If the attempt succeeds, the return
575      * value is returned by this method. Otherwise, <tt>def</tt> is returned.
576      *
577      * @param key key whose associated value is to be returned as a double.
578      * @param def the value to be returned in the event that this
579      * preference node has no value associated with <tt>key</tt>
580      * or the associated value cannot be interpreted as a double.
581      * @return the double value represented by the string associated with
582      * <tt>key</tt> in this preference node, or <tt>def</tt> if the
583      * associated value does not exist or cannot be interpreted as
584      * a double.
585      * @throws IllegalStateException if this node (or an ancestor) has been
586      * removed with the {@link #removeNode()} method.
587      * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>.
588      */

589     public double getDouble(String JavaDoc key, double def) {
590         double result = def;
591         try {
592             String JavaDoc value = get(key, null);
593             if (value != null)
594                 result = Double.parseDouble(value);
595         } catch (NumberFormatException JavaDoc e) {
596             // Ignoring exception causes specified default to be returned
597
}
598
599         return result;
600     }
601
602     /**
603      * Implements the <tt>putByteArray</tt> method as per the specification in
604      * {@link Preferences#putByteArray(String,byte[])}.
605      *
606      * @param key key with which the string form of value is to be associated.
607      * @param value value whose string form is to be associated with key.
608      * @throws NullPointerException if key or value is <tt>null</tt>.
609      * @throws IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH
610      * or if value.length exceeds MAX_VALUE_LENGTH*3/4.
611      * @throws IllegalStateException if this node (or an ancestor) has been
612      * removed with the {@link #removeNode()} method.
613      */

614     public void putByteArray(String JavaDoc key, byte[] value) {
615         put(key, Base64.byteArrayToBase64(value));
616     }
617
618     /**
619      * Implements the <tt>getByteArray</tt> method as per the specification in
620      * {@link Preferences#getByteArray(String,byte[])}.
621      *
622      * @param key key whose associated value is to be returned as a byte array.
623      * @param def the value to be returned in the event that this
624      * preference node has no value associated with <tt>key</tt>
625      * or the associated value cannot be interpreted as a byte array.
626      * @return the byte array value represented by the string associated with
627      * <tt>key</tt> in this preference node, or <tt>def</tt> if the
628      * associated value does not exist or cannot be interpreted as
629      * a byte array.
630      * @throws IllegalStateException if this node (or an ancestor) has been
631      * removed with the {@link #removeNode()} method.
632      * @throws NullPointerException if <tt>key</tt> is <tt>null</tt>. (A
633      * <tt>null</tt> value for <tt>def</tt> <i>is</i> permitted.)
634      */

635     public byte[] getByteArray(String JavaDoc key, byte[] def) {
636         byte[] result = def;
637         String JavaDoc value = get(key, null);
638         try {
639             if (value != null)
640                 result = Base64.base64ToByteArray(value);
641         }
642         catch (RuntimeException JavaDoc e) {
643             // Ignoring exception causes specified default to be returned
644
}
645
646         return result;
647     }
648
649     /**
650      * Implements the <tt>keys</tt> method as per the specification in
651      * {@link Preferences#keys()}.
652      *
653      * <p>This implementation obtains this preference node's lock, checks that
654      * the node has not been removed and invokes {@link #keysSpi()}.
655      *
656      * @return an array of the keys that have an associated value in this
657      * preference node.
658      * @throws BackingStoreException if this operation cannot be completed
659      * due to a failure in the backing store, or inability to
660      * communicate with it.
661      * @throws IllegalStateException if this node (or an ancestor) has been
662      * removed with the {@link #removeNode()} method.
663      */

664     public String JavaDoc[] keys() throws BackingStoreException JavaDoc {
665         synchronized(lock) {
666             if (removed)
667                 throw new IllegalStateException JavaDoc("Node has been removed.");
668
669             return keysSpi();
670         }
671     }
672
673     /**
674      * Implements the <tt>children</tt> method as per the specification in
675      * {@link Preferences#childrenNames()}.
676      *
677      * <p>This implementation obtains this preference node's lock, checks that
678      * the node has not been removed, constructs a <tt>TreeSet</tt> initialized
679      * to the names of children already cached (the children in this node's
680      * "child-cache"), invokes {@link #childrenNamesSpi()}, and adds all of the
681      * returned child-names into the set. The elements of the tree set are
682      * dumped into a <tt>String</tt> array using the <tt>toArray</tt> method,
683      * and this array is returned.
684      *
685      * @return the names of the children of this preference node.
686      * @throws BackingStoreException if this operation cannot be completed
687      * due to a failure in the backing store, or inability to
688      * communicate with it.
689      * @throws IllegalStateException if this node (or an ancestor) has been
690      * removed with the {@link #removeNode()} method.
691      * @see #cachedChildren()
692      */

693     public String JavaDoc[] childrenNames() throws BackingStoreException JavaDoc {
694         synchronized(lock) {
695             if (removed)
696                 throw new IllegalStateException JavaDoc("Node has been removed.");
697
698             Set s = new TreeSet(kidCache.keySet());
699             String JavaDoc[] kids = childrenNamesSpi();
700             for(int i=0; i<kids.length; i++)
701                 s.add(kids[i]);
702             return (String JavaDoc[]) s.toArray(EMPTY_STRING_ARRAY);
703         }
704     }
705
706     private static final String JavaDoc[] EMPTY_STRING_ARRAY = new String JavaDoc[0];
707
708     /**
709      * Returns all known unremoved children of this node.
710      *
711      * @return all known unremoved children of this node.
712      */

713     protected final AbstractPreferences JavaDoc[] cachedChildren() {
714         return (AbstractPreferences JavaDoc[]) kidCache.values().
715             toArray(EMPTY_ABSTRACT_PREFS_ARRAY);
716     }
717
718     private static final AbstractPreferences JavaDoc[] EMPTY_ABSTRACT_PREFS_ARRAY
719         = new AbstractPreferences JavaDoc[0];
720
721     /**
722      * Implements the <tt>parent</tt> method as per the specification in
723      * {@link Preferences#parent()}.
724      *
725      * <p>This implementation obtains this preference node's lock, checks that
726      * the node has not been removed and returns the parent value that was
727      * passed to this node's constructor.
728      *
729      * @return the parent of this preference node.
730      * @throws IllegalStateException if this node (or an ancestor) has been
731      * removed with the {@link #removeNode()} method.
732      */

733     public Preferences JavaDoc parent() {
734         synchronized(lock) {
735             if (removed)
736                 throw new IllegalStateException JavaDoc("Node has been removed.");
737
738             return parent;
739         }
740     }
741
742     /**
743      * Implements the <tt>node</tt> method as per the specification in
744      * {@link Preferences#node(String)}.
745      *
746      * <p>This implementation obtains this preference node's lock and checks
747      * that the node has not been removed. If <tt>path</tt> is <tt>""</tt>,
748      * this node is returned; if <tt>path</tt> is <tt>"/"</tt>, this node's
749      * root is returned. If the first character in <tt>path</tt> is
750      * not <tt>'/'</tt>, the implementation breaks <tt>path</tt> into
751      * tokens and recursively traverses the path from this node to the
752      * named node, "consuming" a name and a slash from <tt>path</tt> at
753      * each step of the traversal. At each step, the current node is locked
754      * and the node's child-cache is checked for the named node. If it is
755      * not found, the name is checked to make sure its length does not
756      * exceed <tt>MAX_NAME_LENGTH</tt>. Then the {@link #childSpi(String)}
757      * method is invoked, and the result stored in this node's child-cache.
758      * If the newly created <tt>Preferences</tt> object's {@link #newNode}
759      * field is <tt>true</tt> and there are any node change listeners,
760      * a notification event is enqueued for processing by the event dispatch
761      * thread.
762      *
763      * <p>When there are no more tokens, the last value found in the
764      * child-cache or returned by <tt>childSpi</tt> is returned by this
765      * method. If during the traversal, two <tt>"/"</tt> tokens occur
766      * consecutively, or the final token is <tt>"/"</tt> (rather than a name),
767      * an appropriate <tt>IllegalArgumentException</tt> is thrown.
768      *
769      * <p> If the first character of <tt>path</tt> is <tt>'/'</tt>
770      * (indicating an absolute path name name) this preference node's
771      * lock is dropped prior to breaking <tt>path</tt> into tokens, and
772      * this method recursively traverses the path starting from the root
773      * (rather than starting from this node). The traversal is otherwise
774      * identical to the one described for relative path names. Dropping
775      * the lock on this node prior to commencing the traversal at the root
776      * node is essential to avoid the possibility of deadlock, as per the
777      * {@link #lock locking invariant}.
778      *
779      * @param path the path name of the preference node to return.
780      * @return the specified preference node.
781      * @throws IllegalArgumentException if the path name is invalid (i.e.,
782      * it contains multiple consecutive slash characters, or ends
783      * with a slash character and is more than one character long).
784      * @throws IllegalStateException if this node (or an ancestor) has been
785      * removed with the {@link #removeNode()} method.
786      */

787     public Preferences JavaDoc node(String JavaDoc path) {
788         synchronized(lock) {
789             if (removed)
790                 throw new IllegalStateException JavaDoc("Node has been removed.");
791             if (path.equals(""))
792                 return this;
793             if (path.equals("/"))
794                 return root;
795             if (path.charAt(0) != '/')
796                 return node(new StringTokenizer(path, "/", true));
797         }
798
799         // Absolute path. Note that we've dropped our lock to avoid deadlock
800
return root.node(new StringTokenizer(path.substring(1), "/", true));
801     }
802
803     /**
804      * tokenizer contains <name> {'/' <name>}*
805      */

806     private Preferences JavaDoc node(StringTokenizer path) {
807         String JavaDoc token = path.nextToken();
808         if (token.equals("/")) // Check for consecutive slashes
809
throw new IllegalArgumentException JavaDoc("Consecutive slashes in path");
810         synchronized(lock) {
811             AbstractPreferences JavaDoc child=(AbstractPreferences JavaDoc)kidCache.get(token);
812             if (child == null) {
813                 if (token.length() > MAX_NAME_LENGTH)
814                     throw new IllegalArgumentException JavaDoc(
815                         "Node name " + token + " too long");
816                 child = childSpi(token);
817                 if (child.newNode)
818                     enqueueNodeAddedEvent(child);
819                 kidCache.put(token, child);
820             }
821             if (!path.hasMoreTokens())
822                 return child;
823             path.nextToken(); // Consume slash
824
if (!path.hasMoreTokens())
825                 throw new IllegalArgumentException JavaDoc("Path ends with slash");
826             return child.node(path);
827         }
828     }
829
830     /**
831      * Implements the <tt>nodeExists</tt> method as per the specification in
832      * {@link Preferences#nodeExists(String)}.
833      *
834      * <p>This implementation is very similar to {@link #node(String)},
835      * except that {@link #getChild(String)} is used instead of {@link
836      * #childSpi(String)}.
837      *
838      * @param path the path name of the node whose existence is to be checked.
839      * @return true if the specified node exists.
840      * @throws BackingStoreException if this operation cannot be completed
841      * due to a failure in the backing store, or inability to
842      * communicate with it.
843      * @throws IllegalArgumentException if the path name is invalid (i.e.,
844      * it contains multiple consecutive slash characters, or ends
845      * with a slash character and is more than one character long).
846      * @throws IllegalStateException if this node (or an ancestor) has been
847      * removed with the {@link #removeNode()} method and
848      * <tt>pathname</tt> is not the empty string (<tt>""</tt>).
849      */

850     public boolean nodeExists(String JavaDoc path)
851         throws BackingStoreException JavaDoc
852     {
853         synchronized(lock) {
854             if (path.equals(""))
855                 return !removed;
856             if (removed)
857                 throw new IllegalStateException JavaDoc("Node has been removed.");
858             if (path.equals("/"))
859                 return true;
860             if (path.charAt(0) != '/')
861                 return nodeExists(new StringTokenizer(path, "/", true));
862         }
863
864         // Absolute path. Note that we've dropped our lock to avoid deadlock
865
return root.nodeExists(new StringTokenizer(path.substring(1), "/",
866                                                    true));
867     }
868
869     /**
870      * tokenizer contains <name> {'/' <name>}*
871      */

872     private boolean nodeExists(StringTokenizer path)
873         throws BackingStoreException JavaDoc
874     {
875         String JavaDoc token = path.nextToken();
876         if (token.equals("/")) // Check for consecutive slashes
877
throw new IllegalArgumentException JavaDoc("Consecutive slashes in path");
878         synchronized(lock) {
879             AbstractPreferences JavaDoc child=(AbstractPreferences JavaDoc)kidCache.get(token);
880             if (child == null)
881                 child = getChild(token);
882             if (child==null)
883                 return false;
884             if (!path.hasMoreTokens())
885                 return true;
886             path.nextToken(); // Consume slash
887
if (!path.hasMoreTokens())
888                 throw new IllegalArgumentException JavaDoc("Path ends with slash");
889             return child.nodeExists(path);
890         }
891     }
892
893     /**
894
895      * Implements the <tt>removeNode()</tt> method as per the specification in
896      * {@link Preferences#removeNode()}.
897      *
898      * <p>This implementation checks to see that this node is the root; if so,
899      * it throws an appropriate exception. Then, it locks this node's parent,
900      * and calls a recursive helper method that traverses the subtree rooted at
901      * this node. The recursive method locks the node on which it was called,
902      * checks that it has not already been removed, and then ensures that all
903      * of its children are cached: The {@link #childrenNamesSpi()} method is
904      * invoked and each returned child name is checked for containment in the
905      * child-cache. If a child is not already cached, the {@link
906      * #childSpi(String)} method is invoked to create a <tt>Preferences</tt>
907      * instance for it, and this instance is put into the child-cache. Then
908      * the helper method calls itself recursively on each node contained in its
909      * child-cache. Next, it invokes {@link #removeNodeSpi()}, marks itself
910      * as removed, and removes itself from its parent's child-cache. Finally,
911      * if there are any node change listeners, it enqueues a notification
912      * event for processing by the event dispatch thread.
913      *
914      * <p>Note that the helper method is always invoked with all ancestors up
915      * to the "closest non-removed ancestor" locked.
916      *
917      * @throws IllegalStateException if this node (or an ancestor) has already
918      * been removed with the {@link #removeNode()} method.
919      * @throws UnsupportedOperationException if this method is invoked on
920      * the root node.
921      * @throws BackingStoreException if this operation cannot be completed
922      * due to a failure in the backing store, or inability to
923      * communicate with it.
924      */

925     public void removeNode() throws BackingStoreException JavaDoc {
926         if (this==root)
927             throw new UnsupportedOperationException JavaDoc("Can't remove the root!");
928         synchronized(parent.lock) {
929             removeNode2();
930             parent.kidCache.remove(name);
931         }
932     }
933
934     /*
935      * Called with locks on all nodes on path from parent of "removal root"
936      * to this (including the former but excluding the latter).
937      */

938     private void removeNode2() throws BackingStoreException JavaDoc {
939         synchronized(lock) {
940             if (removed)
941                 throw new IllegalStateException JavaDoc("Node already removed.");
942
943             // Ensure that all children are cached
944
String JavaDoc[] kidNames = childrenNamesSpi();
945             for (int i=0; i<kidNames.length; i++)
946                 if (!kidCache.containsKey(kidNames[i]))
947                     kidCache.put(kidNames[i], childSpi(kidNames[i]));
948
949             // Recursively remove all cached children
950
for (Iterator i=kidCache.values().iterator(); i.hasNext(); )
951                 ((AbstractPreferences JavaDoc)i.next()).removeNode2();
952             kidCache.clear();
953             
954             // Now we have no descendants - it's time to die!
955
removeNodeSpi();
956             removed = true;
957             parent.enqueueNodeRemovedEvent(this);
958         }
959     }
960
961     /**
962      * Implements the <tt>name</tt> method as per the specification in
963      * {@link Preferences#name()}.
964      *
965      * <p>This implementation merely returns the name that was
966      * passed to this node's constructor.
967      *
968      * @return this preference node's name, relative to its parent.
969      */

970     public String JavaDoc name() {
971         return name;
972     }
973
974     /**
975      * Implements the <tt>absolutePath</tt> method as per the specification in
976      * {@link Preferences#absolutePath()}.
977      *
978      * <p>This implementation merely returns the absolute path name that
979      * was computed at the time that this node was constructed (based on
980      * the name that was passed to this node's constructor, and the names
981      * that were passed to this node's ancestors' constructors).
982      *
983      * @return this preference node's absolute path name.
984      */

985     public String JavaDoc absolutePath() {
986         return absolutePath;
987     }
988
989     /**
990      * Implements the <tt>isUserNode</tt> method as per the specification in
991      * {@link Preferences#isUserNode()}.
992      *
993      * <p>This implementation compares this node's root node (which is stored
994      * in a private field) with the value returned by
995      * {@link Preferences#userRoot()}. If the two object references are
996      * identical, this method returns true.
997      *
998      * @return <tt>true</tt> if this preference node is in the user
999      * preference tree, <tt>false</tt> if it's in the system
1000     * preference tree.
1001     */

1002    public boolean isUserNode() {
1003        Boolean JavaDoc result = (Boolean JavaDoc)
1004          AccessController.doPrivileged( new PrivilegedAction JavaDoc() {
1005            public Object JavaDoc run() {
1006                return new Boolean JavaDoc(root == Preferences.userRoot());
1007            }
1008        });
1009        return result.booleanValue();
1010    }
1011
1012    public void addPreferenceChangeListener(PreferenceChangeListener JavaDoc pcl) {
1013        if (pcl==null)
1014            throw new NullPointerException JavaDoc("Change listener is null.");
1015        synchronized(lock) {
1016            if (removed)
1017                throw new IllegalStateException JavaDoc("Node has been removed.");
1018
1019            // Copy-on-write
1020
PreferenceChangeListener JavaDoc[] old = prefListeners;
1021            prefListeners = new PreferenceChangeListener JavaDoc[old.length + 1];
1022            System.arraycopy(old, 0, prefListeners, 0, old.length);
1023            prefListeners[old.length] = pcl;
1024        }
1025        startEventDispatchThreadIfNecessary();
1026    }
1027
1028    public void removePreferenceChangeListener(PreferenceChangeListener JavaDoc pcl) {
1029        synchronized(lock) {
1030            if (removed)
1031                throw new IllegalStateException JavaDoc("Node has been removed.");
1032            if ((prefListeners == null) || (prefListeners.length == 0))
1033                throw new IllegalArgumentException JavaDoc("Listener not registered.");
1034
1035            // Copy-on-write
1036
PreferenceChangeListener JavaDoc[] newPl =
1037                new PreferenceChangeListener JavaDoc[prefListeners.length - 1];
1038            int i = 0;
1039            while (i < newPl.length && prefListeners[i] != pcl)
1040                newPl[i] = prefListeners[i++];
1041
1042            if (i == newPl.length && prefListeners[i] != pcl)
1043                throw new IllegalArgumentException JavaDoc("Listener not registered.");
1044            while (i < newPl.length)
1045                newPl[i] = prefListeners[++i];
1046            prefListeners = newPl;
1047        }
1048    }
1049
1050    public void addNodeChangeListener(NodeChangeListener JavaDoc ncl) {
1051        if (ncl==null)
1052            throw new NullPointerException JavaDoc("Change listener is null.");
1053        synchronized(lock) {
1054            if (removed)
1055                throw new IllegalStateException JavaDoc("Node has been removed.");
1056
1057            // Copy-on-write
1058
if (nodeListeners == null) {
1059                nodeListeners = new NodeChangeListener JavaDoc[1];
1060                nodeListeners[0] = ncl;
1061            } else {
1062                NodeChangeListener JavaDoc[] old = nodeListeners;
1063                nodeListeners = new NodeChangeListener JavaDoc[old.length + 1];
1064                System.arraycopy(old, 0, nodeListeners, 0, old.length);
1065                nodeListeners[old.length] = ncl;
1066            }
1067        }
1068        startEventDispatchThreadIfNecessary();
1069    }
1070
1071    public void removeNodeChangeListener(NodeChangeListener JavaDoc ncl) {
1072        synchronized(lock) {
1073            if (removed)
1074                throw new IllegalStateException JavaDoc("Node has been removed.");
1075            if ((nodeListeners == null) || (nodeListeners.length == 0))
1076                throw new IllegalArgumentException JavaDoc("Listener not registered.");
1077
1078            // Copy-on-write
1079
NodeChangeListener JavaDoc[] newNl =
1080                new NodeChangeListener JavaDoc[nodeListeners.length - 1];
1081            int i = 0;
1082            while (i < nodeListeners.length && nodeListeners[i] != ncl)
1083                newNl[i] = nodeListeners[i++];
1084
1085            if (i == nodeListeners.length)
1086                throw new IllegalArgumentException JavaDoc("Listener not registered.");
1087            while (i < newNl.length)
1088                newNl[i] = nodeListeners[++i];
1089            nodeListeners = newNl;
1090        }
1091    }
1092
1093    // "SPI" METHODS
1094

1095    /**
1096     * Put the given key-value association into this preference node. It is
1097     * guaranteed that <tt>key</tt> and <tt>value</tt> are non-null and of
1098     * legal length. Also, it is guaranteed that this node has not been
1099     * removed. (The implementor needn't check for any of these things.)
1100     *
1101     * <p>This method is invoked with the lock on this node held.
1102     */

1103    protected abstract void putSpi(String JavaDoc key, String JavaDoc value);
1104
1105    /**
1106     * Return the value associated with the specified key at this preference
1107     * node, or <tt>null</tt> if there is no association for this key, or the
1108     * association cannot be determined at this time. It is guaranteed that
1109     * <tt>key</tt> is non-null. Also, it is guaranteed that this node has
1110     * not been removed. (The implementor needn't check for either of these
1111     * things.)
1112     *
1113     * <p> Generally speaking, this method should not throw an exception
1114     * under any circumstances. If, however, if it does throw an exception,
1115     * the exception will be intercepted and treated as a <tt>null</tt>
1116     * return value.
1117     *
1118     * <p>This method is invoked with the lock on this node held.
1119     *
1120     * @return the value associated with the specified key at this preference
1121     * node, or <tt>null</tt> if there is no association for this
1122     * key, or the association cannot be determined at this time.
1123     */

1124    protected abstract String JavaDoc getSpi(String JavaDoc key);
1125
1126    /**
1127     * Remove the association (if any) for the specified key at this
1128     * preference node. It is guaranteed that <tt>key</tt> is non-null.
1129     * Also, it is guaranteed that this node has not been removed.
1130     * (The implementor needn't check for either of these things.)
1131     *
1132     * <p>This method is invoked with the lock on this node held.
1133     */

1134    protected abstract void removeSpi(String JavaDoc key);
1135
1136    /**
1137     * Removes this preference node, invalidating it and any preferences that
1138     * it contains. The named child will have no descendants at the time this
1139     * invocation is made (i.e., the {@link Preferences#removeNode()} method
1140     * invokes this method repeatedly in a bottom-up fashion, removing each of
1141     * a node's descendants before removing the node itself).
1142     *
1143     * <p>This method is invoked with the lock held on this node and its
1144     * parent (and all ancestors that are being removed as a
1145     * result of a single invocation to {@link Preferences#removeNode()}).
1146     *
1147     * <p>The removal of a node needn't become persistent until the
1148     * <tt>flush</tt> method is invoked on this node (or an ancestor).
1149     *
1150     * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
1151     * will propagate out beyond the enclosing {@link #removeNode()}
1152     * invocation.
1153     *
1154     * @throws BackingStoreException if this operation cannot be completed
1155     * due to a failure in the backing store, or inability to
1156     * communicate with it.
1157     */

1158    protected abstract void removeNodeSpi() throws BackingStoreException JavaDoc;
1159
1160    /**
1161     * Returns all of the keys that have an associated value in this
1162     * preference node. (The returned array will be of size zero if
1163     * this node has no preferences.) It is guaranteed that this node has not
1164     * been removed.
1165     *
1166     * <p>This method is invoked with the lock on this node held.
1167     *
1168     * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
1169     * will propagate out beyond the enclosing {@link #keys()} invocation.
1170     *
1171     * @return an array of the keys that have an associated value in this
1172     * preference node.
1173     * @throws BackingStoreException if this operation cannot be completed
1174     * due to a failure in the backing store, or inability to
1175     * communicate with it.
1176     */

1177    protected abstract String JavaDoc[] keysSpi() throws BackingStoreException JavaDoc;
1178
1179    /**
1180     * Returns the names of the children of this preference node. (The
1181     * returned array will be of size zero if this node has no children.)
1182     * This method need not return the names of any nodes already cached,
1183     * but may do so without harm.
1184     *
1185     * <p>This method is invoked with the lock on this node held.
1186     *
1187     * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
1188     * will propagate out beyond the enclosing {@link #childrenNames()}
1189     * invocation.
1190     *
1191     * @return an array containing the names of the children of this
1192     * preference node.
1193     * @throws BackingStoreException if this operation cannot be completed
1194     * due to a failure in the backing store, or inability to
1195     * communicate with it.
1196     */

1197    protected abstract String JavaDoc[] childrenNamesSpi()
1198        throws BackingStoreException JavaDoc;
1199
1200    /**
1201     * Returns the named child if it exists, or <tt>null</tt> if it does not.
1202     * It is guaranteed that <tt>nodeName</tt> is non-null, non-empty,
1203     * does not contain the slash character ('/'), and is no longer than
1204     * {@link #MAX_NAME_LENGTH} characters. Also, it is guaranteed
1205     * that this node has not been removed. (The implementor needn't check
1206     * for any of these things if he chooses to override this method.)
1207     *
1208     * <p>Finally, it is guaranteed that the named node has not been returned
1209     * by a previous invocation of this method or {@link #childSpi} after the
1210     * last time that it was removed. In other words, a cached value will
1211     * always be used in preference to invoking this method. (The implementor
1212     * needn't maintain his own cache of previously returned children if he
1213     * chooses to override this method.)
1214     *
1215     * <p>This implementation obtains this preference node's lock, invokes
1216     * {@link #childrenNames()} to get an array of the names of this node's
1217     * children, and iterates over the array comparing the name of each child
1218     * with the specified node name. If a child node has the correct name,
1219     * the {@link #childSpi(String)} method is invoked and the resulting
1220     * node is returned. If the iteration completes without finding the
1221     * specified name, <tt>null</tt> is returned.
1222     *
1223     * @param nodeName name of the child to be searched for.
1224     * @return the named child if it exists, or null if it does not.
1225     * @throws BackingStoreException if this operation cannot be completed
1226     * due to a failure in the backing store, or inability to
1227     * communicate with it.
1228     */

1229    protected AbstractPreferences JavaDoc getChild(String JavaDoc nodeName)
1230            throws BackingStoreException JavaDoc {
1231        synchronized(lock) {
1232            // assert kidCache.get(nodeName)==null;
1233
String JavaDoc[] kidNames = childrenNames();
1234            for (int i=0; i<kidNames.length; i++)
1235                if (kidNames[i].equals(nodeName))
1236                    return childSpi(kidNames[i]);
1237        }
1238        return null;
1239    }
1240
1241    /**
1242     * Returns the named child of this preference node, creating it if it does
1243     * not already exist. It is guaranteed that <tt>name</tt> is non-null,
1244     * non-empty, does not contain the slash character ('/'), and is no longer
1245     * than {@link #MAX_NAME_LENGTH} characters. Also, it is guaranteed that
1246     * this node has not been removed. (The implementor needn't check for any
1247     * of these things.)
1248     *
1249     * <p>Finally, it is guaranteed that the named node has not been returned
1250     * by a previous invocation of this method or {@link #getChild(String)}
1251     * after the last time that it was removed. In other words, a cached
1252     * value will always be used in preference to invoking this method.
1253     * Subclasses need not maintain their own cache of previously returned
1254     * children.
1255     *
1256     * <p>The implementer must ensure that the returned node has not been
1257     * removed. If a like-named child of this node was previously removed, the
1258     * implementer must return a newly constructed <tt>AbstractPreferences</tt>
1259     * node; once removed, an <tt>AbstractPreferences</tt> node
1260     * cannot be "resuscitated."
1261     *
1262     * <p>If this method causes a node to be created, this node is not
1263     * guaranteed to be persistent until the <tt>flush</tt> method is
1264     * invoked on this node or one of its ancestors (or descendants).
1265     *
1266     * <p>This method is invoked with the lock on this node held.
1267     *
1268     * @param name The name of the child node to return, relative to
1269     * this preference node.
1270     * @return The named child node.
1271     */

1272    protected abstract AbstractPreferences JavaDoc childSpi(String JavaDoc name);
1273
1274    /**
1275     * Returns the absolute path name of this preferences node.
1276     */

1277    public String JavaDoc toString() {
1278        return (this.isUserNode() ? "User" : "System") +
1279               " Preference Node: " + this.absolutePath();
1280    }
1281
1282    /**
1283     * Implements the <tt>sync</tt> method as per the specification in
1284     * {@link Preferences#sync()}.
1285     *
1286     * <p>This implementation calls a recursive helper method that locks this
1287     * node, invokes syncSpi() on it, unlocks this node, and recursively
1288     * invokes this method on each "cached child." A cached child is a child
1289     * of this node that has been created in this VM and not subsequently
1290     * removed. In effect, this method does a depth first traversal of the
1291     * "cached subtree" rooted at this node, calling syncSpi() on each node in
1292     * the subTree while only that node is locked. Note that syncSpi() is
1293     * invoked top-down.
1294     *
1295     * @throws BackingStoreException if this operation cannot be completed
1296     * due to a failure in the backing store, or inability to
1297     * communicate with it.
1298     * @throws IllegalStateException if this node (or an ancestor) has been
1299     * removed with the {@link #removeNode()} method.
1300     * @see #flush()
1301     */

1302    public void sync() throws BackingStoreException JavaDoc {
1303        sync2();
1304    }
1305
1306    private void sync2() throws BackingStoreException JavaDoc {
1307        AbstractPreferences JavaDoc[] cachedKids;
1308
1309        synchronized(lock) {
1310        if (removed)
1311        throw new IllegalStateException JavaDoc("Node has been removed");
1312        syncSpi();
1313        cachedKids = cachedChildren();
1314        }
1315
1316        for (int i=0; i<cachedKids.length; i++)
1317            cachedKids[i].sync2();
1318    }
1319
1320    /**
1321     * This method is invoked with this node locked. The contract of this
1322     * method is to synchronize any cached preferences stored at this node
1323     * with any stored in the backing store. (It is perfectly possible that
1324     * this node does not exist on the backing store, either because it has
1325     * been deleted by another VM, or because it has not yet been created.)
1326     * Note that this method should <i>not</i> synchronize the preferences in
1327     * any subnodes of this node. If the backing store naturally syncs an
1328     * entire subtree at once, the implementer is encouraged to override
1329     * sync(), rather than merely overriding this method.
1330     *
1331     * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
1332     * will propagate out beyond the enclosing {@link #sync()} invocation.
1333     *
1334     * @throws BackingStoreException if this operation cannot be completed
1335     * due to a failure in the backing store, or inability to
1336     * communicate with it.
1337     */

1338    protected abstract void syncSpi() throws BackingStoreException JavaDoc;
1339
1340    /**
1341     * Implements the <tt>flush</tt> method as per the specification in
1342     * {@link Preferences#flush()}.
1343     *
1344     * <p>This implementation calls a recursive helper method that locks this
1345     * node, invokes flushSpi() on it, unlocks this node, and recursively
1346     * invokes this method on each "cached child." A cached child is a child
1347     * of this node that has been created in this VM and not subsequently
1348     * removed. In effect, this method does a depth first traversal of the
1349     * "cached subtree" rooted at this node, calling flushSpi() on each node in
1350     * the subTree while only that node is locked. Note that flushSpi() is
1351     * invoked top-down.
1352     *
1353     * <p> If this method is invoked on a node that has been removed with
1354     * the {@link #removeNode()} method, flushSpi() is invoked on this node,
1355     * but not on others.
1356     *
1357     * @throws BackingStoreException if this operation cannot be completed
1358     * due to a failure in the backing store, or inability to
1359     * communicate with it.
1360     * @see #flush()
1361     */

1362    public void flush() throws BackingStoreException JavaDoc {
1363        flush2();
1364    }
1365
1366    private void flush2() throws BackingStoreException JavaDoc {
1367        AbstractPreferences JavaDoc[] cachedKids;
1368    
1369    synchronized(lock) {
1370        flushSpi();
1371        if(removed)
1372        return;
1373            cachedKids = cachedChildren();
1374        }
1375    
1376        for (int i = 0; i < cachedKids.length; i++)
1377            cachedKids[i].flush2();
1378    }
1379
1380    /**
1381     * This method is invoked with this node locked. The contract of this
1382     * method is to force any cached changes in the contents of this
1383     * preference node to the backing store, guaranteeing their persistence.
1384     * (It is perfectly possible that this node does not exist on the backing
1385     * store, either because it has been deleted by another VM, or because it
1386     * has not yet been created.) Note that this method should <i>not</i>
1387     * flush the preferences in any subnodes of this node. If the backing
1388     * store naturally flushes an entire subtree at once, the implementer is
1389     * encouraged to override flush(), rather than merely overriding this
1390     * method.
1391     *
1392     * <p>If this node throws a <tt>BackingStoreException</tt>, the exception
1393     * will propagate out beyond the enclosing {@link #flush()} invocation.
1394     *
1395     * @throws BackingStoreException if this operation cannot be completed
1396     * due to a failure in the backing store, or inability to
1397     * communicate with it.
1398     */

1399    protected abstract void flushSpi() throws BackingStoreException JavaDoc;
1400
1401    /**
1402     * Returns <tt>true</tt> iff this node (or an ancestor) has been
1403     * removed with the {@link #removeNode()} method. This method
1404     * locks this node prior to returning the contents of the private
1405     * field used to track this state.
1406     *
1407     * @return <tt>true</tt> iff this node (or an ancestor) has been
1408     * removed with the {@link #removeNode()} method.
1409     */

1410    protected boolean isRemoved() {
1411        synchronized(lock) {
1412            return removed;
1413        }
1414    }
1415
1416    /**
1417     * Queue of pending notification events. When a preference or node
1418     * change event for which there are one or more listeners occurs,
1419     * it is placed on this queue and the queue is notified. A background
1420     * thread waits on this queue and delivers the events. This decouples
1421     * event delivery from preference activity, greatly simplifying
1422     * locking and reducing opportunity for deadlock.
1423     */

1424    private static final List eventQueue = new LinkedList();
1425
1426    /**
1427     * These two classes are used to distinguish NodeChangeEvents on
1428     * eventQueue so the event dispatch thread knows whether to call
1429     * childAdded or childRemoved.
1430     */

1431    private class NodeAddedEvent extends NodeChangeEvent JavaDoc {
1432    private static final long serialVersionUID = -6743557530157328528L;
1433        NodeAddedEvent(Preferences JavaDoc parent, Preferences JavaDoc child) {
1434            super(parent, child);
1435        }
1436    }
1437    private class NodeRemovedEvent extends NodeChangeEvent JavaDoc {
1438    private static final long serialVersionUID = 8735497392918824837L;
1439        NodeRemovedEvent(Preferences JavaDoc parent, Preferences JavaDoc child) {
1440            super(parent, child);
1441        }
1442    }
1443
1444    /**
1445     * A single background thread ("the event notification thread") monitors
1446     * the event queue and delivers events that are placed on the queue.
1447     */

1448    private static class EventDispatchThread extends Thread JavaDoc {
1449        public void run() {
1450            while(true) {
1451                // Wait on eventQueue till an event is present
1452
EventObject event = null;
1453                synchronized(eventQueue) {
1454                    try {
1455                        while (eventQueue.isEmpty())
1456                            eventQueue.wait();
1457                        event = (EventObject) eventQueue.remove(0);
1458                    } catch (InterruptedException JavaDoc e) {
1459                        // XXX Log "Event dispatch thread interrupted. Exiting"
1460
return;
1461                    }
1462                }
1463
1464                // Now we have event & hold no locks; deliver evt to listeners
1465
AbstractPreferences JavaDoc SRC=(AbstractPreferences JavaDoc)event.getSource();
1466                if (event instanceof PreferenceChangeEvent JavaDoc) {
1467                    PreferenceChangeEvent JavaDoc pce = (PreferenceChangeEvent JavaDoc)event;
1468                    PreferenceChangeListener JavaDoc[] listeners = src.prefListeners();
1469                    for (int i=0; i<listeners.length; i++)
1470                        listeners[i].preferenceChange(pce);
1471                } else {
1472                    NodeChangeEvent JavaDoc nce = (NodeChangeEvent JavaDoc)event;
1473                    NodeChangeListener JavaDoc[] listeners = src.nodeListeners();
1474                    if (nce instanceof NodeAddedEvent) {
1475                        for (int i=0; i<listeners.length; i++)
1476                            listeners[i].childAdded(nce);
1477                    } else {
1478                        // assert nce instanceof NodeRemovedEvent;
1479
for (int i=0; i<listeners.length; i++)
1480                            listeners[i].childRemoved(nce);
1481                    }
1482                }
1483            }
1484        }
1485    }
1486
1487    private static Thread JavaDoc eventDispatchThread = null;
1488
1489    /**
1490     * This method starts the event dispatch thread the first time it
1491     * is called. The event dispatch thread will be started only
1492     * if someone registers a listener.
1493     */

1494    private static synchronized void startEventDispatchThreadIfNecessary() {
1495        if (eventDispatchThread == null) {
1496            // XXX Log "Starting event dispatch thread"
1497
eventDispatchThread = new EventDispatchThread();
1498            eventDispatchThread.setDaemon(true);
1499            eventDispatchThread.start();
1500        }
1501    }
1502
1503    /**
1504     * Return this node's preference/node change listeners. Even though
1505     * we're using a copy-on-write lists, we use synchronized accessors to
1506     * ensure information transmission from the writing thread to the
1507     * reading thread.
1508     */

1509    PreferenceChangeListener JavaDoc[] prefListeners() {
1510        synchronized(lock) {
1511            return prefListeners;
1512        }
1513    }
1514    NodeChangeListener JavaDoc[] nodeListeners() {
1515        synchronized(lock) {
1516            return nodeListeners;
1517        }
1518    }
1519
1520    /**
1521     * Enqueue a preference change event for delivery to registered
1522     * preference change listeners unless there are no registered
1523     * listeners. Invoked with this.lock held.
1524     */

1525    private void enqueuePreferenceChangeEvent(String JavaDoc key, String JavaDoc newValue) {
1526        if (prefListeners.length != 0) {
1527            synchronized(eventQueue) {
1528                eventQueue.add(new PreferenceChangeEvent JavaDoc(this, key, newValue));
1529                eventQueue.notify();
1530            }
1531        }
1532    }
1533
1534    /**
1535     * Enqueue a "node added" event for delivery to registered node change
1536     * listeners unless there are no registered listeners. Invoked with
1537     * this.lock held.
1538     */

1539    private void enqueueNodeAddedEvent(Preferences JavaDoc child) {
1540        if (nodeListeners.length != 0) {
1541            synchronized(eventQueue) {
1542                eventQueue.add(new NodeAddedEvent(this, child));
1543                eventQueue.notify();
1544            }
1545        }
1546    }
1547
1548    /**
1549     * Enqueue a "node removed" event for delivery to registered node change
1550     * listeners unless there are no registered listeners. Invoked with
1551     * this.lock held.
1552     */

1553    private void enqueueNodeRemovedEvent(Preferences JavaDoc child) {
1554        if (nodeListeners.length != 0) {
1555            synchronized(eventQueue) {
1556                eventQueue.add(new NodeRemovedEvent(this, child));
1557                eventQueue.notify();
1558            }
1559        }
1560    }
1561
1562    /**
1563     * Implements the <tt>exportNode</tt> method as per the specification in
1564     * {@link Preferences#exportNode(OutputStream)}.
1565     *
1566     * @param os the output stream on which to emit the XML document.
1567     * @throws IOException if writing to the specified output stream
1568     * results in an <tt>IOException</tt>.
1569     * @throws BackingStoreException if preference data cannot be read from
1570     * backing store.
1571     */

1572    public void exportNode(OutputStream os)
1573        throws IOException, BackingStoreException JavaDoc
1574    {
1575        XmlSupport.export(os, this, false);
1576    }
1577
1578    /**
1579     * Implements the <tt>exportSubtree</tt> method as per the specification in
1580     * {@link Preferences#exportSubtree(OutputStream)}.
1581     *
1582     * @param os the output stream on which to emit the XML document.
1583     * @throws IOException if writing to the specified output stream
1584     * results in an <tt>IOException</tt>.
1585     * @throws BackingStoreException if preference data cannot be read from
1586     * backing store.
1587     */

1588    public void exportSubtree(OutputStream os)
1589        throws IOException, BackingStoreException JavaDoc
1590    {
1591        XmlSupport.export(os, this, true);
1592    }
1593}
1594
Popular Tags