src/share/classes/java/util/prefs/XmlSupport.java
changeset 1258 6dcea85ad8ba
child 2395 00cd9dc3c2b5
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/share/classes/java/util/prefs/XmlSupport.java	Mon Jun 22 18:07:11 2009 +0200
     1.3 @@ -0,0 +1,421 @@
     1.4 +/*
     1.5 + * Copyright 2002-2006 Sun Microsystems, Inc.  All Rights Reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Sun designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Sun in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    1.25 + * CA 95054 USA or visit www.sun.com if you need additional information or
    1.26 + * have any questions.
    1.27 + */
    1.28 +
    1.29 +package java.util.prefs;
    1.30 +
    1.31 +import java.util.*;
    1.32 +import java.io.*;
    1.33 +import javax.xml.parsers.*;
    1.34 +import javax.xml.transform.*;
    1.35 +import javax.xml.transform.dom.*;
    1.36 +import javax.xml.transform.stream.*;
    1.37 +import org.xml.sax.*;
    1.38 +import org.w3c.dom.*;
    1.39 +
    1.40 +/**
    1.41 + * XML Support for java.util.prefs. Methods to import and export preference
    1.42 + * nodes and subtrees.
    1.43 + *
    1.44 + * @author  Josh Bloch and Mark Reinhold
    1.45 + * @see     Preferences
    1.46 + * @since   1.4
    1.47 + */
    1.48 +class XmlSupport {
    1.49 +    // The required DTD URI for exported preferences
    1.50 +    private static final String PREFS_DTD_URI =
    1.51 +        "http://java.sun.com/dtd/preferences.dtd";
    1.52 +
    1.53 +    // The actual DTD corresponding to the URI
    1.54 +    private static final String PREFS_DTD =
    1.55 +        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
    1.56 +
    1.57 +        "<!-- DTD for preferences -->"               +
    1.58 +
    1.59 +        "<!ELEMENT preferences (root) >"             +
    1.60 +        "<!ATTLIST preferences"                      +
    1.61 +        " EXTERNAL_XML_VERSION CDATA \"0.0\"  >"     +
    1.62 +
    1.63 +        "<!ELEMENT root (map, node*) >"              +
    1.64 +        "<!ATTLIST root"                             +
    1.65 +        "          type (system|user) #REQUIRED >"   +
    1.66 +
    1.67 +        "<!ELEMENT node (map, node*) >"              +
    1.68 +        "<!ATTLIST node"                             +
    1.69 +        "          name CDATA #REQUIRED >"           +
    1.70 +
    1.71 +        "<!ELEMENT map (entry*) >"                   +
    1.72 +        "<!ATTLIST map"                              +
    1.73 +        "  MAP_XML_VERSION CDATA \"0.0\"  >"         +
    1.74 +        "<!ELEMENT entry EMPTY >"                    +
    1.75 +        "<!ATTLIST entry"                            +
    1.76 +        "          key CDATA #REQUIRED"              +
    1.77 +        "          value CDATA #REQUIRED >"          ;
    1.78 +    /**
    1.79 +     * Version number for the format exported preferences files.
    1.80 +     */
    1.81 +    private static final String EXTERNAL_XML_VERSION = "1.0";
    1.82 +
    1.83 +    /*
    1.84 +     * Version number for the internal map files.
    1.85 +     */
    1.86 +    private static final String MAP_XML_VERSION = "1.0";
    1.87 +
    1.88 +    /**
    1.89 +     * Export the specified preferences node and, if subTree is true, all
    1.90 +     * subnodes, to the specified output stream.  Preferences are exported as
    1.91 +     * an XML document conforming to the definition in the Preferences spec.
    1.92 +     *
    1.93 +     * @throws IOException if writing to the specified output stream
    1.94 +     *         results in an <tt>IOException</tt>.
    1.95 +     * @throws BackingStoreException if preference data cannot be read from
    1.96 +     *         backing store.
    1.97 +     * @throws IllegalStateException if this node (or an ancestor) has been
    1.98 +     *         removed with the {@link #removeNode()} method.
    1.99 +     */
   1.100 +    static void export(OutputStream os, final Preferences p, boolean subTree)
   1.101 +        throws IOException, BackingStoreException {
   1.102 +        if (((AbstractPreferences)p).isRemoved())
   1.103 +            throw new IllegalStateException("Node has been removed");
   1.104 +        Document doc = createPrefsDoc("preferences");
   1.105 +        Element preferences =  doc.getDocumentElement() ;
   1.106 +        preferences.setAttribute("EXTERNAL_XML_VERSION", EXTERNAL_XML_VERSION);
   1.107 +        Element xmlRoot =  (Element)
   1.108 +        preferences.appendChild(doc.createElement("root"));
   1.109 +        xmlRoot.setAttribute("type", (p.isUserNode() ? "user" : "system"));
   1.110 +
   1.111 +        // Get bottom-up list of nodes from p to root, excluding root
   1.112 +        List ancestors = new ArrayList();
   1.113 +
   1.114 +        for (Preferences kid = p, dad = kid.parent(); dad != null;
   1.115 +                                   kid = dad, dad = kid.parent()) {
   1.116 +            ancestors.add(kid);
   1.117 +        }
   1.118 +        Element e = xmlRoot;
   1.119 +        for (int i=ancestors.size()-1; i >= 0; i--) {
   1.120 +            e.appendChild(doc.createElement("map"));
   1.121 +            e = (Element) e.appendChild(doc.createElement("node"));
   1.122 +            e.setAttribute("name", ((Preferences)ancestors.get(i)).name());
   1.123 +        }
   1.124 +        putPreferencesInXml(e, doc, p, subTree);
   1.125 +
   1.126 +        writeDoc(doc, os);
   1.127 +    }
   1.128 +
   1.129 +    /**
   1.130 +     * Put the preferences in the specified Preferences node into the
   1.131 +     * specified XML element which is assumed to represent a node
   1.132 +     * in the specified XML document which is assumed to conform to
   1.133 +     * PREFS_DTD.  If subTree is true, create children of the specified
   1.134 +     * XML node conforming to all of the children of the specified
   1.135 +     * Preferences node and recurse.
   1.136 +     *
   1.137 +     * @throws BackingStoreException if it is not possible to read
   1.138 +     *         the preferences or children out of the specified
   1.139 +     *         preferences node.
   1.140 +     */
   1.141 +    private static void putPreferencesInXml(Element elt, Document doc,
   1.142 +               Preferences prefs, boolean subTree) throws BackingStoreException
   1.143 +    {
   1.144 +        Preferences[] kidsCopy = null;
   1.145 +        String[] kidNames = null;
   1.146 +
   1.147 +        // Node is locked to export its contents and get a
   1.148 +        // copy of children, then lock is released,
   1.149 +        // and, if subTree = true, recursive calls are made on children
   1.150 +        synchronized (((AbstractPreferences)prefs).lock) {
   1.151 +            // Check if this node was concurrently removed. If yes
   1.152 +            // remove it from XML Document and return.
   1.153 +            if (((AbstractPreferences)prefs).isRemoved()) {
   1.154 +                elt.getParentNode().removeChild(elt);
   1.155 +                return;
   1.156 +            }
   1.157 +            // Put map in xml element
   1.158 +            String[] keys = prefs.keys();
   1.159 +            Element map = (Element) elt.appendChild(doc.createElement("map"));
   1.160 +            for (int i=0; i<keys.length; i++) {
   1.161 +                Element entry = (Element)
   1.162 +                    map.appendChild(doc.createElement("entry"));
   1.163 +                entry.setAttribute("key", keys[i]);
   1.164 +                // NEXT STATEMENT THROWS NULL PTR EXC INSTEAD OF ASSERT FAIL
   1.165 +                entry.setAttribute("value", prefs.get(keys[i], null));
   1.166 +            }
   1.167 +            // Recurse if appropriate
   1.168 +            if (subTree) {
   1.169 +                /* Get a copy of kids while lock is held */
   1.170 +                kidNames = prefs.childrenNames();
   1.171 +                kidsCopy = new Preferences[kidNames.length];
   1.172 +                for (int i = 0; i <  kidNames.length; i++)
   1.173 +                    kidsCopy[i] = prefs.node(kidNames[i]);
   1.174 +            }
   1.175 +            // release lock
   1.176 +        }
   1.177 +
   1.178 +        if (subTree) {
   1.179 +            for (int i=0; i < kidNames.length; i++) {
   1.180 +                Element xmlKid = (Element)
   1.181 +                    elt.appendChild(doc.createElement("node"));
   1.182 +                xmlKid.setAttribute("name", kidNames[i]);
   1.183 +                putPreferencesInXml(xmlKid, doc, kidsCopy[i], subTree);
   1.184 +            }
   1.185 +        }
   1.186 +    }
   1.187 +
   1.188 +    /**
   1.189 +     * Import preferences from the specified input stream, which is assumed
   1.190 +     * to contain an XML document in the format described in the Preferences
   1.191 +     * spec.
   1.192 +     *
   1.193 +     * @throws IOException if reading from the specified output stream
   1.194 +     *         results in an <tt>IOException</tt>.
   1.195 +     * @throws InvalidPreferencesFormatException Data on input stream does not
   1.196 +     *         constitute a valid XML document with the mandated document type.
   1.197 +     */
   1.198 +    static void importPreferences(InputStream is)
   1.199 +        throws IOException, InvalidPreferencesFormatException
   1.200 +    {
   1.201 +        try {
   1.202 +            Document doc = loadPrefsDoc(is);
   1.203 +            String xmlVersion =
   1.204 +                doc.getDocumentElement().getAttribute("EXTERNAL_XML_VERSION");
   1.205 +            if (xmlVersion.compareTo(EXTERNAL_XML_VERSION) > 0)
   1.206 +                throw new InvalidPreferencesFormatException(
   1.207 +                "Exported preferences file format version " + xmlVersion +
   1.208 +                " is not supported. This java installation can read" +
   1.209 +                " versions " + EXTERNAL_XML_VERSION + " or older. You may need" +
   1.210 +                " to install a newer version of JDK.");
   1.211 +
   1.212 +            Element xmlRoot = (Element) doc.getDocumentElement().
   1.213 +                                               getChildNodes().item(0);
   1.214 +            Preferences prefsRoot =
   1.215 +                (xmlRoot.getAttribute("type").equals("user") ?
   1.216 +                            Preferences.userRoot() : Preferences.systemRoot());
   1.217 +            ImportSubtree(prefsRoot, xmlRoot);
   1.218 +        } catch(SAXException e) {
   1.219 +            throw new InvalidPreferencesFormatException(e);
   1.220 +        }
   1.221 +    }
   1.222 +
   1.223 +    /**
   1.224 +     * Create a new prefs XML document.
   1.225 +     */
   1.226 +    private static Document createPrefsDoc( String qname ) {
   1.227 +        try {
   1.228 +            DOMImplementation di = DocumentBuilderFactory.newInstance().
   1.229 +                newDocumentBuilder().getDOMImplementation();
   1.230 +            DocumentType dt = di.createDocumentType(qname, null, PREFS_DTD_URI);
   1.231 +            return di.createDocument(null, qname, dt);
   1.232 +        } catch(ParserConfigurationException e) {
   1.233 +            throw new AssertionError(e);
   1.234 +        }
   1.235 +    }
   1.236 +
   1.237 +    /**
   1.238 +     * Load an XML document from specified input stream, which must
   1.239 +     * have the requisite DTD URI.
   1.240 +     */
   1.241 +    private static Document loadPrefsDoc(InputStream in)
   1.242 +        throws SAXException, IOException
   1.243 +    {
   1.244 +        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   1.245 +        dbf.setIgnoringElementContentWhitespace(true);
   1.246 +        dbf.setValidating(true);
   1.247 +        dbf.setCoalescing(true);
   1.248 +        dbf.setIgnoringComments(true);
   1.249 +        try {
   1.250 +            DocumentBuilder db = dbf.newDocumentBuilder();
   1.251 +            db.setEntityResolver(new Resolver());
   1.252 +            db.setErrorHandler(new EH());
   1.253 +            return db.parse(new InputSource(in));
   1.254 +        } catch (ParserConfigurationException e) {
   1.255 +            throw new AssertionError(e);
   1.256 +        }
   1.257 +    }
   1.258 +
   1.259 +    /**
   1.260 +     * Write XML document to the specified output stream.
   1.261 +     */
   1.262 +    private static final void writeDoc(Document doc, OutputStream out)
   1.263 +        throws IOException
   1.264 +    {
   1.265 +        try {
   1.266 +            TransformerFactory tf = TransformerFactory.newInstance();
   1.267 +            try {
   1.268 +                tf.setAttribute("indent-number", new Integer(2));
   1.269 +            } catch (IllegalArgumentException iae) {
   1.270 +                //Ignore the IAE. Should not fail the writeout even the
   1.271 +                //transformer provider does not support "indent-number".
   1.272 +            }
   1.273 +            Transformer t = tf.newTransformer();
   1.274 +            t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
   1.275 +            t.setOutputProperty(OutputKeys.INDENT, "yes");
   1.276 +            //Transformer resets the "indent" info if the "result" is a StreamResult with
   1.277 +            //an OutputStream object embedded, creating a Writer object on top of that
   1.278 +            //OutputStream object however works.
   1.279 +            t.transform(new DOMSource(doc),
   1.280 +                        new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));
   1.281 +        } catch(TransformerException e) {
   1.282 +            throw new AssertionError(e);
   1.283 +        }
   1.284 +    }
   1.285 +
   1.286 +    /**
   1.287 +     * Recursively traverse the specified preferences node and store
   1.288 +     * the described preferences into the system or current user
   1.289 +     * preferences tree, as appropriate.
   1.290 +     */
   1.291 +    private static void ImportSubtree(Preferences prefsNode, Element xmlNode) {
   1.292 +        NodeList xmlKids = xmlNode.getChildNodes();
   1.293 +        int numXmlKids = xmlKids.getLength();
   1.294 +        /*
   1.295 +         * We first lock the node, import its contents and get
   1.296 +         * child nodes. Then we unlock the node and go to children
   1.297 +         * Since some of the children might have been concurrently
   1.298 +         * deleted we check for this.
   1.299 +         */
   1.300 +        Preferences[] prefsKids;
   1.301 +        /* Lock the node */
   1.302 +        synchronized (((AbstractPreferences)prefsNode).lock) {
   1.303 +            //If removed, return silently
   1.304 +            if (((AbstractPreferences)prefsNode).isRemoved())
   1.305 +                return;
   1.306 +
   1.307 +            // Import any preferences at this node
   1.308 +            Element firstXmlKid = (Element) xmlKids.item(0);
   1.309 +            ImportPrefs(prefsNode, firstXmlKid);
   1.310 +            prefsKids = new Preferences[numXmlKids - 1];
   1.311 +
   1.312 +            // Get involved children
   1.313 +            for (int i=1; i < numXmlKids; i++) {
   1.314 +                Element xmlKid = (Element) xmlKids.item(i);
   1.315 +                prefsKids[i-1] = prefsNode.node(xmlKid.getAttribute("name"));
   1.316 +            }
   1.317 +        } // unlocked the node
   1.318 +        // import children
   1.319 +        for (int i=1; i < numXmlKids; i++)
   1.320 +            ImportSubtree(prefsKids[i-1], (Element)xmlKids.item(i));
   1.321 +    }
   1.322 +
   1.323 +    /**
   1.324 +     * Import the preferences described by the specified XML element
   1.325 +     * (a map from a preferences document) into the specified
   1.326 +     * preferences node.
   1.327 +     */
   1.328 +    private static void ImportPrefs(Preferences prefsNode, Element map) {
   1.329 +        NodeList entries = map.getChildNodes();
   1.330 +        for (int i=0, numEntries = entries.getLength(); i < numEntries; i++) {
   1.331 +            Element entry = (Element) entries.item(i);
   1.332 +            prefsNode.put(entry.getAttribute("key"),
   1.333 +                          entry.getAttribute("value"));
   1.334 +        }
   1.335 +    }
   1.336 +
   1.337 +    /**
   1.338 +     * Export the specified Map<String,String> to a map document on
   1.339 +     * the specified OutputStream as per the prefs DTD.  This is used
   1.340 +     * as the internal (undocumented) format for FileSystemPrefs.
   1.341 +     *
   1.342 +     * @throws IOException if writing to the specified output stream
   1.343 +     *         results in an <tt>IOException</tt>.
   1.344 +     */
   1.345 +    static void exportMap(OutputStream os, Map map) throws IOException {
   1.346 +        Document doc = createPrefsDoc("map");
   1.347 +        Element xmlMap = doc.getDocumentElement( ) ;
   1.348 +        xmlMap.setAttribute("MAP_XML_VERSION", MAP_XML_VERSION);
   1.349 +
   1.350 +        for (Iterator i = map.entrySet().iterator(); i.hasNext(); ) {
   1.351 +            Map.Entry e = (Map.Entry) i.next();
   1.352 +            Element xe = (Element)
   1.353 +                xmlMap.appendChild(doc.createElement("entry"));
   1.354 +            xe.setAttribute("key",   (String) e.getKey());
   1.355 +            xe.setAttribute("value", (String) e.getValue());
   1.356 +        }
   1.357 +
   1.358 +        writeDoc(doc, os);
   1.359 +    }
   1.360 +
   1.361 +    /**
   1.362 +     * Import Map from the specified input stream, which is assumed
   1.363 +     * to contain a map document as per the prefs DTD.  This is used
   1.364 +     * as the internal (undocumented) format for FileSystemPrefs.  The
   1.365 +     * key-value pairs specified in the XML document will be put into
   1.366 +     * the specified Map.  (If this Map is empty, it will contain exactly
   1.367 +     * the key-value pairs int the XML-document when this method returns.)
   1.368 +     *
   1.369 +     * @throws IOException if reading from the specified output stream
   1.370 +     *         results in an <tt>IOException</tt>.
   1.371 +     * @throws InvalidPreferencesFormatException Data on input stream does not
   1.372 +     *         constitute a valid XML document with the mandated document type.
   1.373 +     */
   1.374 +    static void importMap(InputStream is, Map m)
   1.375 +        throws IOException, InvalidPreferencesFormatException
   1.376 +    {
   1.377 +        try {
   1.378 +            Document doc = loadPrefsDoc(is);
   1.379 +            Element xmlMap = doc.getDocumentElement();
   1.380 +            // check version
   1.381 +            String mapVersion = xmlMap.getAttribute("MAP_XML_VERSION");
   1.382 +            if (mapVersion.compareTo(MAP_XML_VERSION) > 0)
   1.383 +                throw new InvalidPreferencesFormatException(
   1.384 +                "Preferences map file format version " + mapVersion +
   1.385 +                " is not supported. This java installation can read" +
   1.386 +                " versions " + MAP_XML_VERSION + " or older. You may need" +
   1.387 +                " to install a newer version of JDK.");
   1.388 +
   1.389 +            NodeList entries = xmlMap.getChildNodes();
   1.390 +            for (int i=0, numEntries=entries.getLength(); i<numEntries; i++) {
   1.391 +                Element entry = (Element) entries.item(i);
   1.392 +                m.put(entry.getAttribute("key"), entry.getAttribute("value"));
   1.393 +            }
   1.394 +        } catch(SAXException e) {
   1.395 +            throw new InvalidPreferencesFormatException(e);
   1.396 +        }
   1.397 +    }
   1.398 +
   1.399 +    private static class Resolver implements EntityResolver {
   1.400 +        public InputSource resolveEntity(String pid, String sid)
   1.401 +            throws SAXException
   1.402 +        {
   1.403 +            if (sid.equals(PREFS_DTD_URI)) {
   1.404 +                InputSource is;
   1.405 +                is = new InputSource(new StringReader(PREFS_DTD));
   1.406 +                is.setSystemId(PREFS_DTD_URI);
   1.407 +                return is;
   1.408 +            }
   1.409 +            throw new SAXException("Invalid system identifier: " + sid);
   1.410 +        }
   1.411 +    }
   1.412 +
   1.413 +    private static class EH implements ErrorHandler {
   1.414 +        public void error(SAXParseException x) throws SAXException {
   1.415 +            throw x;
   1.416 +        }
   1.417 +        public void fatalError(SAXParseException x) throws SAXException {
   1.418 +            throw x;
   1.419 +        }
   1.420 +        public void warning(SAXParseException x) throws SAXException {
   1.421 +            throw x;
   1.422 +        }
   1.423 +    }
   1.424 +}