Java.utils.prefs.Preferences API throws exception on Mac, not Windows

This is a Mac-specific problem. Is it a bug, or am I misusing the java.utils.prefs.Preferences API?
The Preferences flush() API call always throws a BackingStoreException if a system tree preferences root has been read. The system tree has not been modified or written to, but the flush() call is nevertheless throwing an exception. This occurs when running as a normal user without the ability to write to /Library/Preferences.
See sample code below. Note that I only want to read the system prefs tree. The user tree write flush fails. If the system tree node is not created, the user flush() succeeds.
Steps to Reproduce
Delete any existing Java prefs files:
~/Library/Preferences/com.apple.java.util.prefs.plist
~/Library/Preferences/com.mycompany.prefstest
/Library/Preferences/com.apple.java.util.prefs.plist
/Library/Preferences/com.mycompany.prefstest
Run the following Java code:
package com.mycompany.prefstest;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
public class PrefsTest {
      * @param args
     public static void main(String[] args) {
          String strKey1 = "com/mycompany/prefstest/one/two/three/four/key1";
          Preferences systemRoot = Preferences.systemRoot();
          Preferences userRoot = Preferences.userRoot();
          // Get a value for user prefs.
          String value1 = userRoot.get(strKey1, "missing");
          // Fall back to system prefs if it is not defined.
          if (value1.equals("missing"))
               value1 = systemRoot.get(strKey1, "missing");
          System.out.println("key1 --> " + value1);
          // If still not defined, set a user-specific value
          if (value1.equals("missing"))
               userRoot.put(strKey1, "value1");
               try {
                    userRoot.flush();
                    System.out.println("flushed prefs successfully");
               catch (BackingStoreException e)
                    System.out.println("Exception: " + e.toString());
Expected Results
Should produce the output:
key --> missing
flushed prefs successfully
Actual Results
Console output is
key --> missing
Exception: java.util.prefs.BackingStoreException: Synchronization failed for node '/'
Notes
$ java -version
java version "1.6.0_29"
Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-11D50b)
Java HotSpot(TM) 64-Bit Server VM (build 20.4-b02-402, mixed mode)
also tested with:
java version "1.7.0_04-ea"
Java(TM) SE Runtime Environment (build 1.7.0_04-ea-b16)
Java HotSpot(TM) 64-Bit Server VM (build 23.0-b17, mixed mode)
Mac OS X 10.7.3.
The "Expected Results" are correctly obtained running the same code on MS-Windows.
Running the jar as sudo works (with write access to /Library/Preferences), as expected.

Just for fun, try a key without slashes in it (but for example dots if you must use such a long key).
I say that because a quick Google search points out that Apple stores the preferences in a file hierarchy in the user home folder. I can already see how using keys which look like a file path are going to cause nuclear reactors to meltdown...

Similar Messages

  • How to create a node in java.util.prefs.Preferences  -- Need Help !!

    Hi All
    I want to know the way of implementing a Node using java.util.prefs.Preferences , and need to store a value.
    Your Help wil be greatly appreciated
    best Regards
    Madumm

    http://java.sun.com/j2se/1.5.0/docs/api/java/util/prefs/Preferences.html

  • Java.util.pref.Preferences

    Hello Sir,
    Is java.util.pref.Preferences class support property file?
    Thanks for advance
    bala

    Read the API for Preferences.
    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.
    Does that answer your question?
    db

  • How can I create an instance of "java.util.prefs.WindowsPreferences"?

    Hi All,
    I was trying to find out a way to access the Windows Registry to add soome keys and and later add a string.
    I found WindowsPreferences might be useful in the above mentioned context.
    I was trying to create an instance of it, but when I import the class, it says it is invisible.
    Can anyone let me know how to instantiate this class.
    Note:- Under the same package "java.util.prefs" we have another class "Preferences", Iam able to import this one and use it in my code.
    Thank You.
    Regards,
    Suman.H

    It's true that Preferences uses the Registry on Windows systems, that does not mean you can use it as a Registry API. The only part of the Registry you can access are those branches that are set aside for java.util.prefs: HKLM\Software\JavaSoft\Prefs and HKCU\Software\JavaSoft\Prefs. IF you need to access other parts of the Registry, you'll need to use JNI or a separate Windows Registry library.

  • PDFLPrintDoc function throw exception on Mac in PDF Lib 10

    Hi,
    Currently I'm doing the work of upgrading a xcode project on Mac from PDF lib from 8.1 to 10.
    After change to use PDF lib 10 framework, and build project, I found it throw an exception when calling function PDFLPrintDoc to print PS type, error message saying An internal error occured.
    However, on Win platform, it is ok.
    I read from release note that since PDF lib 9,  
    PDFLPrintDoc() honors only default values for tilingMode (kPDNoTiling)
    In the previous code, the  flattenInfo variable in PDPrintParams is a null porinter, so I manuall add code to set PDFlattenTilingMode to be kPDNoTiling.
    But the problem is, now when running ,it still throw exception saying "An internal error occured" , nothing changed.
    Has anybody here encountered such problem?
    Please give me an answer, thanks~

    Since this is PDFL, you have a license from either Adobe or Datalogics.  Please contact their support directly.

  • Xjc throwing exception that "document not well formed"

    I have the following DTD file given in the sample code saved as item.dtd
    <?xml version='1.0' encoding='utf-8'?>
    <!-- Simple DTD -->
    <!ELEMENT item_list (item_info*)>
    <!ELEMENT item_info (name, price)>
    <!ELEMENT name (#PCDATA)>
    <!ELEMENT price (#PCDATA)>
    and the following xjs file as given in the sample code
    saved as item.xjs
    <xml-java-binding-schema>
    <element name="item_list" type="class" root="true"/>
    <element name="item_info" type="class"/>
    </xml-java-binding-schema>
    now from command prompt when I run the following command, it throws the following error.
    c:\Some-folder\ xjc item.dtd item.xjs
    the EXCEPTION thrown is :
    The markup in the document preceding the root element must be well-formed. line 4 of item.dtd
    The FULL TRACE is(if anybody is interested to see).. PLEASE HELP ME OUT.
    Thanks
    Gagan
    TRACE STARTS HERE:
    parsing a schema...
    The markup in the document preceding the root element must be well-formed.
    line 4 of item.dtd
    Exception in thread "main" ::file:///C:/RBML/xml-java/item.dtd:file:///C:/RBML/x
    ml-java/item.dtd:file:///C:/RBML/xml-java/item.dtd:4:3:The markup in the document preceding the root element must be well-formed.

    NO i dont think so..
    as you could see the code pasted in the first instance. the only diffrence is that you are using double quotes.(I tried that as well)
    I hope you are referring to item.dtd file not item.xjs file
    Thanks
    Gagan

  • Preferences import generates exception.

    Hi!
    So, here is a newbie question:
    Is it possible to use the new preferences API together with JDeveloper9i?
    When I create a simple new project, using J2SE1.4 and do something like this:
    try
    Preferences.importPreferences( new FileInputStream( "C:\\JDev9i\\jdev\\mywork\\System.xml" ) );
    catch (Exception ex)
    ex.printStackTrace();
    everything works okay. When I try to use the very same lines in my JClient client project, accessing a BC4J module in local deployment (no app server), I get an exception:
    java.lang.ClassCastException: oracle.xml.parser.v2.DTD
         at java.util.prefs.XmlSupport.importPreferences(XmlSupport.java:182)
         at java.util.prefs.Preferences.importPreferences(Preferences.java:1138)
         at test.Untitled1.<init>(Untitled1.java:38)
         at test.Untitled1.main(Untitled1.java:68)
    Has anyone else experienced this? In my simple project it works, in my real project I get an exception. The Oracle XML parser is not part of either project.
    Thanx in advance for your help!
    Sascha Herrmann

    I think there are a couple of things going on here.
    [list=1]
    [*] is that while parsing the Text.xml file, our XML parser is opening the DTD referenced in the DOCTYPE which it must do to see if the DTD has any default attribute values which need to be included in the parsed tree representation).
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE preferences SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>
    <preferences EXTERNAL_XML_VERSION="1.0">
      <root type="user">
        <map />
        <node name="Test">
          <map>
            <entry key="TestEntry" value="true" />
          </map>
        </node>
      </root>
    </preferences>If you don't have your proxy server set correctly, then the attempt to fetch the DTD at it's SYSTEM id URI: http://java.sun.com/dtd/preferences.dtd will hang, and then ultimately fail.
    [*] There is a bug in the JDK 1.4 java.util.prefs.XmlSupport class at line 183:
    ((Element)doc.getChildNodes().item(1)).getAttribute("EXTERNAL_XML_VERSION");.
    where they are making a (bold, and bad) assumption that the 2nd child node of the document object IS the document element. This is not necessary true, and in fact with both Oracle XML Parser 9.0.2 and Apache Xerces 2.1.0 that I tested, it's a bad assumption since both of these JAXP 1.1 compliant XML Parsers fail the simple test example class of:
    import java.io.FileInputStream;
    import java.util.prefs.Preferences;
    public class Test {
    public static void main(String[] args) throws Throwable {
          Preferences.importPreferences(
                        new FileInputStream( "C:\\temp\\sacha\\PrefsTest\\Test.xml" ) );
          System.out.println("ok");
    At line 183 when XmlSupport tries to cast the 2nd child of the document node to (Element), Xerces 2.1.0 fails with
    java.lang.ClassCastException: org.apache.xerces.dom.DeferredCommentImpl.
    and Oracle XML Parser 9.0.2 fails with:
    java.lang.ClassCastException: oracle.xml.parser.v2.DTD.
    they should have written instead:
    String xmlVersion = doc.getDocumentElement().getAttribute("EXTERNAL_XML_VERSION");.
    instead of what they did.
    [list]
    Of course, it works OK when you use the Sun Crimson XML parser which is included by default in the JDK 1.4, and apparently that's the only one they tested.
    However, JClient requires the Oracle XML Parser so you need to use the Oracle XML Parser implementation of JAXP 1.1 (which should work fine, except for this bug). I patched the java.util.XmlSupport class, and prepended my fixed version of this class to the System classpath by adding the following Java VM command line parameter:
    -Xbootclasspath/p:C:\temp\xmlsupportfix\classes.
    and then I'm able to run your Client example with no problems.
    Not sure if Sun knows about this bug, but I'll look into it.
    I've attached my patched version of this JDK 1.4 class. I changed like 183 and line 192 (which had another use of the "bad assumption" DOM code.) Here it is:
    * @(#)XmlSupport.java  1.10 01/12/03
    * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
    * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
    package java.util.prefs;
    import java.util.*;
    import java.io.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.w3c.dom.*;
    import org.apache.crimson.tree.*;
    * XML Support for java.util.prefs. Methods to import and export preference
    * nodes and subtrees.
    * @author  Josh Bloch and Mark Reinhold
    * @version 1.10, 12/03/01
    * @see     Preferences
    * @since   1.4
    class XmlSupport {
        // The required DTD URI for exported preferences
        private static final String PREFS_DTD_URI =
            "http://java.sun.com/dtd/preferences.dtd";
        // The actual DTD corresponding to the URI
        private static final String PREFS_DTD =
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "<!-- DTD for preferences -->"               +
            "<!ELEMENT preferences (root) >"             +
            "<!ATTLIST preferences"                      +
            " EXTERNAL_XML_VERSION CDATA \"0.0\"  >"     +
            "<!ELEMENT root (map, node*) >"              +
            "<!ATTLIST root"                             +
            "          type (system|user) #REQUIRED >"   +
            "<!ELEMENT node (map, node*) >"              +
            "<!ATTLIST node"                             +
            "          name CDATA #REQUIRED >"           +
            "<!ELEMENT map (entry*) >"                   +
            "<!ATTLIST map"                              +
            "  MAP_XML_VERSION CDATA \"0.0\"  >"         +
            "<!ELEMENT entry EMPTY >"                    +
            "<!ATTLIST entry"                            +
            "          key CDATA #REQUIRED"              +
            "          value CDATA #REQUIRED >"          ;
         * Version number for the format exported preferences files.
        private static final String EXTERNAL_XML_VERSION = "1.0";
         * Version number for the internal map files.
        private static final String MAP_XML_VERSION = "1.0";
         * Export the specified preferences node and, if subTree is true, all
         * subnodes, to the specified output stream.  Preferences are exported as
         * an XML document conforming to the definition in the Preferences spec.
         * @throws IOException if writing to the specified output stream
         *         results in an <tt>IOException</tt>.
         * @throws BackingStoreException if preference data cannot be read from
         *         backing store.
         * @throws IllegalStateException if this node (or an ancestor) has been
         *         removed with the {@link #removeNode()} method.
        static void export(OutputStream os, final Preferences p, boolean subTree)
            throws IOException, BackingStoreException {
            if (((AbstractPreferences)p).isRemoved())
                throw new IllegalStateException("Node has been removed");               
            XmlDocument doc = new XmlDocument();
            doc.setDoctype(null, PREFS_DTD_URI, null);
            Element preferences =  (Element)
                doc.appendChild(doc.createElement("preferences"));
            preferences.setAttribute("EXTERNAL_XML_VERSION", EXTERNAL_XML_VERSION);
            Element xmlRoot =  (Element)
            preferences.appendChild(doc.createElement("root"));
            xmlRoot.setAttribute("type", (p.isUserNode() ? "user" : "system"));
            // Get bottom-up list of nodes from p to root, excluding root
            List ancestors = new ArrayList();
            for (Preferences kid = p, dad = kid.parent(); dad != null;
                                       kid = dad, dad = kid.parent()) {
                ancestors.add(kid);
            Element e = xmlRoot;                       
            for (int i=ancestors.size()-1; i >= 0; i--) {
                e.appendChild(doc.createElement("map"));
                e = (Element) e.appendChild(doc.createElement("node"));
                e.setAttribute("name", ((Preferences)ancestors.get(i)).name());
            putPreferencesInXml(e, doc, p, subTree);
            doc.write(os);
         * Put the preferences in the specified Preferences node into the
         * specified XML element which is assumed to represent a node
         * in the specified XML document which is assumed to conform to
         * PREFS_DTD.  If subTree is true, create children of the specified
         * XML node conforming to all of the children of the specified
         * Preferences node and recurse.
         * @throws BackingStoreException if it is not possible to read
         *         the preferences or children out of the specified
         *         preferences node.
        private static void putPreferencesInXml(Element elt, Document doc,
                   Preferences prefs, boolean subTree) throws BackingStoreException
            Preferences[] kidsCopy = null;
            String[] kidNames = null;
            // Node is locked to export its contents and get a
            // copy of children, then lock is released,
            // and, if subTree = true, recursive calls are made on children
            synchronized (((AbstractPreferences)prefs).lock) {
                // Check if this node was concurrently removed. If yes
                // remove it from XML Document and return.
                if (((AbstractPreferences)prefs).isRemoved()) {
                    elt.getParentNode().removeChild(elt);
                    return;
                // Put map in xml element           
                String[] keys = prefs.keys();
                Element map = (Element) elt.appendChild(doc.createElement("map"));
                for (int i=0; i<keys.length; i++) {
                    Element entry = (Element)
                        map.appendChild(doc.createElement("entry"));
                    entry.setAttribute("key", keys);
    // NEXT STATEMENT THROWS NULL PTR EXC INSTEAD OF ASSERT FAIL
    entry.setAttribute("value", prefs.get(keys[i], null));
    // Recurse if appropriate
    if (subTree) {
    /* Get a copy of kids while lock is held */
    kidNames = prefs.childrenNames();
    kidsCopy = new Preferences[kidNames.length];
    for (int i = 0; i < kidNames.length; i++)
    kidsCopy[i] = prefs.node(kidNames[i]);
    // release lock
    if (subTree) {
    for (int i=0; i < kidNames.length; i++) {
    Element xmlKid = (Element)
    elt.appendChild(doc.createElement("node"));
    xmlKid.setAttribute("name", kidNames[i]);
    putPreferencesInXml(xmlKid, doc, kidsCopy[i], subTree);
    * Import preferences from the specified input stream, which is assumed
    * to contain an XML document in the format described in the Preferences
    * spec.
    * @throws IOException if reading from the specified output stream
    * results in an <tt>IOException</tt>.
    * @throws InvalidPreferencesFormatException Data on input stream does not
    * constitute a valid XML document with the mandated document type.
    static void importPreferences(InputStream is)
    throws IOException, InvalidPreferencesFormatException
    try {
    Document doc = load(is);
    String xmlVersion =
    // SPM - Fix bad assumption of getChildNodes().item(1)
    doc.getDocumentElement().getAttribute("EXTERNAL_XML_VERSION");
    if (xmlVersion.compareTo(EXTERNAL_XML_VERSION) > 0)
    throw new InvalidPreferencesFormatException(
    "Exported preferences file format version " + xmlVersion +
    " is not supported. This java installation can read" +
    " versions " + EXTERNAL_XML_VERSION + " or older. You may need" +
    " to install a newer version of JDK.");
    // SPM - Fix bad assumption of getChildNodes().item(1)
    Element xmlRoot = (Element)doc.getDocumentElement().getChildNodes().item(0);
    Preferences prefsRoot =
    (xmlRoot.getAttribute("type").equals("user") ?
    Preferences.userRoot() : Preferences.systemRoot());
    ImportSubtree(prefsRoot, xmlRoot);
    } catch(SAXException e) {
    throw new InvalidPreferencesFormatException(e);
    * Load an XML document from specified input stream, which must
    * have the requisite DTD URI.
    private static Document load(InputStream in)
    throws SAXException, IOException
    Resolver r = new Resolver();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setValidating(true);
    dbf.setCoalescing(true);
    try {
    DocumentBuilder db = dbf.newDocumentBuilder();
    db.setEntityResolver(new Resolver());
    db.setErrorHandler(new EH());
    return db.parse(new InputSource(in));
    } catch (ParserConfigurationException x) {
    throw new Error(x);
    * Recursively traverse the specified preferences node and store
    * the described preferences into the system or current user
    * preferences tree, as appropriate.
    private static void ImportSubtree(Preferences prefsNode, Element xmlNode) {
    NodeList xmlKids = xmlNode.getChildNodes();
    int numXmlKids = xmlKids.getLength();
    * We first lock the node, import its contents and get
    * child nodes. Then we unlock the node and go to children
    * Since some of the children might have been concurrently
    * deleted we check for this.
    Preferences[] prefsKids;
    /* Lock the node */
    synchronized (((AbstractPreferences)prefsNode).lock) {
    //If removed, return silently
    if (((AbstractPreferences)prefsNode).isRemoved())
    return;
    // Import any preferences at this node
    Element firstXmlKid = (Element) xmlKids.item(0);
    ImportPrefs(prefsNode, firstXmlKid);
    prefsKids = new Preferences[numXmlKids - 1];
    // Get involved children
    for (int i=1; i < numXmlKids; i++) {
    Element xmlKid = (Element) xmlKids.item(i);
    prefsKids[i-1] = prefsNode.node(xmlKid.getAttribute("name"));
    } // unlocked the node
    // import children
    for (int i=1; i < numXmlKids; i++)
    ImportSubtree(prefsKids[i-1], (Element)xmlKids.item(i));
    * Import the preferences described by the specified XML element
    * (a map from a preferences document) into the specified
    * preferences node.
    private static void ImportPrefs(Preferences prefsNode, Element map) {
    NodeList entries = map.getChildNodes();
    for (int i=0, numEntries = entries.getLength(); i < numEntries; i++) {
    Element entry = (Element) entries.item(i);
    prefsNode.put(entry.getAttribute("key"),
    entry.getAttribute("value"));
    * Export the specified Map<String,String> to a map document on
    * the specified OutputStream as per the prefs DTD. This is used
    * as the internal (undocumented) format for FileSystemPrefs.
    * @throws IOException if writing to the specified output stream
    * results in an <tt>IOException</tt>.
    static void exportMap(OutputStream os, Map map) throws IOException {
    XmlDocument doc = new XmlDocument();
    doc.setDoctype(null, PREFS_DTD_URI, null);
    Element xmlMap = (Element) doc.appendChild(doc.createElement("map"));
    xmlMap.setAttribute("MAP_XML_VERSION", MAP_XML_VERSION);
    for (Iterator i = map.entrySet().iterator(); i.hasNext(); ) {
    Map.Entry e = (Map.Entry) i.next();
    Element xe = (Element)
    xmlMap.appendChild(doc.createElement("entry"));
    xe.setAttribute("key", (String) e.getKey());
    xe.setAttribute("value", (String) e.getValue());
    doc.write(os);
    * Import Map from the specified input stream, which is assumed
    * to contain a map document as per the prefs DTD. This is used
    * as the internal (undocumented) format for FileSystemPrefs. The
    * key-value pairs specified in the XML document will be put into
    * the specified Map. (If this Map is empty, it will contain exactly
    * the key-value pairs int the XML-document when this method returns.)
    * @throws IOException if reading from the specified output stream
    * results in an <tt>IOException</tt>.
    * @throws InvalidPreferencesFormatException Data on input stream does not
    * constitute a valid XML document with the mandated document type.
    static void importMap(InputStream is, Map m)
    throws IOException, InvalidPreferencesFormatException
    try {
    Document doc = load(is);
    Element xmlMap = (Element) doc.getChildNodes().item(1);
    // check version
    String mapVersion = xmlMap.getAttribute("MAP_XML_VERSION");
    if (mapVersion.compareTo(MAP_XML_VERSION) > 0)
    throw new InvalidPreferencesFormatException(
    "Preferences map file format version " + mapVersion +
    " is not supported. This java installation can read" +
    " versions " + MAP_XML_VERSION + " or older. You may need" +
    " to install a newer version of JDK.");
    NodeList entries = xmlMap.getChildNodes();
    for (int i=0, numEntries=entries.getLength(); i<numEntries; i++) {
    Element entry = (Element) entries.item(i);
    m.put(entry.getAttribute("key"), entry.getAttribute("value"));
    } catch(SAXException e) {
    throw new InvalidPreferencesFormatException(e);
    private static class Resolver implements EntityResolver {
    public InputSource resolveEntity(String pid, String sid)
    throws SAXException
    if (sid.equals(PREFS_DTD_URI)) {
    InputSource is;
    is = new InputSource(new StringReader(PREFS_DTD));
    is.setSystemId(PREFS_DTD_URI);
    return is;
    throw new SAXException("Invalid system identifier: " + sid);
    private static class EH implements ErrorHandler {
    public void error(SAXParseException x) throws SAXException {
    throw x;
    public void fatalError(SAXParseException x) throws SAXException {
    throw x;
    public void warning(SAXParseException x) throws SAXException {
    throw x;

  • Setting logging.config.class via Preferences API

    The Javadoc for LogManager says:
    In addition, the LogManager uses two optional system properties that allow more control over reading the initial configuration:
    * "java.util.logging.config.class"
    * "java.util.logging.config.file"
    These two properties may be set via the Preferences API, or as command line property definitions to the "java" command, or as system property definitions passed to JNI_CreateJavaVM.
    http://java.sun.com/j2se/1.4/docs/api/java/util/logging/LogManager.html
    So, how can I set the "java.util.logging.config.class" system property via the Preferences API? How can I set any system property via the Preferences API? I think this is a documentation bug, but I would like to know how to do it, otherwise.
    http://java.sun.com/j2se/1.4/docs/api/java/util/prefs/Preferences.html

    I don't know why I couldn't find it when I looked before,
    but it is a filed bug.
    http://developer.java.sun.com/developer/bugParade/bugs/4691587.html
    This help me find a work-around.
    http://developer.java.sun.com/developer/bugParade/bugs/4506094.html

  • Preference API in windows when registry is blocked

    Hi All,
    I have a requirement to save the user preferences of a swing based medical application at the user end and the Preferences API seemed clean to fit the bill.
    However after going live, we found that some workstations have been denied user access to the registry. In such cases the entire application seems to fail. Please suggest some way out. It is exteremely important as we have already gone live with the software in place and some doctors may not be able to use the system. For the time being I could start using a properties file as a back up and storing using the random-access file api. Please help......
    Thanks in advance,
    Zeus

    A cursory look at the Preferences.java source leads me to believe that it should be possible to change where the values are stored. This code interrogates the os.name and chooses either the Windows Registry or something else (I assume a file it creates.)
    // 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;
    }You should be able to subclass this class and change so that the Registry isn't used.

  • Using the Preferences API

    I've never used this API before, so excuse my ignorance. I have a web application that I have been using a properties file to store base app info, such as the backend database, the url for the ldap, etc. This has been working fine, but after reading about the Preferences API, I thought that this might be the better place to store this info. However, I'm having permission problems that I haven't been able to figure out.
    I've got a development copy of everything on a single computer (using Windows XP), Sun One App Server, and Oracle.
    I created a small test class to see if I could load preferences from an xml file. Here's the class
    package portal.common;
    import java.util.*;
    import java.util.prefs.*;
    import java.io.*;
    import java.lang.*;
    public class PortalPreferences{
         Preferences sysPreferencesRoot;
         public void prefs() throws SecurityException{
    sysPreferencesRoot = Preferences.systemRoot();
         public void uploadPrefs(String file) throws IOException, InvalidPreferencesFormatException{
         FileInputStream fis = new FileInputStream(file);
         RuntimePermission rpermiss = new RuntimePermission("preferences.*");
         Preferences.importPreferences(fis);
         public Preferences getPrefs(){
         return sysPreferencesRoot;
    I then used a jsp to instantiate the class and call the uploadPrefs method. The class instantiates without error, but when I try to load the xml file I get the following error:
    access denied (java.lang.RuntimePermission preferences)
    I've never done anything with the security manager before so I'm not sure how to get around this. I tried creating a RuntimePermission object above, but that didn't work.
    If anyone has any ideas, I'd much appreciate it.

    No, actually I've got the Sun One App server loaded on a desktop I built that I'm using as a test box - its not a server. The Sun server is running fine, as is Oracle. The only problem I'm having is figuring out how to use the Preferences API. Maybe this API isn't the right thing to be using, that's why I'm asking for advice as well as how to get around the security issue that I'm having. My goal is to have application level information that can be stored somewhere other than in a database - this is because one of the pieces of app info is the database that's being used. This app will work with any backend. Currently, this info is stored in a properties file inside the WEB-INF directory. This works fine as is. However, my issue with that is that in order to load the properties file, I've got to have a real drive path. This again isn't that much of an issue except when trying to access from a class that doesn't have the servlet context, however, I am looking for an alternative solution to the properties file. The Preferences seemed like a good solution.

  • Fatal Error: missing resource: java.util.PropertyResourceBundle =Urgent

    Hi all,
    In the JSP ,if I include the statement <%@ page import="jack.samples.*" %>
    it is throwing following error:
    This is the Error Message from the Exception:
         Server caught unhandled exception from servlet [BaseServlet]: Server caught
         unhandled exception from servlet [CategoryDisplay]: Server caught unhandled
         exception from servlet [jsp]: Fatal Error: missing resource: java.util.PropertyResourceBundle
         I am using Websphere 3.5 on Windows NT.
         can somebody please help me what is going wrong here ???I am stopped at
         this problem for last 2 days.
    Thanks
    Jack

    Hi,
    Finally I was able to resolve after adding this jar file to the classfile
    path of the application.
    Now,I am trying to access use linkTable.add(new Item(222,"222","333",12.33)) in JSP.
    where linkTable is a LinkedList.
    It fails giving following error:
    This is the Error Message from the Exception:
    Server caught unhandled exception from servlet [BaseServlet]: Server caught unhandled exception from servlet : Server caught unhandled exception from servlet [jsp]: Compilation of "softproduct.jsp" failed: d:\ibm\WAServer\temp\default_host\WCSServlets\_jameco_2F_softproduct_2E_jsp_jsp_2.java:824: No constructor matching Item&#40;int, java.lang.String, java.lang.String, double&#41; found in class jack.samples.Item. linkTab.add&#40;new Item&#40;2222,"222","222",22.33&#41;&#41;&#59; ^ Note: d:\ibm\WAServer\temp\default_host\WCSServlets\_jameco_2F_softproduct_2E_jsp_jsp_2.java uses or overrides a deprecated API. Recompile with "-deprecation" for details. 1 error, 1 warning
    I dont understand why it is failing to add Item object to LinkedList.
    can somebody help me in the forum in this regard.
    Thanks
    Jack

  • Java.util.PropertyPermission...not granted to ProtectionDomain(Stored Proc)

    I'm trying to develop a java stored procedure on Oracle 10.1.2 that makes use of many other libraries, (Axis, WSIF, custom libs), and I'm stuck on this permissions error. I've loaded all of the libs into the same schema under the same user, (with JAVA_ADMIN), and several other privileges. I loaded the files using the following command, "loadjava -verbose -debug -recursivejars -genmissing -resolve -time -fileout loadJava.log -user {userID}/{pwd}@{SID} someJar.jar". The error occurs when a call to WSIFProperties.getProperty attempts to access the org.apache.wsif.mapper or org.apache.wsif.mappingconvention properties.
    In a normal java2 environment, I'd simply edit the java.policy file to provide permissions to the codebase (file:/C:/spi4j2.5.4_J2ee1.4/coreLib/fsgWsif1.1.jar). Since Oracle doesn't have ProtectionDomains, if I add read permissions for those properties using the following command, "call dbms_java.grant_permission( 'SCHEMANAME', 'SYS:java.util.PropertyPermission', 'org.apache.wsif.mapper', 'read' )", it seems as if all of the other classes in the schema should be able to read the property, right? It appears the logfile dump below is showing the permissions that the classloader recognizes. Where did he get those? If they came from the DBA_JAVA_POLICY view, then why can't it pick up on the fact that I've granted read permission to the property it's trying to read? When I tried loading the classes without using the -recursivejars option, I got all kinds of ClassDefNotFound errors and couldn't even start the program, (I guess because it'd loaded the other jars as resources instead of unpacking the classes, the resolver couldn't look into the jars and locate the classes that it needed). The program works just fine outside of the database, (even without me adding read permissions for the codebase to access the properties in the java.policy file). Any help would be greatly appreciated. Thanks in advance.
    Error shown below:
    [2008-03-20 18:23:18.144] [DEBUG] [Root Thread] [org.apache.wsif.*][org.apache.wsif.logging.Trc] [traceIt] [Trc.java:1308] EVENT WSIFMapperFactory.newMapper Caught and handled throwable: java.security.AccessControlException: the Permission (java.util.PropertyPermission org.apache.wsif.mapper read) has not been granted to ProtectionDomain (file:/C:/spi4j2.5.4_J2ee1.4/coreLib/fsgWsif1.1.jar <no certificates>)
    com.fds.classloader.ParentLastUrlClassLoader@e87f10c1
    <no principals>
    java.security.Permissions@c5dd7492 (
    (java.io.FilePermission \C:\spi4j2.5.4_J2ee1.4\coreLib\fsgWsif1.1.jar read)
    (java.net.SocketPermission localhost:1024- listen,resolve)
    (java.util.PropertyPermission java.version read)
    (java.util.PropertyPermission java.vm.name read)
    (java.util.PropertyPermission java.vm.vendor read)
    (java.util.PropertyPermission os.name read)
    (java.util.PropertyPermission java.vendor.url read)
    (java.util.PropertyPermission java.vm.specification.vendor read)
    (java.util.PropertyPermission java.specification.vendor read)
    (java.util.PropertyPermission os.version read)
    (java.util.PropertyPermission java.specification.name read)
    (java.util.PropertyPermission java.class.version read)
    (java.util.PropertyPermission file.separator read)
    (java.util.PropertyPermission java.vm.version read)
    (java.util.PropertyPermission os.arch read)
    (java.util.PropertyPermission java.vm.specification.name read)
    (java.util.PropertyPermission java.vm.specification.version read)
    (java.util.PropertyPermission java.specification.version read)
    (java.util.PropertyPermission java.vendor read)
    (java.util.PropertyPermission path.separator read)
    (java.util.PropertyPermission line.separator read)
    )

    hi rzander,
    I am in a situation similar to your :
    {color:#ff0000}Caused by: java.security.AccessControlException: the Permission (java.io.FilePermission /home/neogeo/Java_Resources.jrxml read) has not been granted to ProtectionDomain (file:/home/neogeo/lib/jasperreports-3.0.0.jar &lt;no signer certificates&gt;)
    AppClassLoader: file:/home/neogeo/lib/xml-apis.jar file:/home/neogeo/lib/jpa.jar file:/home/neogeo/lib/jdt-compiler-3.1.1.jar file:/home/neogeo/lib/png-encoder-1.5.jar file:/home/neogeo/lib/ant-1.5.1.jar file:/home/neogeo/lib/jaxen-1.1.1.jar file:/home/neogeo/lib/mondrian-2.3.2.8944.jar file:/home/neogeo/lib/commons-javaflow-20060411.jar file:/home/neogeo/lib/batik-bridge.jar file:/home/neogeo/lib/antlr-2.7.5.jar file:/home/neogeo/lib/batik-parser.jar file:/home/neogeo/lib/hibernate3.jar file:/home/neogeo/lib/batik-ext.jar file:/home/neogeo/lib/commons-logging-1.0.2.jar file:/home/neogeo/lib/jasperreports-3.0.0.jar file:/home/neogeo/lib/batik-svggen.jar file:/home/neogeo/lib/batik-xml.jar file:/home/neogeo/lib/xml-apis-ext.jar file:/home/neogeo/lib/batik-dom.jar file:/home/neogeo/lib/jakarta-bcel-20050813.jar file:/home/neogeo/lib/servlet.jar file:/home/neogeo/lib/hsqldb-1.7.1.jar file:/home/neogeo/lib/batik-gvt.jar file:/home/neogeo/lib/batik-svg-dom.jar file:/home/neogeo/lib/jxl-2.6.jar file:/home/neogeo/lib/groovy-all-1.5.5.jar file:/home/neogeo/lib/xercesImpl.jar file:/home/neogeo/lib/batik-awt-util.jar file:/home/neogeo/lib/bsh-2.0b4.jar file:/home/neogeo/lib/commons-digester-1.7.jar file:/home/neogeo/lib/batik-css.jar file:/home/neogeo/lib/commons-logging-api-1.0.2.jar file:/home/neogeo/lib/jfreechart-1.0.0.jar file:/home/neogeo/lib/itext-1.3.1.jar file:/home/neogeo/lib/poi-3.0.1-FINAL-20070705.jar file:/home/neogeo/lib/batik-util.jar file:/home/neogeo/lib/commons-beanutils-1.7.jar file:/home/neogeo/lib/jcommon-1.0.0.jar file:/home/neogeo/lib/saaj-api-1.3.jar file:/home/neogeo/lib/batik-script.jar file:/home/neogeo/lib/xalan.jar file:/home/neogeo/lib/batik-anim.jar file:/home/neogeo/lib/commons-collections-2.1.jar
    &lt;no principals&gt;
    java.security.Permissions@1aebb385 (
    (java.io.FilePermission /home/neogeo/lib/jasperreports-3.0.0.jar read)
    (java.util.PropertyPermission user.language write)
    (java.util.PropertyPermission * read)
    (java.lang.RuntimePermission modifyThreadGroup)
    (java.lang.RuntimePermission createSecurityManager)
    (java.lang.RuntimePermission modifyThread)
    (java.lang.RuntimePermission preferences)
    (java.lang.RuntimePermission exitVM)
    (oracle.aurora.security.JServerPermission LoadClassInPackage.*)
    {color}
    {color:#ff0000}
    at java.security.AccessControlContext.checkPermission(AccessControlContext.java)
    at java.security.AccessController.checkPermission(AccessController.java)
    at java.lang.SecurityManager.checkPermission(SecurityManager.java)
    at oracle.aurora.rdbms.SecurityManagerImpl.checkPermission(SecurityManagerImpl.java)
    at java.lang.SecurityManager.checkRead(SecurityManager.java)
    at java.io.FileInputStream.&lt;init&gt;(FileInputStream.java)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:167)
    at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:152)
    at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:150)
    ... 9 more{color}
    I followed your help creating the file  "ORACLE_HOME/javavm/lib/security / java.policy", but I still get the same exception.
    Please, can you post the contents of your java.policy to understand how  you set the permissions ?
    Edited by: NeOGeO on 11-nov-2008 6.43

  • Preferences API On 1.3

    Hi, we are restricted to jdk 1.3 for a few months yet, but
    I'd like to use the preferences api for a new project. Is
    it possible to install the preferences packages on 1.3?
    Bill.

    You may run into class mismatches and such.
    You can also take a look at the source code to find out if there are other dependencies... but if I were you, I'd keep it clean. Mixing and matching packages will only muddy things up ... and if you happen to write work-arounds to make the java.util.pref package work ... if may effect your eventual migration to 1.4

  • Preferences API storage

    (I'm posting this question here because noone in the beginners forum could answer me)
    I'm using the new (since j2sdk 1.4) Preferences API to store a small number of prefs. I use user nodes (as opposed tot system nodes), and in Windows everything works correct, but linux users get problems with the backingstore (BackingStoreException). The root user does not have this problem.
    The good point about the preferences also seems a bad point: I don't know where the data is stored, so I can't advise on setting a certain directory readable/writable.
    Preferences prefs = Preferences.userNodeForPackage(auteurstool.Auteursomgeving.class);
    boolean someChoice = prefs.getBoolean("some choice", true);And I'm getting these errors:
    13-nov-2002 16:44:59 java.util.prefs.FileSystemPreferences syncWorld
    WARNING: Couldn't flush user
    prefs: java.util.prefs.BackingStoreException: java.lang.ClassCastException:
    org.apache.xerces.dom.DeferredCommentImpl
    13-nov-2002 16:45:00 java.util.prefs.FileSystemPreferences
    checkLockFile0ErrorCode
    WARNING: Could not lock System prefs.Unix error code 135399620.
    13-nov-2002 16:45:00 java.util.prefs.FileSystemPreferences syncWorld
    WARNING: Couldn't flush system
    prefs: java.util.prefs.BackingStoreException: Couldn't get file lock.
    java.util.prefs.BackingStoreException: Couldn't get file lock.
    Any suggestions?

    There was an answer in the forum
    http://forum.java.sun.com/thread.jsp?forum=32&thread=325325
    that was also quite interesting.

  • Cannot extract Zip file with Winzip after zipping with java.util.zip

    Hi all,
    I write a class for zip and unzip the text files together which can be zip and unzip successfully with Java platform. However, I cannot extract the zip file with Winzip or even WinRAR after zipping with Java platform.
    Please help to comment, thanks~
    Below is the code:
    =====================================================================
    package myapp.util;
    import java.io.* ;
    import java.util.TreeMap ;
    import java.util.zip.* ;
    import myapp.exception.UserException ;
    public class CompressionUtil {
      public CompressionUtil() {
        super() ;
      public void createZip(String zipName, String fileName)
          throws ZipException, FileNotFoundException, IOException, UserException {
        FileOutputStream fos = null ;
        BufferedOutputStream bos = null ;
        ZipOutputStream zos = null ;
        File file = null ;
        try {
          file = new File(zipName) ; //new zip file
          if (file.isDirectory()) //check if it is a directory
         throw new UserException("Invalid zip file ["+zipName+"]") ;
          if (file.exists() && !file.canWrite()) //check if it is readonly
         throw new UserException("Zip file is ReadOnly ["+zipName+"]") ;
          if (file.exists()) //overwrite the existing file
         file.delete();
          file.createNewFile();
          //instantiate the ZipOutputStream
          fos = new FileOutputStream(file) ;
          bos = new BufferedOutputStream(fos) ;
          zos = new ZipOutputStream(bos) ;
          this.writeZipFileEntry(zos, fileName); //call to write the file into the zip
          zos.finish() ;
        catch (ZipException ze) {
          throw ze ;
        catch (FileNotFoundException fnfe) {
          throw fnfe ;
        catch (IOException ioe) {
          throw ioe ;
        catch (UserException ue) {
          throw ue ;
        finally {
          //close all the stream and file
          if (fos != null)
         fos.close() ;
          if (bos != null)
         bos.close();
          if (zos != null)
         zos.close();
          if (file != null)
         file = null ;
        }//end of try-catch-finally
      private void writeZipFileEntry(ZipOutputStream zos, String fileName)
          throws ZipException, FileNotFoundException, IOException, UserException {
        BufferedInputStream bis = null ;
        File file = null ;
        ZipEntry zentry = null ;
        byte[] bArray = null ;
        try {
          file = new File(fileName) ; //instantiate the file
          if (!file.exists()) //check if the file is not exist
         throw new UserException("No such file ["+fileName+"]") ;
          if (file.isDirectory()) //check if the file is a directory
         throw new UserException("Invalid file ["+fileName+"]") ;
          //instantiate the BufferedInputStream
          bis = new BufferedInputStream(new FileInputStream(file)) ;
          //Get the content of the file and put into the byte[]
          int size = (int) file.length();
          if (size == -1)
         throw new UserException("Cannot determine the file size [" +fileName + "]");
          bArray = new byte[(int) size];
          int rb = 0;
          int chunk = 0;
          while (((int) size - rb) > 0) {
         chunk = bis.read(bArray, rb, (int) size - rb);
         if (chunk == -1)
           break;
         rb += chunk;
          }//end of while (((int)size - rb) > 0)
          //instantiate the CRC32
          CRC32 crc = new CRC32() ;
          crc.update(bArray, 0, size);
          //instantiate the ZipEntry
          zentry = new ZipEntry(fileName) ;
          zentry.setMethod(ZipEntry.STORED) ;
          zentry.setSize(size);
          zentry.setCrc(crc.getValue());
          //write all the info to the ZipOutputStream
          zos.putNextEntry(zentry);
          zos.write(bArray, 0, size);
          zos.closeEntry();
        catch (ZipException ze) {
          throw ze ;
        catch (FileNotFoundException fnfe) {
          throw fnfe ;
        catch (IOException ioe) {
          throw ioe ;
        catch (UserException ue) {
          throw ue ;
        finally {
          //close all the stream and file
          if (bis != null)
         bis.close();
          if (file != null)
         file = null ;
        }//end of try-catch-finally
    }

    Tried~
    The problem is still here~ >___<
    Anyway, thanks for information sharing~
    The message is:
    Cannot open file: it does not appear to be a valid archive.
    If you downloaded this file, try downloading the file again.
    The problem may be here:
    if (fos != null)
    fos.close() ;
    if (bos != null)
    bos.close();
    if (zos != null)
    zos.close();
    if (file != null)
    file = null ;
    The fos is closed before bos so the last buffer is not
    saved.
    zos.close() is enough.

Maybe you are looking for

  • File does not exist: /www/public_html/null, referer:  - error in log file from IE8 and IE9

    I just updated an existing slide show that was created several months back. Since loading my new set of files to our web server, we keep getting the following error in our server log files when someone loads our page in IE8 and IE9: File does not exi

  • Text Message # displays instead of Contact

    Text message contact name is not displaying... only their number.  Despite having the contact name and number in "contacts".  Also, i have confirmed the number is the exact same in contacts book as it is in the received text message.  I am on Sprint

  • What software do I need to receive Podcasts?

    This is my first interaction with this community, so let me say Good Morning. My brother has offered to set me up with podcasts from my favorite radio show, if I can figure out how to get them. Is there special software I need to download? Where do I

  • Dynamic client invocation (6.1) question

    Hi I am invoking an external webservice using a WL6.1 based client. Since I have the WSDL, I use WebSeviceProxy.getServiceAt(wsdl) to get the proxy based on the given wsdl URL. The external webservice has the following signature : void notification(M

  • Files that contain folder structures (i.e. Quicken) general questions

    My iMac hard drive just recently gave out. I've been backing up with Mozy, and I thought that was great. Until I tried to restore the Quicken file. This file is actually a directory structure inside. Unfortunately, Mozy treated this file as a folder,