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