FileDocCategorySizeDatePackage
AbstractPreferences.javaAPI DocJava SE 6 API69717Tue Jun 10 00:26:00 BST 2008java.util.prefs

AbstractPreferences

public abstract class AbstractPreferences extends Preferences
This class provides a skeletal implementation of the {@link Preferences} class, greatly easing the task of implementing it.

This class is for Preferences implementers only. Normal users of the Preferences facility should have no need to consult this documentation. The {@link Preferences} documentation should suffice.

Implementors must override the nine abstract service-provider interface (SPI) methods: {@link #getSpi(String)}, {@link #putSpi(String,String)}, {@link #removeSpi(String)}, {@link #childSpi(String)}, {@link #removeNodeSpi()}, {@link #keysSpi()}, {@link #childrenNamesSpi()}, {@link #syncSpi()} and {@link #flushSpi()}. All of the concrete methods specify precisely how they are implemented atop these SPI methods. The implementor may, at his discretion, override one or more of the concrete methods if the default implementation is unsatisfactory for any reason, such as performance.

The SPI methods fall into three groups concerning exception behavior. The getSpi method should never throw exceptions, but it doesn't really matter, as any exception thrown by this method will be intercepted by {@link #get(String,String)}, which will return the specified default value to the caller. The removeNodeSpi, keysSpi, childrenNamesSpi, syncSpi and flushSpi methods are specified to throw {@link BackingStoreException}, and the implementation is required to throw this checked exception if it is unable to perform the operation. The exception propagates outward, causing the corresponding API method to fail.

The remaining SPI methods {@link #putSpi(String,String)}, {@link #removeSpi(String)} and {@link #childSpi(String)} have more complicated exception behavior. They are not specified to throw BackingStoreException, as they can generally obey their contracts even if the backing store is unavailable. This is true because they return no information and their effects are not required to become permanent until a subsequent call to {@link Preferences#flush()} or {@link Preferences#sync()}. Generally speaking, these SPI methods should not throw exceptions. In some implementations, there may be circumstances under which these calls cannot even enqueue the requested operation for later processing. Even under these circumstances it is generally better to simply ignore the invocation and return, rather than throwing an exception. Under these circumstances, however, all subsequent invocations of flush() and sync should return false, as returning true would imply that all previous operations had successfully been made permanent.

There is one circumstance under which putSpi, removeSpi and childSpi should throw an exception: if the caller lacks sufficient privileges on the underlying operating system to perform the requested operation. This will, for instance, occur on most systems if a non-privileged user attempts to modify system preferences. (The required privileges will vary from implementation to implementation. On some implementations, they are the right to modify the contents of some directory in the file system; on others they are the right to modify contents of some key in a registry.) Under any of these circumstances, it would generally be undesirable to let the program continue executing as if these operations would become permanent at a later time. While implementations are not required to throw an exception under these circumstances, they are encouraged to do so. A {@link SecurityException} would be appropriate.

Most of the SPI methods require the implementation to read or write information at a preferences node. The implementor should beware of the fact that another VM may have concurrently deleted this node from the backing store. It is the implementation's responsibility to recreate the node if it has been deleted.

Implementation note: In Sun's default Preferences implementations, the user's identity is inherited from the underlying operating system and does not change for the lifetime of the virtual machine. It is recognized that server-side Preferences implementations may have the user identity change from request to request, implicitly passed to Preferences methods via the use of a static {@link ThreadLocal} instance. Authors of such implementations are strongly encouraged to determine the user at the time preferences are accessed (for example by the {@link #get(String,String)} or {@link #put(String,String)} method) rather than permanently associating a user with each Preferences instance. The latter behavior conflicts with normal Preferences usage and would lead to great confusion.

author
Josh Bloch
version
1.25, 06/06/06
see
Preferences
since
1.4

Fields Summary
private final String
name
Our name relative to parent.
private final String
absolutePath
Our absolute path name.
final AbstractPreferences
parent
Our parent node.
private final AbstractPreferences
root
Our root node.
protected boolean
newNode
This field should be true if this node did not exist in the backing store prior to the creation of this object. The field is initialized to false, but may be set to true by a subclass constructor (and should not be modified thereafter). This field indicates whether a node change event should be fired when creation is complete.
private Map
kidCache
All known unremoved children of this node. (This "cache" is consulted prior to calling childSpi() or getChild().
private boolean
removed
This field is used to keep track of whether or not this node has been removed. Once it's set to true, it will never be reset to false.
private PreferenceChangeListener[]
prefListeners
Registered preference change listeners.
private NodeChangeListener[]
nodeListeners
Registered node change listeners.
protected final Object
lock
An object whose monitor is used to lock this node. This object is used in preference to the node itself to reduce the likelihood of intentional or unintentional denial of service due to a locked node. To avoid deadlock, a node is never locked by a thread that holds a lock on a descendant of that node.
private static final String[]
EMPTY_STRING_ARRAY
private static final AbstractPreferences[]
EMPTY_ABSTRACT_PREFS_ARRAY
private static final List
eventQueue
Queue of pending notification events. When a preference or node change event for which there are one or more listeners occurs, it is placed on this queue and the queue is notified. A background thread waits on this queue and delivers the events. This decouples event delivery from preference activity, greatly simplifying locking and reducing opportunity for deadlock.
private static Thread
eventDispatchThread
Constructors Summary
protected AbstractPreferences(AbstractPreferences parent, String name)
Creates a preference node with the specified parent and the specified name relative to its parent.

param
parent the parent of this preference node, or null if this is the root.
param
name the name of this preference node, relative to its parent, or "" if this is the root.
throws
IllegalArgumentException if name contains a slash ('/'), or parent is null and name isn't "".


                                                                                                                          
         
        if (parent==null) {
            if (!name.equals(""))
                throw new IllegalArgumentException("Root name '"+name+
                                                   "' must be \"\"");
            this.absolutePath = "/";
            root = this;
        } else {
            if (name.indexOf('/") != -1)
                throw new IllegalArgumentException("Name '" + name +
                                                 "' contains '/'");
            if (name.equals(""))
              throw new IllegalArgumentException("Illegal name: empty string");

            root = parent.root;
            absolutePath = (parent==root ? "/" + name
                            		 : parent.absolutePath() + "/" + name);
        }
        this.name = name;
        this.parent = parent;
    
Methods Summary
public java.lang.StringabsolutePath()
Implements the absolutePath method as per the specification in {@link Preferences#absolutePath()}.

This implementation merely returns the absolute path name that was computed at the time that this node was constructed (based on the name that was passed to this node's constructor, and the names that were passed to this node's ancestors' constructors).

return
this preference node's absolute path name.

        return absolutePath;
    
public voidaddNodeChangeListener(java.util.prefs.NodeChangeListener ncl)

        if (ncl==null)
            throw new NullPointerException("Change listener is null.");
        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node has been removed.");

            // Copy-on-write
            if (nodeListeners == null) {
                nodeListeners = new NodeChangeListener[1];
                nodeListeners[0] = ncl;
            } else {
                NodeChangeListener[] old = nodeListeners;
                nodeListeners = new NodeChangeListener[old.length + 1];
                System.arraycopy(old, 0, nodeListeners, 0, old.length);
                nodeListeners[old.length] = ncl;
            }
        }
        startEventDispatchThreadIfNecessary();
    
public voidaddPreferenceChangeListener(java.util.prefs.PreferenceChangeListener pcl)

        if (pcl==null)
            throw new NullPointerException("Change listener is null.");
        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node has been removed.");

            // Copy-on-write
            PreferenceChangeListener[] old = prefListeners;
            prefListeners = new PreferenceChangeListener[old.length + 1];
            System.arraycopy(old, 0, prefListeners, 0, old.length);
            prefListeners[old.length] = pcl;
        }
        startEventDispatchThreadIfNecessary();
    
protected final java.util.prefs.AbstractPreferences[]cachedChildren()
Returns all known unremoved children of this node.

return
all known unremoved children of this node.


                         
        
        return (AbstractPreferences[]) kidCache.values().
            toArray(EMPTY_ABSTRACT_PREFS_ARRAY);
    
protected abstract java.util.prefs.AbstractPreferenceschildSpi(java.lang.String name)
Returns the named child of this preference node, creating it if it does not already exist. It is guaranteed that name is non-null, non-empty, does not contain the slash character ('/'), and is no longer than {@link #MAX_NAME_LENGTH} characters. Also, it is guaranteed that this node has not been removed. (The implementor needn't check for any of these things.)

Finally, it is guaranteed that the named node has not been returned by a previous invocation of this method or {@link #getChild(String)} after the last time that it was removed. In other words, a cached value will always be used in preference to invoking this method. Subclasses need not maintain their own cache of previously returned children.

The implementer must ensure that the returned node has not been removed. If a like-named child of this node was previously removed, the implementer must return a newly constructed AbstractPreferences node; once removed, an AbstractPreferences node cannot be "resuscitated."

If this method causes a node to be created, this node is not guaranteed to be persistent until the flush method is invoked on this node or one of its ancestors (or descendants).

This method is invoked with the lock on this node held.

param
name The name of the child node to return, relative to this preference node.
return
The named child node.

public java.lang.String[]childrenNames()
Implements the children method as per the specification in {@link Preferences#childrenNames()}.

This implementation obtains this preference node's lock, checks that the node has not been removed, constructs a TreeSet initialized to the names of children already cached (the children in this node's "child-cache"), invokes {@link #childrenNamesSpi()}, and adds all of the returned child-names into the set. The elements of the tree set are dumped into a String array using the toArray method, and this array is returned.

return
the names of the children of this preference node.
throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.
see
#cachedChildren()

        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node has been removed.");

            Set s = new TreeSet(kidCache.keySet());
            String[] kids = childrenNamesSpi();
            for(int i=0; i<kids.length; i++)
                s.add(kids[i]);
            return (String[]) s.toArray(EMPTY_STRING_ARRAY);
        }
    
protected abstract java.lang.String[]childrenNamesSpi()
Returns the names of the children of this preference node. (The returned array will be of size zero if this node has no children.) This method need not return the names of any nodes already cached, but may do so without harm.

This method is invoked with the lock on this node held.

If this node throws a BackingStoreException, the exception will propagate out beyond the enclosing {@link #childrenNames()} invocation.

return
an array containing the names of the children of this preference node.
throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.

public voidclear()
Implements the clear method as per the specification in {@link Preferences#clear()}.

This implementation obtains this preference node's lock, invokes {@link #keys()} to obtain an array of keys, and iterates over the array invoking {@link #remove(String)} on each key.

throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        synchronized(lock) {
            String[] keys = keys();
            for (int i=0; i<keys.length; i++)
                remove(keys[i]);
        }
    
private voidenqueueNodeAddedEvent(java.util.prefs.Preferences child)
Enqueue a "node added" event for delivery to registered node change listeners unless there are no registered listeners. Invoked with this.lock held.

        if (nodeListeners.length != 0) {
            synchronized(eventQueue) {
                eventQueue.add(new NodeAddedEvent(this, child));
                eventQueue.notify();
            }
        }
    
private voidenqueueNodeRemovedEvent(java.util.prefs.Preferences child)
Enqueue a "node removed" event for delivery to registered node change listeners unless there are no registered listeners. Invoked with this.lock held.

        if (nodeListeners.length != 0) {
            synchronized(eventQueue) {
                eventQueue.add(new NodeRemovedEvent(this, child));
                eventQueue.notify();
            }
        }
    
private voidenqueuePreferenceChangeEvent(java.lang.String key, java.lang.String newValue)
Enqueue a preference change event for delivery to registered preference change listeners unless there are no registered listeners. Invoked with this.lock held.

        if (prefListeners.length != 0) {
            synchronized(eventQueue) {
                eventQueue.add(new PreferenceChangeEvent(this, key, newValue));
                eventQueue.notify();
            }
        }
    
public voidexportNode(java.io.OutputStream os)
Implements the exportNode method as per the specification in {@link Preferences#exportNode(OutputStream)}.

param
os the output stream on which to emit the XML document.
throws
IOException if writing to the specified output stream results in an IOException.
throws
BackingStoreException if preference data cannot be read from backing store.

   
        XmlSupport.export(os, this, false);
    
public voidexportSubtree(java.io.OutputStream os)
Implements the exportSubtree method as per the specification in {@link Preferences#exportSubtree(OutputStream)}.

param
os the output stream on which to emit the XML document.
throws
IOException if writing to the specified output stream results in an IOException.
throws
BackingStoreException if preference data cannot be read from backing store.

       
        XmlSupport.export(os, this, true);
    
public voidflush()
Implements the flush method as per the specification in {@link Preferences#flush()}.

This implementation calls a recursive helper method that locks this node, invokes flushSpi() on it, unlocks this node, and recursively invokes this method on each "cached child." A cached child is a child of this node that has been created in this VM and not subsequently removed. In effect, this method does a depth first traversal of the "cached subtree" rooted at this node, calling flushSpi() on each node in the subTree while only that node is locked. Note that flushSpi() is invoked top-down.

If this method is invoked on a node that has been removed with the {@link #removeNode()} method, flushSpi() is invoked on this node, but not on others.

throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.
see
#flush()

        flush2();
    
private voidflush2()

        AbstractPreferences[] cachedKids;
	
	synchronized(lock) {
	    flushSpi();
	    if(removed) 
		return;
            cachedKids = cachedChildren();
        }
	
        for (int i = 0; i < cachedKids.length; i++)
            cachedKids[i].flush2();
    
protected abstract voidflushSpi()
This method is invoked with this node locked. The contract of this method is to force any cached changes in the contents of this preference node to the backing store, guaranteeing their persistence. (It is perfectly possible that this node does not exist on the backing store, either because it has been deleted by another VM, or because it has not yet been created.) Note that this method should not flush the preferences in any subnodes of this node. If the backing store naturally flushes an entire subtree at once, the implementer is encouraged to override flush(), rather than merely overriding this method.

If this node throws a BackingStoreException, the exception will propagate out beyond the enclosing {@link #flush()} invocation.

throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.

public java.lang.Stringget(java.lang.String key, java.lang.String def)
Implements the get method as per the specification in {@link Preferences#get(String,String)}.

This implementation first checks to see if key is null throwing a NullPointerException if this is the case. Then it obtains this preference node's lock, checks that the node has not been removed, invokes {@link #getSpi(String)}, and returns the result, unless the getSpi invocation returns null or throws an exception, in which case this invocation returns def.

param
key key whose associated value is to be returned.
param
def the value to be returned in the event that this preference node has no value associated with key.
return
the value associated with key, or def if no value is associated with key.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.
throws
NullPointerException if key is null. (A null default is permitted.)

        if (key==null)
            throw new NullPointerException("Null key");
        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node has been removed.");

            String result = null;
            try {
                result = getSpi(key);
            } catch (Exception e) {
                // Ignoring exception causes default to be returned
            }
            return (result==null ? def : result);
        }
    
public booleangetBoolean(java.lang.String key, boolean def)
Implements the getBoolean method as per the specification in {@link Preferences#getBoolean(String,boolean)}.

This implementation invokes {@link #get(String,String) get(key, null)}. If the return value is non-null, it is compared with "true" using {@link String#equalsIgnoreCase(String)}. If the comparison returns true, this invocation returns true. Otherwise, the original return value is compared with "false", again using {@link String#equalsIgnoreCase(String)}. If the comparison returns true, this invocation returns false. Otherwise, this invocation returns def.

param
key key whose associated value is to be returned as a boolean.
param
def the value to be returned in the event that this preference node has no value associated with key or the associated value cannot be interpreted as a boolean.
return
the boolean value represented by the string associated with key in this preference node, or def if the associated value does not exist or cannot be interpreted as a boolean.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.
throws
NullPointerException if key is null.

        boolean result = def;
        String value = get(key, null);
        if (value != null) {
            if (value.equalsIgnoreCase("true"))
                result = true;
            else if (value.equalsIgnoreCase("false"))
                result = false;
        }

        return result;
    
public byte[]getByteArray(java.lang.String key, byte[] def)
Implements the getByteArray method as per the specification in {@link Preferences#getByteArray(String,byte[])}.

param
key key whose associated value is to be returned as a byte array.
param
def the value to be returned in the event that this preference node has no value associated with key or the associated value cannot be interpreted as a byte array.
return
the byte array value represented by the string associated with key in this preference node, or def if the associated value does not exist or cannot be interpreted as a byte array.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.
throws
NullPointerException if key is null. (A null value for def is permitted.)

        byte[] result = def;
        String value = get(key, null);
        try {
            if (value != null)
                result = Base64.base64ToByteArray(value);
        }
        catch (RuntimeException e) {
            // Ignoring exception causes specified default to be returned
        }

        return result;
    
protected java.util.prefs.AbstractPreferencesgetChild(java.lang.String nodeName)
Returns the named child if it exists, or null if it does not. It is guaranteed that nodeName is non-null, non-empty, does not contain the slash character ('/'), and is no longer than {@link #MAX_NAME_LENGTH} characters. Also, it is guaranteed that this node has not been removed. (The implementor needn't check for any of these things if he chooses to override this method.)

Finally, it is guaranteed that the named node has not been returned by a previous invocation of this method or {@link #childSpi} after the last time that it was removed. In other words, a cached value will always be used in preference to invoking this method. (The implementor needn't maintain his own cache of previously returned children if he chooses to override this method.)

This implementation obtains this preference node's lock, invokes {@link #childrenNames()} to get an array of the names of this node's children, and iterates over the array comparing the name of each child with the specified node name. If a child node has the correct name, the {@link #childSpi(String)} method is invoked and the resulting node is returned. If the iteration completes without finding the specified name, null is returned.

param
nodeName name of the child to be searched for.
return
the named child if it exists, or null if it does not.
throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.

        synchronized(lock) {
            // assert kidCache.get(nodeName)==null;
            String[] kidNames = childrenNames();
            for (int i=0; i<kidNames.length; i++)
                if (kidNames[i].equals(nodeName))
                    return childSpi(kidNames[i]);
        }
        return null;
    
public doublegetDouble(java.lang.String key, double def)
Implements the getDouble method as per the specification in {@link Preferences#getDouble(String,double)}.

This implementation invokes {@link #get(String,String) get(key, null)}. If the return value is non-null, the implementation attempts to translate it to an double with {@link Double#parseDouble(String)}. If the attempt succeeds, the return value is returned by this method. Otherwise, def is returned.

param
key key whose associated value is to be returned as a double.
param
def the value to be returned in the event that this preference node has no value associated with key or the associated value cannot be interpreted as a double.
return
the double value represented by the string associated with key in this preference node, or def if the associated value does not exist or cannot be interpreted as a double.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.
throws
NullPointerException if key is null.

        double result = def;
        try {
            String value = get(key, null);
            if (value != null)
                result = Double.parseDouble(value);
        } catch (NumberFormatException e) {
            // Ignoring exception causes specified default to be returned
        }

        return result;
    
public floatgetFloat(java.lang.String key, float def)
Implements the getFloat method as per the specification in {@link Preferences#getFloat(String,float)}.

This implementation invokes {@link #get(String,String) get(key, null)}. If the return value is non-null, the implementation attempts to translate it to an float with {@link Float#parseFloat(String)}. If the attempt succeeds, the return value is returned by this method. Otherwise, def is returned.

param
key key whose associated value is to be returned as a float.
param
def the value to be returned in the event that this preference node has no value associated with key or the associated value cannot be interpreted as a float.
return
the float value represented by the string associated with key in this preference node, or def if the associated value does not exist or cannot be interpreted as a float.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.
throws
NullPointerException if key is null.

        float result = def;
        try {
            String value = get(key, null);
            if (value != null)
                result = Float.parseFloat(value);
        } catch (NumberFormatException e) {
            // Ignoring exception causes specified default to be returned
        }

        return result;
    
public intgetInt(java.lang.String key, int def)
Implements the getInt method as per the specification in {@link Preferences#getInt(String,int)}.

This implementation invokes {@link #get(String,String) get(key, null)}. If the return value is non-null, the implementation attempts to translate it to an int with {@link Integer#parseInt(String)}. If the attempt succeeds, the return value is returned by this method. Otherwise, def is returned.

param
key key whose associated value is to be returned as an int.
param
def the value to be returned in the event that this preference node has no value associated with key or the associated value cannot be interpreted as an int.
return
the int value represented by the string associated with key in this preference node, or def if the associated value does not exist or cannot be interpreted as an int.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.
throws
NullPointerException if key is null.

        int result = def;
        try {
            String value = get(key, null);
            if (value != null)
                result = Integer.parseInt(value);
        } catch (NumberFormatException e) {
            // Ignoring exception causes specified default to be returned
        }

        return result;
    
public longgetLong(java.lang.String key, long def)
Implements the getLong method as per the specification in {@link Preferences#getLong(String,long)}.

This implementation invokes {@link #get(String,String) get(key, null)}. If the return value is non-null, the implementation attempts to translate it to a long with {@link Long#parseLong(String)}. If the attempt succeeds, the return value is returned by this method. Otherwise, def is returned.

param
key key whose associated value is to be returned as a long.
param
def the value to be returned in the event that this preference node has no value associated with key or the associated value cannot be interpreted as a long.
return
the long value represented by the string associated with key in this preference node, or def if the associated value does not exist or cannot be interpreted as a long.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.
throws
NullPointerException if key is null.

        long result = def;
        try {
            String value = get(key, null);
            if (value != null)
                result = Long.parseLong(value);
        } catch (NumberFormatException e) {
            // Ignoring exception causes specified default to be returned
        }

        return result;
    
protected abstract java.lang.StringgetSpi(java.lang.String key)
Return the value associated with the specified key at this preference node, or null if there is no association for this key, or the association cannot be determined at this time. It is guaranteed that key is non-null. Also, it is guaranteed that this node has not been removed. (The implementor needn't check for either of these things.)

Generally speaking, this method should not throw an exception under any circumstances. If, however, if it does throw an exception, the exception will be intercepted and treated as a null return value.

This method is invoked with the lock on this node held.

return
the value associated with the specified key at this preference node, or null if there is no association for this key, or the association cannot be determined at this time.

protected booleanisRemoved()
Returns true iff this node (or an ancestor) has been removed with the {@link #removeNode()} method. This method locks this node prior to returning the contents of the private field used to track this state.

return
true iff this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        synchronized(lock) {
            return removed;
        }
    
public booleanisUserNode()
Implements the isUserNode method as per the specification in {@link Preferences#isUserNode()}.

This implementation compares this node's root node (which is stored in a private field) with the value returned by {@link Preferences#userRoot()}. If the two object references are identical, this method returns true.

return
true if this preference node is in the user preference tree, false if it's in the system preference tree.

        Boolean result = (Boolean)
          AccessController.doPrivileged( new PrivilegedAction() {            
            public Object run() {
                return new Boolean(root == Preferences.userRoot());
            }
        });
        return result.booleanValue();
    
public java.lang.String[]keys()
Implements the keys method as per the specification in {@link Preferences#keys()}.

This implementation obtains this preference node's lock, checks that the node has not been removed and invokes {@link #keysSpi()}.

return
an array of the keys that have an associated value in this preference node.
throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node has been removed.");

            return keysSpi();
        }
    
protected abstract java.lang.String[]keysSpi()
Returns all of the keys that have an associated value in this preference node. (The returned array will be of size zero if this node has no preferences.) It is guaranteed that this node has not been removed.

This method is invoked with the lock on this node held.

If this node throws a BackingStoreException, the exception will propagate out beyond the enclosing {@link #keys()} invocation.

return
an array of the keys that have an associated value in this preference node.
throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.

public java.lang.Stringname()
Implements the name method as per the specification in {@link Preferences#name()}.

This implementation merely returns the name that was passed to this node's constructor.

return
this preference node's name, relative to its parent.

        return name;
    
public java.util.prefs.Preferencesnode(java.lang.String path)
Implements the node method as per the specification in {@link Preferences#node(String)}.

This implementation obtains this preference node's lock and checks that the node has not been removed. If path is "", this node is returned; if path is "/", this node's root is returned. If the first character in path is not '/', the implementation breaks path into tokens and recursively traverses the path from this node to the named node, "consuming" a name and a slash from path at each step of the traversal. At each step, the current node is locked and the node's child-cache is checked for the named node. If it is not found, the name is checked to make sure its length does not exceed MAX_NAME_LENGTH. Then the {@link #childSpi(String)} method is invoked, and the result stored in this node's child-cache. If the newly created Preferences object's {@link #newNode} field is true and there are any node change listeners, a notification event is enqueued for processing by the event dispatch thread.

When there are no more tokens, the last value found in the child-cache or returned by childSpi is returned by this method. If during the traversal, two "/" tokens occur consecutively, or the final token is "/" (rather than a name), an appropriate IllegalArgumentException is thrown.

If the first character of path is '/' (indicating an absolute path name) this preference node's lock is dropped prior to breaking path into tokens, and this method recursively traverses the path starting from the root (rather than starting from this node). The traversal is otherwise identical to the one described for relative path names. Dropping the lock on this node prior to commencing the traversal at the root node is essential to avoid the possibility of deadlock, as per the {@link #lock locking invariant}.

param
path the path name of the preference node to return.
return
the specified preference node.
throws
IllegalArgumentException if the path name is invalid (i.e., it contains multiple consecutive slash characters, or ends with a slash character and is more than one character long).
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node has been removed.");
            if (path.equals(""))
                return this;
            if (path.equals("/"))
                return root;
            if (path.charAt(0) != '/")
                return node(new StringTokenizer(path, "/", true));
        }

        // Absolute path.  Note that we've dropped our lock to avoid deadlock
        return root.node(new StringTokenizer(path.substring(1), "/", true));
    
private java.util.prefs.Preferencesnode(java.util.StringTokenizer path)
tokenizer contains {'/' }*

        String token = path.nextToken();
        if (token.equals("/"))  // Check for consecutive slashes
            throw new IllegalArgumentException("Consecutive slashes in path");
        synchronized(lock) {
            AbstractPreferences child=(AbstractPreferences)kidCache.get(token);
            if (child == null) {
                if (token.length() > MAX_NAME_LENGTH)
                    throw new IllegalArgumentException(
                        "Node name " + token + " too long");
                child = childSpi(token);
                if (child.newNode)
                    enqueueNodeAddedEvent(child);
                kidCache.put(token, child);
            }
            if (!path.hasMoreTokens())
                return child;
            path.nextToken();  // Consume slash
            if (!path.hasMoreTokens())
                throw new IllegalArgumentException("Path ends with slash");
            return child.node(path);
        }
    
public booleannodeExists(java.lang.String path)
Implements the nodeExists method as per the specification in {@link Preferences#nodeExists(String)}.

This implementation is very similar to {@link #node(String)}, except that {@link #getChild(String)} is used instead of {@link #childSpi(String)}.

param
path the path name of the node whose existence is to be checked.
return
true if the specified node exists.
throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.
throws
IllegalArgumentException if the path name is invalid (i.e., it contains multiple consecutive slash characters, or ends with a slash character and is more than one character long).
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method and pathname is not the empty string ("").

        synchronized(lock) {
            if (path.equals(""))
                return !removed;
            if (removed)
                throw new IllegalStateException("Node has been removed.");
            if (path.equals("/"))
                return true;
            if (path.charAt(0) != '/")
                return nodeExists(new StringTokenizer(path, "/", true));
        }

        // Absolute path.  Note that we've dropped our lock to avoid deadlock
        return root.nodeExists(new StringTokenizer(path.substring(1), "/",
                                                   true));
    
private booleannodeExists(java.util.StringTokenizer path)
tokenizer contains {'/' }*

        String token = path.nextToken();
        if (token.equals("/"))  // Check for consecutive slashes
            throw new IllegalArgumentException("Consecutive slashes in path");
        synchronized(lock) {
            AbstractPreferences child=(AbstractPreferences)kidCache.get(token);
            if (child == null)
                child = getChild(token);
            if (child==null)
                return false;
            if (!path.hasMoreTokens())
                return true;
            path.nextToken();  // Consume slash
            if (!path.hasMoreTokens())
                throw new IllegalArgumentException("Path ends with slash");
            return child.nodeExists(path);
        }
    
java.util.prefs.NodeChangeListener[]nodeListeners()

        synchronized(lock) {
            return nodeListeners;
        }
    
public java.util.prefs.Preferencesparent()
Implements the parent method as per the specification in {@link Preferences#parent()}.

This implementation obtains this preference node's lock, checks that the node has not been removed and returns the parent value that was passed to this node's constructor.

return
the parent of this preference node.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.


                                                                              
       
        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node has been removed.");

            return parent;
        }
    
java.util.prefs.PreferenceChangeListener[]prefListeners()
Return this node's preference/node change listeners. Even though we're using a copy-on-write lists, we use synchronized accessors to ensure information transmission from the writing thread to the reading thread.

        synchronized(lock) {
            return prefListeners;
        }
    
public voidput(java.lang.String key, java.lang.String value)
Implements the put method as per the specification in {@link Preferences#put(String,String)}.

This implementation checks that the key and value are legal, obtains this preference node's lock, checks that the node has not been removed, invokes {@link #putSpi(String,String)}, and if there are any preference change listeners, enqueues a notification event for processing by the event dispatch thread.

param
key key with which the specified value is to be associated.
param
value value to be associated with the specified key.
throws
NullPointerException if key or value is null.
throws
IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH or if value.length exceeds MAX_VALUE_LENGTH.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        if (key==null || value==null)
            throw new NullPointerException();
        if (key.length() > MAX_KEY_LENGTH)
            throw new IllegalArgumentException("Key too long: "+key);
        if (value.length() > MAX_VALUE_LENGTH)
            throw new IllegalArgumentException("Value too long: "+value);

        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node has been removed.");

            putSpi(key, value);
            enqueuePreferenceChangeEvent(key, value);
        }
    
public voidputBoolean(java.lang.String key, boolean value)
Implements the putBoolean method as per the specification in {@link Preferences#putBoolean(String,boolean)}.

This implementation translates value to a string with {@link String#valueOf(boolean)} and invokes {@link #put(String,String)} on the result.

param
key key with which the string form of value is to be associated.
param
value value whose string form is to be associated with key.
throws
NullPointerException if key is null.
throws
IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        put(key, String.valueOf(value));
    
public voidputByteArray(java.lang.String key, byte[] value)
Implements the putByteArray method as per the specification in {@link Preferences#putByteArray(String,byte[])}.

param
key key with which the string form of value is to be associated.
param
value value whose string form is to be associated with key.
throws
NullPointerException if key or value is null.
throws
IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH or if value.length exceeds MAX_VALUE_LENGTH*3/4.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        put(key, Base64.byteArrayToBase64(value));
    
public voidputDouble(java.lang.String key, double value)
Implements the putDouble method as per the specification in {@link Preferences#putDouble(String,double)}.

This implementation translates value to a string with {@link Double#toString(double)} and invokes {@link #put(String,String)} on the result.

param
key key with which the string form of value is to be associated.
param
value value whose string form is to be associated with key.
throws
NullPointerException if key is null.
throws
IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        put(key, Double.toString(value));
    
public voidputFloat(java.lang.String key, float value)
Implements the putFloat method as per the specification in {@link Preferences#putFloat(String,float)}.

This implementation translates value to a string with {@link Float#toString(float)} and invokes {@link #put(String,String)} on the result.

param
key key with which the string form of value is to be associated.
param
value value whose string form is to be associated with key.
throws
NullPointerException if key is null.
throws
IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        put(key, Float.toString(value));
    
public voidputInt(java.lang.String key, int value)
Implements the putInt method as per the specification in {@link Preferences#putInt(String,int)}.

This implementation translates value to a string with {@link Integer#toString(int)} and invokes {@link #put(String,String)} on the result.

param
key key with which the string form of value is to be associated.
param
value value whose string form is to be associated with key.
throws
NullPointerException if key is null.
throws
IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        put(key, Integer.toString(value));
    
public voidputLong(java.lang.String key, long value)
Implements the putLong method as per the specification in {@link Preferences#putLong(String,long)}.

This implementation translates value to a string with {@link Long#toString(long)} and invokes {@link #put(String,String)} on the result.

param
key key with which the string form of value is to be associated.
param
value value whose string form is to be associated with key.
throws
NullPointerException if key is null.
throws
IllegalArgumentException if key.length() exceeds MAX_KEY_LENGTH.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        put(key, Long.toString(value));
    
protected abstract voidputSpi(java.lang.String key, java.lang.String value)
Put the given key-value association into this preference node. It is guaranteed that key and value are non-null and of legal length. Also, it is guaranteed that this node has not been removed. (The implementor needn't check for any of these things.)

This method is invoked with the lock on this node held.

public voidremove(java.lang.String key)
Implements the remove(String) method as per the specification in {@link Preferences#remove(String)}.

This implementation obtains this preference node's lock, checks that the node has not been removed, invokes {@link #removeSpi(String)} and if there are any preference change listeners, enqueues a notification event for processing by the event dispatch thread.

param
key key whose mapping is to be removed from the preference node.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.

        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node has been removed.");

            removeSpi(key);
            enqueuePreferenceChangeEvent(key, null);
        }
    
public voidremoveNode()
Implements the removeNode() method as per the specification in {@link Preferences#removeNode()}.

This implementation checks to see that this node is the root; if so, it throws an appropriate exception. Then, it locks this node's parent, and calls a recursive helper method that traverses the subtree rooted at this node. The recursive method locks the node on which it was called, checks that it has not already been removed, and then ensures that all of its children are cached: The {@link #childrenNamesSpi()} method is invoked and each returned child name is checked for containment in the child-cache. If a child is not already cached, the {@link #childSpi(String)} method is invoked to create a Preferences instance for it, and this instance is put into the child-cache. Then the helper method calls itself recursively on each node contained in its child-cache. Next, it invokes {@link #removeNodeSpi()}, marks itself as removed, and removes itself from its parent's child-cache. Finally, if there are any node change listeners, it enqueues a notification event for processing by the event dispatch thread.

Note that the helper method is always invoked with all ancestors up to the "closest non-removed ancestor" locked.

throws
IllegalStateException if this node (or an ancestor) has already been removed with the {@link #removeNode()} method.
throws
UnsupportedOperationException if this method is invoked on the root node.
throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.

        if (this==root)
            throw new UnsupportedOperationException("Can't remove the root!");
        synchronized(parent.lock) {
            removeNode2();
            parent.kidCache.remove(name);
        }
    
private voidremoveNode2()

        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node already removed.");

            // Ensure that all children are cached
            String[] kidNames = childrenNamesSpi();
            for (int i=0; i<kidNames.length; i++)
                if (!kidCache.containsKey(kidNames[i]))
                    kidCache.put(kidNames[i], childSpi(kidNames[i]));

            // Recursively remove all cached children
            for (Iterator i = kidCache.values().iterator(); i.hasNext();) {
		try {
		    ((AbstractPreferences)i.next()).removeNode2();
                    i.remove();
		} catch (BackingStoreException x) { }
	    }

	    // Now we have no descendants - it's time to die!
	    removeNodeSpi();
	    removed = true;
	    parent.enqueueNodeRemovedEvent(this);
	}
    
public voidremoveNodeChangeListener(java.util.prefs.NodeChangeListener ncl)

        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node has been removed.");
            if ((nodeListeners == null) || (nodeListeners.length == 0))
                throw new IllegalArgumentException("Listener not registered.");

            // Copy-on-write
	    int i = 0;
	    while (i < nodeListeners.length && nodeListeners[i] != ncl)
		i++;
	    if (i == nodeListeners.length)
		throw new IllegalArgumentException("Listener not registered.");
	    NodeChangeListener[] newNl =
		new NodeChangeListener[nodeListeners.length - 1];
            if (i != 0) 
		System.arraycopy(nodeListeners, 0, newNl, 0, i);
            if (i != newNl.length) 
		System.arraycopy(nodeListeners, i + 1, 
				 newNl, i, newNl.length - i);
	    nodeListeners = newNl;
        }
    
protected abstract voidremoveNodeSpi()
Removes this preference node, invalidating it and any preferences that it contains. The named child will have no descendants at the time this invocation is made (i.e., the {@link Preferences#removeNode()} method invokes this method repeatedly in a bottom-up fashion, removing each of a node's descendants before removing the node itself).

This method is invoked with the lock held on this node and its parent (and all ancestors that are being removed as a result of a single invocation to {@link Preferences#removeNode()}).

The removal of a node needn't become persistent until the flush method is invoked on this node (or an ancestor).

If this node throws a BackingStoreException, the exception will propagate out beyond the enclosing {@link #removeNode()} invocation.

throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.

public voidremovePreferenceChangeListener(java.util.prefs.PreferenceChangeListener pcl)

        synchronized(lock) {
            if (removed)
                throw new IllegalStateException("Node has been removed.");
            if ((prefListeners == null) || (prefListeners.length == 0))
                throw new IllegalArgumentException("Listener not registered.");

            // Copy-on-write
            PreferenceChangeListener[] newPl =
                new PreferenceChangeListener[prefListeners.length - 1];
            int i = 0;
            while (i < newPl.length && prefListeners[i] != pcl)
                newPl[i] = prefListeners[i++];

            if (i == newPl.length &&  prefListeners[i] != pcl)
                throw new IllegalArgumentException("Listener not registered.");
            while (i < newPl.length)
                newPl[i] = prefListeners[++i];
            prefListeners = newPl;
        }
    
protected abstract voidremoveSpi(java.lang.String key)
Remove the association (if any) for the specified key at this preference node. It is guaranteed that key is non-null. Also, it is guaranteed that this node has not been removed. (The implementor needn't check for either of these things.)

This method is invoked with the lock on this node held.

private static synchronized voidstartEventDispatchThreadIfNecessary()
This method starts the event dispatch thread the first time it is called. The event dispatch thread will be started only if someone registers a listener.


                                    
         
        if (eventDispatchThread == null) {
            // XXX Log "Starting event dispatch thread"
            eventDispatchThread = new EventDispatchThread();
            eventDispatchThread.setDaemon(true);
            eventDispatchThread.start();
        }
    
public voidsync()
Implements the sync method as per the specification in {@link Preferences#sync()}.

This implementation calls a recursive helper method that locks this node, invokes syncSpi() on it, unlocks this node, and recursively invokes this method on each "cached child." A cached child is a child of this node that has been created in this VM and not subsequently removed. In effect, this method does a depth first traversal of the "cached subtree" rooted at this node, calling syncSpi() on each node in the subTree while only that node is locked. Note that syncSpi() is invoked top-down.

throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.
throws
IllegalStateException if this node (or an ancestor) has been removed with the {@link #removeNode()} method.
see
#flush()

       
        sync2();
    
private voidsync2()

        AbstractPreferences[] cachedKids;

        synchronized(lock) {
	    if (removed) 
		throw new IllegalStateException("Node has been removed");            
	    syncSpi();
	    cachedKids = cachedChildren();
        }

        for (int i=0; i<cachedKids.length; i++)
            cachedKids[i].sync2();
    
protected abstract voidsyncSpi()
This method is invoked with this node locked. The contract of this method is to synchronize any cached preferences stored at this node with any stored in the backing store. (It is perfectly possible that this node does not exist on the backing store, either because it has been deleted by another VM, or because it has not yet been created.) Note that this method should not synchronize the preferences in any subnodes of this node. If the backing store naturally syncs an entire subtree at once, the implementer is encouraged to override sync(), rather than merely overriding this method.

If this node throws a BackingStoreException, the exception will propagate out beyond the enclosing {@link #sync()} invocation.

throws
BackingStoreException if this operation cannot be completed due to a failure in the backing store, or inability to communicate with it.

public java.lang.StringtoString()
Returns the absolute path name of this preferences node.

        return (this.isUserNode() ? "User" : "System") +
               " Preference Node: " + this.absolutePath();