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               &n