/* * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.io.InputStream;import java.io.IOException;import java.io.OutputStream;import java.security.AccessController;import java.security.Permission;import java.security.PrivilegedAction;import java.util.Iterator;import java.util.ServiceLoader;import java.util.ServiceConfigurationError; // These imports needed only as a workaround for a JavaDoc bugimport java.lang.RuntimePermission;import java.lang.Integer;import java.lang.Long;import java.lang.Float;import java.lang.Double; /** * A node in a hierarchical collection of preference data. This class * allows applications to store and retrieve user and system * preference and configuration data. This data is stored * persistently in an implementation-dependent backing store. Typical * implementations include flat files, OS-specific registries, * directory servers and SQL databases. The user of this class needn't * be concerned with details of the backing store. * * <p>There are two separate trees of preference nodes, one for user * preferences and one for system preferences. Each user has a separate user * preference tree, and all users in a given system share the same system * preference tree. The precise description of "user" and "system" will vary * from implementation to implementation. Typical information stored in the * user preference tree might include font choice, color choice, or preferred * window location and size for a particular application. Typical information * stored in the system preference tree might include installation * configuration data for an application. * * <p>Nodes in a preference tree are named in a similar fashion to * directories in a hierarchical file system. Every node in a preference * tree has a <i>node name</i> (which is not necessarily unique), * a unique <i>absolute path name</i>, and a path name <i>relative</i> to each * ancestor including itself. * * <p>The root node has a node name of the empty string (""). Every other * node has an arbitrary node name, specified at the time it is created. The * only restrictions on this name are that it cannot be the empty string, and * it cannot contain the slash character ('/'). * * <p>The root node has an absolute path name of <tt>"/"</tt>. Children of * the root node have absolute path names of <tt>"/" + </tt><i><node * name></i>. All other nodes have absolute path names of <i><parent's * absolute path name></i><tt> + "/" + </tt><i><node name></i>. * Note that all absolute path names begin with the slash character. * * <p>A node <i>n</i>'s path name relative to its ancestor <i>a</i> * is simply the string that must be appended to <i>a</i>'s absolute path name * in order to form <i>n</i>'s absolute path name, with the initial slash * character (if present) removed. Note that: * <ul> * <li>No relative path names begin with the slash character. * <li>Every node's path name relative to itself is the empty string. * <li>Every node's path name relative to its parent is its node name (except * for the root node, which does not have a parent). * <li>Every node's path name relative to the root is its absolute path name * with the initial slash character removed. * </ul> * * <p>Note finally that: * <ul> * <li>No path name contains multiple consecutive slash characters. * <li>No path name with the exception of the root's absolute path name * ends in the slash character. * <li>Any string that conforms to these two rules is a valid path name. * </ul> * * <p>All of the methods that modify preferences data are permitted to operate * asynchronously; they may return immediately, and changes will eventually * propagate to the persistent backing store with an implementation-dependent * delay. The <tt>flush</tt> method may be used to synchronously force * updates to the backing store. Normal termination of the Java Virtual * Machine will <i>not</i> result in the loss of pending updates -- an explicit * <tt>flush</tt> invocation is <i>not</i> required upon termination to ensure * that pending updates are made persistent. * * <p>All of the methods that read preferences from a <tt>Preferences</tt> * object require the invoker to provide a default value. The default value is * returned if no value has been previously set <i>or if the backing store is * unavailable</i>. The intent is to allow applications to operate, albeit * with slightly degraded functionality, even if the backing store becomes * unavailable. Several methods, like <tt>flush</tt>, have semantics that * prevent them from operating if the backing store is unavailable. Ordinary * applications should have no need to invoke any of these methods, which can * be identified by the fact that they are declared to throw {@link * BackingStoreException}. * * <p>The methods in this class may be invoked concurrently by multiple threads * in a single JVM without the need for external synchronization, and the * results will be equivalent to some serial execution. If this class is used * concurrently <i>by multiple JVMs</i> that store their preference data in * the same backing store, the data store will not be corrupted, but no * other guarantees are made concerning the consistency of the preference * data. * * <p>This class contains an export/import facility, allowing preferences * to be "exported" to an XML document, and XML documents representing * preferences to be "imported" back into the system. This facility * may be used to back up all or part of a preference tree, and * subsequently restore from the backup. * * <p>The XML document has the following DOCTYPE declaration: * <pre> * <!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd"> * </pre> * Note that the system URI (http://java.sun.com/dtd/preferences.dtd) is * <i>not</i> accessed when exporting or importing preferences; it merely * serves as a string to uniquely identify the DTD, which is: * <pre> * <?xml version="1.0" encoding="UTF-8"?> * * <!-- DTD for a Preferences tree. --> * * <!-- The preferences element is at the root of an XML document * representing a Preferences tree. --> * <!ELEMENT preferences (root)> * * <!-- The preferences element contains an optional version attribute, * which specifies version of DTD. --> * <!ATTLIST preferences EXTERNAL_XML_VERSION CDATA "0.0" > * * <!-- The root element has a map representing the root's preferences * (if any), and one node for each child of the root (if any). --> * <!ELEMENT root (map, node*) > * * <!-- Additionally, the root contains a type attribute, which * specifies whether it's the system or user root. --> * <!ATTLIST root * type (system|user) #REQUIRED > * * <!-- Each node has a map representing its preferences (if any), * and one node for each child (if any). --> * <!ELEMENT node (map, node*) > * * <!-- Additionally, each node has a name attribute --> * <!ATTLIST node * name CDATA #REQUIRED > * * <!-- A map represents the preferences stored at a node (if any). --> * <!ELEMENT map (entry*) > * * <!-- An entry represents a single preference, which is simply * a key-value pair. --> * <!ELEMENT entry EMPTY > * <!ATTLIST entry * key CDATA #REQUIRED * value CDATA #REQUIRED > * </pre> * * Every <tt>Preferences</tt> implementation must have an associated {@link * PreferencesFactory} implementation. Every Java(TM) SE implementation must provide * some means of specifying which <tt>PreferencesFactory</tt> implementation * is used to generate the root preferences nodes. This allows the * administrator to replace the default preferences implementation with an * alternative implementation. * * <p>Implementation note: In Sun's JRE, the <tt>PreferencesFactory</tt> * implementation is located as follows: * * <ol> * * <li><p>If the system property * <tt>java.util.prefs.PreferencesFactory</tt> is defined, then it is * taken to be the fully-qualified name of a class implementing the * <tt>PreferencesFactory</tt> interface. The class is loaded and * instantiated; if this process fails then an unspecified error is * thrown.</p></li> * * <li><p> If a <tt>PreferencesFactory</tt> implementation class file * has been installed in a jar file that is visible to the * {@link java.lang.ClassLoader#getSystemClassLoader system class loader}, * and that jar file contains a provider-configuration file named * <tt>java.util.prefs.PreferencesFactory</tt> in the resource * directory <tt>META-INF/services</tt>, then the first class name * specified in that file is taken. If more than one such jar file is * provided, the first one found will be used. The class is loaded * and instantiated; if this process fails then an unspecified error * is thrown. </p></li> * * <li><p>Finally, if neither the above-mentioned system property nor * an extension jar file is provided, then the system-wide default * <tt>PreferencesFactory</tt> implementation for the underlying * platform is loaded and instantiated.</p></li> * * </ol> * * @author Josh Bloch * @since 1.4 */public abstract class Preferences { private static final PreferencesFactory factory = factory(); private static PreferencesFactory factory() { // 1. Try user-specified system property String factoryName = AccessController.doPrivileged( new PrivilegedAction<String>() { public String run() { return System.getProperty( "java.util.prefs.PreferencesFactory");}}); if (factoryName != null) { // FIXME: This code should be run in a doPrivileged and // not use the context classloader, to avoid being // dependent on the invoking thread. // Checking AllPermission also seems wrong. try { return (PreferencesFactory) Class.forName(factoryName, false, ClassLoader.getSystemClassLoader()) .newInstance(); } catch (Exception ex) { try { // workaround for javaws, plugin, // load factory class using non-system classloader SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new java.security.AllPermission()); } return (PreferencesFactory) Class.forName(factoryName, false, Thread.currentThread() .getContextClassLoader()) .newInstance(); } catch (Exception e) { InternalError error = new InternalError( "Can't instantiate Preferences factory " + factoryName); error.initCause(e); throw error; } } } return AccessController.doPrivileged( new PrivilegedAction<PreferencesFactory>() { public PreferencesFactory run() { return factory1();}}); } private static PreferencesFactory factory1() { // 2. Try service provider interface Iterator<PreferencesFactory> itr = ServiceLoader .load(PreferencesFactory.class, ClassLoader.getSystemClassLoader()) .iterator(); // choose first provider instance while (itr.hasNext()) { try { return itr.next(); } catch (ServiceConfigurationError sce) { if (sce.getCause() instanceof SecurityException) { // Ignore the security exception, try the next provider continue; } throw sce; } } // 3. Use platform-specific system-wide default String platformFactory = System.getProperty("os.name").startsWith("Windows") ? "java.util.prefs.WindowsPreferencesFactory" : "java.util.prefs.FileSystemPreferencesFactory"; try { return (PreferencesFactory) Class.forName(platformFactory, false, null).newInstance(); } catch (Exception e) { InternalError error = new InternalError( "Can't instantiate platform default Preferences factory " + platformFactory); error.initCause(e); throw error; } } /** * Maximum length of string allowed as a key (80 characters). */ public static final int MAX_KEY_LENGTH = 80; /** * Maximum length of string allowed as a value (8192 characters). */ public static final int MAX_VALUE_LENGTH = 8*1024; /** * Maximum length of a node name (80 characters). */ public static final int MAX_NAME_LENGTH = 80; /** * Returns the preference node from the calling user's preference tree * that is associated (by convention) with the specified class's package. * The convention is as follows: the absolute path name of the node is the * fully qualified package name, preceded by a slash (<tt>'/'</tt>), and * with each period (<tt>'.'</tt>) replaced by a slash. For example the * absolute path name of the node associated with the class * <tt>com.acme.widget.Foo</tt> is <tt>/com/acme/widget</tt>. * * <p>This convention does not apply to the unnamed package, whose * associated preference node is <tt><unnamed></tt>. This node * is not intended for long term use, but for convenience in the early * development of programs that do not yet belong to a package, and * for "throwaway" programs. <i>Valuable data should not be stored * at this node as it is shared by all programs that use it.</i> * * <p>A class <tt>Foo</tt> wishing to access preferences pertaining to its * package can obtain a preference node as follows: <pre> * static Preferences prefs = Preferences.userNodeForPackage(Foo.class); * </pre> * This idiom obviates the need for using a string to describe the * preferences node and decreases the likelihood of a run-time failure. * (If the class name is misspelled, it will typically result in a * compile-time error.) * * <p>Invoking this method will result in the creation of the returned * node and its ancestors if they do not already exist. If the returned * node did not exist prior to this call, this node and any ancestors that * were created by this call are not guaranteed to become permanent until * the <tt>flush</tt> method is called on the returned node (or one of its * ancestors or descendants). * * @param c the class for whose package a user preference node is desired. * @return the user preference node associated with the package of which * <tt>c</tt> is a member. * @throws NullPointerException if <tt>c</tt> is <tt>null</tt>. * @throws SecurityException if a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences userNodeForPackage(Class<?> c) { return userRoot().node(nodeName(c)); } /** * Returns the preference node from the system preference tree that is * associated (by convention) with the specified class's package. The * convention is as follows: the absolute path name of the node is the * fully qualified package name, preceded by a slash (<tt>'/'</tt>), and * with each period (<tt>'.'</tt>) replaced by a slash. For example the * absolute path name of the node associated with the class * <tt>com.acme.widget.Foo</tt> is <tt>/com/acme/widget</tt>. * * <p>This convention does not apply to the unnamed package, whose * associated preference node is <tt><unnamed></tt>. This node * is not intended for long term use, but for convenience in the early * development of programs that do not yet belong to a package, and * for "throwaway" programs. <i>Valuable data should not be stored * at this node as it is shared by all programs that use it.</i> * * <p>A class <tt>Foo</tt> wishing to access preferences pertaining to its * package can obtain a preference node as follows: <pre> * static Preferences prefs = Preferences.systemNodeForPackage(Foo.class); * </pre> * This idiom obviates the need for using a string to describe the * preferences node and decreases the likelihood of a run-time failure. * (If the class name is misspelled, it will typically result in a * compile-time error.) * * <p>Invoking this method will result in the creation of the returned * node and its ancestors if they do not already exist. If the returned * node did not exist prior to this call, this node and any ancestors that * were created by this call are not guaranteed to become permanent until * the <tt>flush</tt> method is called on the returned node (or one of its * ancestors or descendants). * * @param c the class for whose package a system preference node is desired. * @return the system preference node associated with the package of which * <tt>c</tt> is a member. * @throws NullPointerException if <tt>c</tt> is <tt>null</tt>. * @throws SecurityException if a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences systemNodeForPackage(Class<?> c) { return systemRoot().node(nodeName(c)); } /** * Returns the absolute path name of the node corresponding to the package * of the specified object. * * @throws IllegalArgumentException if the package has node preferences * node associated with it. */ private static String nodeName(Class c) { if (c.isArray()) throw new IllegalArgumentException( "Arrays have no associated preferences node."); String className = c.getName(); int pkgEndIndex = className.lastIndexOf('.'); if (pkgEndIndex < 0) return "/<unnamed>"; String packageName = className.substring(0, pkgEndIndex); return "/" + packageName.replace('.', '/'); } /** * This permission object represents the permission required to get * access to the user or system root (which in turn allows for all * other operations). */ private static Permission prefsPerm = new RuntimePermission("preferences"); /** * Returns the root preference node for the calling user. * * @return the root preference node for the calling user. * @throws SecurityException If a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences userRoot() { SecurityManager security = System.getSecurityManager(); if (security != null) security.checkPermission(prefsPerm); return factory.userRoot(); } /** * Returns the root preference node for the system. * * @return the root preference node for the system. * @throws SecurityException If a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences systemRoot() { SecurityManager security = System.getSecurityManager(); if (security != null) security.checkPermission(prefsPerm); return factory.systemRoot(); } /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected Preferences() { } /** * Associates the specified value with the specified key in this * preference node. * * @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 <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt> or if <tt>value.length</tt> exceeds * <tt>MAX_VALUE_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public abstract void put(String key, String value); /** * Returns the value associated with the specified key in this preference * node. Returns the specified default if there is no value associated * with the key, or the backing store is inaccessible. * * <p>Some implementations may store default values in their backing * stores. If there is no value associated with the specified key * but there is such a <i>stored default</i>, it is returned inLines 1–500 of 1256. Load more
/* * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.prefs; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.security.AccessController; import java.security.Permission; import java.security.PrivilegedAction; import java.util.Iterator; import java.util.ServiceLoader; import java.util.ServiceConfigurationError; // These imports needed only as a workaround for a JavaDoc bug import java.lang.RuntimePermission; import java.lang.Integer; import java.lang.Long; import java.lang.Float; import java.lang.Double; /** * A node in a hierarchical collection of preference data. This class * allows applications to store and retrieve user and system * preference and configuration data. This data is stored * persistently in an implementation-dependent backing store. Typical * implementations include flat files, OS-specific registries, * directory servers and SQL databases. The user of this class needn't * be concerned with details of the backing store. * * <p>There are two separate trees of preference nodes, one for user * preferences and one for system preferences. Each user has a separate user * preference tree, and all users in a given system share the same system * preference tree. The precise description of "user" and "system" will vary * from implementation to implementation. Typical information stored in the * user preference tree might include font choice, color choice, or preferred * window location and size for a particular application. Typical information * stored in the system preference tree might include installation * configuration data for an application. * * <p>Nodes in a preference tree are named in a similar fashion to * directories in a hierarchical file system. Every node in a preference * tree has a <i>node name</i> (which is not necessarily unique), * a unique <i>absolute path name</i>, and a path name <i>relative</i> to each * ancestor including itself. * * <p>The root node has a node name of the empty string (""). Every other * node has an arbitrary node name, specified at the time it is created. The * only restrictions on this name are that it cannot be the empty string, and * it cannot contain the slash character ('/'). * * <p>The root node has an absolute path name of <tt>"/"</tt>. Children of * the root node have absolute path names of <tt>"/" + </tt><i><node * name></i>. All other nodes have absolute path names of <i><parent's * absolute path name></i><tt> + "/" + </tt><i><node name></i>. * Note that all absolute path names begin with the slash character. * * <p>A node <i>n</i>'s path name relative to its ancestor <i>a</i> * is simply the string that must be appended to <i>a</i>'s absolute path name * in order to form <i>n</i>'s absolute path name, with the initial slash * character (if present) removed. Note that: * <ul> * <li>No relative path names begin with the slash character. * <li>Every node's path name relative to itself is the empty string. * <li>Every node's path name relative to its parent is its node name (except * for the root node, which does not have a parent). * <li>Every node's path name relative to the root is its absolute path name * with the initial slash character removed. * </ul> * * <p>Note finally that: * <ul> * <li>No path name contains multiple consecutive slash characters. * <li>No path name with the exception of the root's absolute path name * ends in the slash character. * <li>Any string that conforms to these two rules is a valid path name. * </ul> * * <p>All of the methods that modify preferences data are permitted to operate * asynchronously; they may return immediately, and changes will eventually * propagate to the persistent backing store with an implementation-dependent * delay. The <tt>flush</tt> method may be used to synchronously force * updates to the backing store. Normal termination of the Java Virtual * Machine will <i>not</i> result in the loss of pending updates -- an explicit * <tt>flush</tt> invocation is <i>not</i> required upon termination to ensure * that pending updates are made persistent. * * <p>All of the methods that read preferences from a <tt>Preferences</tt> * object require the invoker to provide a default value. The default value is * returned if no value has been previously set <i>or if the backing store is * unavailable</i>. The intent is to allow applications to operate, albeit * with slightly degraded functionality, even if the backing store becomes * unavailable. Several methods, like <tt>flush</tt>, have semantics that * prevent them from operating if the backing store is unavailable. Ordinary * applications should have no need to invoke any of these methods, which can * be identified by the fact that they are declared to throw {@link * BackingStoreException}. * * <p>The methods in this class may be invoked concurrently by multiple threads * in a single JVM without the need for external synchronization, and the * results will be equivalent to some serial execution. If this class is used * concurrently <i>by multiple JVMs</i> that store their preference data in * the same backing store, the data store will not be corrupted, but no * other guarantees are made concerning the consistency of the preference * data. * * <p>This class contains an export/import facility, allowing preferences * to be "exported" to an XML document, and XML documents representing * preferences to be "imported" back into the system. This facility * may be used to back up all or part of a preference tree, and * subsequently restore from the backup. * * <p>The XML document has the following DOCTYPE declaration: * <pre> * <!DOCTYPE preferences SYSTEM "http://java.sun.com/dtd/preferences.dtd"> * </pre> * Note that the system URI (http://java.sun.com/dtd/preferences.dtd) is * <i>not</i> accessed when exporting or importing preferences; it merely * serves as a string to uniquely identify the DTD, which is: * <pre> * <?xml version="1.0" encoding="UTF-8"?> * * <!-- DTD for a Preferences tree. --> * * <!-- The preferences element is at the root of an XML document * representing a Preferences tree. --> * <!ELEMENT preferences (root)> * * <!-- The preferences element contains an optional version attribute, * which specifies version of DTD. --> * <!ATTLIST preferences EXTERNAL_XML_VERSION CDATA "0.0" > * * <!-- The root element has a map representing the root's preferences * (if any), and one node for each child of the root (if any). --> * <!ELEMENT root (map, node*) > * * <!-- Additionally, the root contains a type attribute, which * specifies whether it's the system or user root. --> * <!ATTLIST root * type (system|user) #REQUIRED > * * <!-- Each node has a map representing its preferences (if any), * and one node for each child (if any). --> * <!ELEMENT node (map, node*) > * * <!-- Additionally, each node has a name attribute --> * <!ATTLIST node * name CDATA #REQUIRED > * * <!-- A map represents the preferences stored at a node (if any). --> * <!ELEMENT map (entry*) > * * <!-- An entry represents a single preference, which is simply * a key-value pair. --> * <!ELEMENT entry EMPTY > * <!ATTLIST entry * key CDATA #REQUIRED * value CDATA #REQUIRED > * </pre> * * Every <tt>Preferences</tt> implementation must have an associated {@link * PreferencesFactory} implementation. Every Java(TM) SE implementation must provide * some means of specifying which <tt>PreferencesFactory</tt> implementation * is used to generate the root preferences nodes. This allows the * administrator to replace the default preferences implementation with an * alternative implementation. * * <p>Implementation note: In Sun's JRE, the <tt>PreferencesFactory</tt> * implementation is located as follows: * * <ol> * * <li><p>If the system property * <tt>java.util.prefs.PreferencesFactory</tt> is defined, then it is * taken to be the fully-qualified name of a class implementing the * <tt>PreferencesFactory</tt> interface. The class is loaded and * instantiated; if this process fails then an unspecified error is * thrown.</p></li> * * <li><p> If a <tt>PreferencesFactory</tt> implementation class file * has been installed in a jar file that is visible to the * {@link java.lang.ClassLoader#getSystemClassLoader system class loader}, * and that jar file contains a provider-configuration file named * <tt>java.util.prefs.PreferencesFactory</tt> in the resource * directory <tt>META-INF/services</tt>, then the first class name * specified in that file is taken. If more than one such jar file is * provided, the first one found will be used. The class is loaded * and instantiated; if this process fails then an unspecified error * is thrown. </p></li> * * <li><p>Finally, if neither the above-mentioned system property nor * an extension jar file is provided, then the system-wide default * <tt>PreferencesFactory</tt> implementation for the underlying * platform is loaded and instantiated.</p></li> * * </ol> * * @author Josh Bloch * @since 1.4 */ public abstract class Preferences { private static final PreferencesFactory factory = factory(); private static PreferencesFactory factory() { // 1. Try user-specified system property String factoryName = AccessController.doPrivileged( new PrivilegedAction<String>() { public String run() { return System.getProperty( "java.util.prefs.PreferencesFactory");}}); if (factoryName != null) { // FIXME: This code should be run in a doPrivileged and // not use the context classloader, to avoid being // dependent on the invoking thread. // Checking AllPermission also seems wrong. try { return (PreferencesFactory) Class.forName(factoryName, false, ClassLoader.getSystemClassLoader()) .newInstance(); } catch (Exception ex) { try { // workaround for javaws, plugin, // load factory class using non-system classloader SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new java.security.AllPermission()); } return (PreferencesFactory) Class.forName(factoryName, false, Thread.currentThread() .getContextClassLoader()) .newInstance(); } catch (Exception e) { InternalError error = new InternalError( "Can't instantiate Preferences factory " + factoryName); error.initCause(e); throw error; } } } return AccessController.doPrivileged( new PrivilegedAction<PreferencesFactory>() { public PreferencesFactory run() { return factory1();}}); } private static PreferencesFactory factory1() { // 2. Try service provider interface Iterator<PreferencesFactory> itr = ServiceLoader .load(PreferencesFactory.class, ClassLoader.getSystemClassLoader()) .iterator(); // choose first provider instance while (itr.hasNext()) { try { return itr.next(); } catch (ServiceConfigurationError sce) { if (sce.getCause() instanceof SecurityException) { // Ignore the security exception, try the next provider continue; } throw sce; } } // 3. Use platform-specific system-wide default String platformFactory = System.getProperty("os.name").startsWith("Windows") ? "java.util.prefs.WindowsPreferencesFactory" : "java.util.prefs.FileSystemPreferencesFactory"; try { return (PreferencesFactory) Class.forName(platformFactory, false, null).newInstance(); } catch (Exception e) { InternalError error = new InternalError( "Can't instantiate platform default Preferences factory " + platformFactory); error.initCause(e); throw error; } } /** * Maximum length of string allowed as a key (80 characters). */ public static final int MAX_KEY_LENGTH = 80; /** * Maximum length of string allowed as a value (8192 characters). */ public static final int MAX_VALUE_LENGTH = 8*1024; /** * Maximum length of a node name (80 characters). */ public static final int MAX_NAME_LENGTH = 80; /** * Returns the preference node from the calling user's preference tree * that is associated (by convention) with the specified class's package. * The convention is as follows: the absolute path name of the node is the * fully qualified package name, preceded by a slash (<tt>'/'</tt>), and * with each period (<tt>'.'</tt>) replaced by a slash. For example the * absolute path name of the node associated with the class * <tt>com.acme.widget.Foo</tt> is <tt>/com/acme/widget</tt>. * * <p>This convention does not apply to the unnamed package, whose * associated preference node is <tt><unnamed></tt>. This node * is not intended for long term use, but for convenience in the early * development of programs that do not yet belong to a package, and * for "throwaway" programs. <i>Valuable data should not be stored * at this node as it is shared by all programs that use it.</i> * * <p>A class <tt>Foo</tt> wishing to access preferences pertaining to its * package can obtain a preference node as follows: <pre> * static Preferences prefs = Preferences.userNodeForPackage(Foo.class); * </pre> * This idiom obviates the need for using a string to describe the * preferences node and decreases the likelihood of a run-time failure. * (If the class name is misspelled, it will typically result in a * compile-time error.) * * <p>Invoking this method will result in the creation of the returned * node and its ancestors if they do not already exist. If the returned * node did not exist prior to this call, this node and any ancestors that * were created by this call are not guaranteed to become permanent until * the <tt>flush</tt> method is called on the returned node (or one of its * ancestors or descendants). * * @param c the class for whose package a user preference node is desired. * @return the user preference node associated with the package of which * <tt>c</tt> is a member. * @throws NullPointerException if <tt>c</tt> is <tt>null</tt>. * @throws SecurityException if a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences userNodeForPackage(Class<?> c) { return userRoot().node(nodeName(c)); } /** * Returns the preference node from the system preference tree that is * associated (by convention) with the specified class's package. The * convention is as follows: the absolute path name of the node is the * fully qualified package name, preceded by a slash (<tt>'/'</tt>), and * with each period (<tt>'.'</tt>) replaced by a slash. For example the * absolute path name of the node associated with the class * <tt>com.acme.widget.Foo</tt> is <tt>/com/acme/widget</tt>. * * <p>This convention does not apply to the unnamed package, whose * associated preference node is <tt><unnamed></tt>. This node * is not intended for long term use, but for convenience in the early * development of programs that do not yet belong to a package, and * for "throwaway" programs. <i>Valuable data should not be stored * at this node as it is shared by all programs that use it.</i> * * <p>A class <tt>Foo</tt> wishing to access preferences pertaining to its * package can obtain a preference node as follows: <pre> * static Preferences prefs = Preferences.systemNodeForPackage(Foo.class); * </pre> * This idiom obviates the need for using a string to describe the * preferences node and decreases the likelihood of a run-time failure. * (If the class name is misspelled, it will typically result in a * compile-time error.) * * <p>Invoking this method will result in the creation of the returned * node and its ancestors if they do not already exist. If the returned * node did not exist prior to this call, this node and any ancestors that * were created by this call are not guaranteed to become permanent until * the <tt>flush</tt> method is called on the returned node (or one of its * ancestors or descendants). * * @param c the class for whose package a system preference node is desired. * @return the system preference node associated with the package of which * <tt>c</tt> is a member. * @throws NullPointerException if <tt>c</tt> is <tt>null</tt>. * @throws SecurityException if a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences systemNodeForPackage(Class<?> c) { return systemRoot().node(nodeName(c)); } /** * Returns the absolute path name of the node corresponding to the package * of the specified object. * * @throws IllegalArgumentException if the package has node preferences * node associated with it. */ private static String nodeName(Class c) { if (c.isArray()) throw new IllegalArgumentException( "Arrays have no associated preferences node."); String className = c.getName(); int pkgEndIndex = className.lastIndexOf('.'); if (pkgEndIndex < 0) return "/<unnamed>"; String packageName = className.substring(0, pkgEndIndex); return "/" + packageName.replace('.', '/'); } /** * This permission object represents the permission required to get * access to the user or system root (which in turn allows for all * other operations). */ private static Permission prefsPerm = new RuntimePermission("preferences"); /** * Returns the root preference node for the calling user. * * @return the root preference node for the calling user. * @throws SecurityException If a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences userRoot() { SecurityManager security = System.getSecurityManager(); if (security != null) security.checkPermission(prefsPerm); return factory.userRoot(); } /** * Returns the root preference node for the system. * * @return the root preference node for the system. * @throws SecurityException If a security manager is present and * it denies <tt>RuntimePermission("preferences")</tt>. * @see RuntimePermission */ public static Preferences systemRoot() { SecurityManager security = System.getSecurityManager(); if (security != null) security.checkPermission(prefsPerm); return factory.systemRoot(); } /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected Preferences() { } /** * Associates the specified value with the specified key in this * preference node. * * @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 <tt>null</tt>. * @throws IllegalArgumentException if <tt>key.length()</tt> exceeds * <tt>MAX_KEY_LENGTH</tt> or if <tt>value.length</tt> exceeds * <tt>MAX_VALUE_LENGTH</tt>. * @throws IllegalStateException if this node (or an ancestor) has been * removed with the {@link #removeNode()} method. */ public abstract void put(String key, String value); /** * Returns the value associated with the specified key in this preference * node. Returns the specified default if there is no value associated * with the key, or the backing store is inaccessible. * * <p>Some implementations may store default values in their backing * stores. If there is no value associated with the specified key * but there is such a <i>stored default</i>, it is returned in