src/share/classes/java/util/prefs/XmlSupport.java
author duke
Sat, 01 Dec 2007 00:00:00 +0000
changeset 0 37a05a11f281
child 2395 00cd9dc3c2b5
permissions -rw-r--r--
Initial load
duke@0
     1
/*
duke@0
     2
 * Copyright 2002-2006 Sun Microsystems, Inc.  All Rights Reserved.
duke@0
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
duke@0
     4
 *
duke@0
     5
 * This code is free software; you can redistribute it and/or modify it
duke@0
     6
 * under the terms of the GNU General Public License version 2 only, as
duke@0
     7
 * published by the Free Software Foundation.  Sun designates this
duke@0
     8
 * particular file as subject to the "Classpath" exception as provided
duke@0
     9
 * by Sun in the LICENSE file that accompanied this code.
duke@0
    10
 *
duke@0
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
duke@0
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
duke@0
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
duke@0
    14
 * version 2 for more details (a copy is included in the LICENSE file that
duke@0
    15
 * accompanied this code).
duke@0
    16
 *
duke@0
    17
 * You should have received a copy of the GNU General Public License version
duke@0
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
duke@0
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
duke@0
    20
 *
duke@0
    21
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
duke@0
    22
 * CA 95054 USA or visit www.sun.com if you need additional information or
duke@0
    23
 * have any questions.
duke@0
    24
 */
duke@0
    25
duke@0
    26
package java.util.prefs;
duke@0
    27
duke@0
    28
import java.util.*;
duke@0
    29
import java.io.*;
duke@0
    30
import javax.xml.parsers.*;
duke@0
    31
import javax.xml.transform.*;
duke@0
    32
import javax.xml.transform.dom.*;
duke@0
    33
import javax.xml.transform.stream.*;
duke@0
    34
import org.xml.sax.*;
duke@0
    35
import org.w3c.dom.*;
duke@0
    36
duke@0
    37
/**
duke@0
    38
 * XML Support for java.util.prefs. Methods to import and export preference
duke@0
    39
 * nodes and subtrees.
duke@0
    40
 *
duke@0
    41
 * @author  Josh Bloch and Mark Reinhold
duke@0
    42
 * @see     Preferences
duke@0
    43
 * @since   1.4
duke@0
    44
 */
duke@0
    45
class XmlSupport {
duke@0
    46
    // The required DTD URI for exported preferences
duke@0
    47
    private static final String PREFS_DTD_URI =
duke@0
    48
        "http://java.sun.com/dtd/preferences.dtd";
duke@0
    49
duke@0
    50
    // The actual DTD corresponding to the URI
duke@0
    51
    private static final String PREFS_DTD =
duke@0
    52
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
duke@0
    53
duke@0
    54
        "<!-- DTD for preferences -->"               +
duke@0
    55
duke@0
    56
        "<!ELEMENT preferences (root) >"             +
duke@0
    57
        "<!ATTLIST preferences"                      +
duke@0
    58
        " EXTERNAL_XML_VERSION CDATA \"0.0\"  >"     +
duke@0
    59
duke@0
    60
        "<!ELEMENT root (map, node*) >"              +
duke@0
    61
        "<!ATTLIST root"                             +
duke@0
    62
        "          type (system|user) #REQUIRED >"   +
duke@0
    63
duke@0
    64
        "<!ELEMENT node (map, node*) >"              +
duke@0
    65
        "<!ATTLIST node"                             +
duke@0
    66
        "          name CDATA #REQUIRED >"           +
duke@0
    67
duke@0
    68
        "<!ELEMENT map (entry*) >"                   +
duke@0
    69
        "<!ATTLIST map"                              +
duke@0
    70
        "  MAP_XML_VERSION CDATA \"0.0\"  >"         +
duke@0
    71
        "<!ELEMENT entry EMPTY >"                    +
duke@0
    72
        "<!ATTLIST entry"                            +
duke@0
    73
        "          key CDATA #REQUIRED"              +
duke@0
    74
        "          value CDATA #REQUIRED >"          ;
duke@0
    75
    /**
duke@0
    76
     * Version number for the format exported preferences files.
duke@0
    77
     */
duke@0
    78
    private static final String EXTERNAL_XML_VERSION = "1.0";
duke@0
    79
duke@0
    80
    /*
duke@0
    81
     * Version number for the internal map files.
duke@0
    82
     */
duke@0
    83
    private static final String MAP_XML_VERSION = "1.0";
duke@0
    84
duke@0
    85
    /**
duke@0
    86
     * Export the specified preferences node and, if subTree is true, all
duke@0
    87
     * subnodes, to the specified output stream.  Preferences are exported as
duke@0
    88
     * an XML document conforming to the definition in the Preferences spec.
duke@0
    89
     *
duke@0
    90
     * @throws IOException if writing to the specified output stream
duke@0
    91
     *         results in an <tt>IOException</tt>.
duke@0
    92
     * @throws BackingStoreException if preference data cannot be read from
duke@0
    93
     *         backing store.
duke@0
    94
     * @throws IllegalStateException if this node (or an ancestor) has been
duke@0
    95
     *         removed with the {@link #removeNode()} method.
duke@0
    96
     */
duke@0
    97
    static void export(OutputStream os, final Preferences p, boolean subTree)
duke@0
    98
        throws IOException, BackingStoreException {
duke@0
    99
        if (((AbstractPreferences)p).isRemoved())
duke@0
   100
            throw new IllegalStateException("Node has been removed");
duke@0
   101
        Document doc = createPrefsDoc("preferences");
duke@0
   102
        Element preferences =  doc.getDocumentElement() ;
duke@0
   103
        preferences.setAttribute("EXTERNAL_XML_VERSION", EXTERNAL_XML_VERSION);
duke@0
   104
        Element xmlRoot =  (Element)
duke@0
   105
        preferences.appendChild(doc.createElement("root"));
duke@0
   106
        xmlRoot.setAttribute("type", (p.isUserNode() ? "user" : "system"));
duke@0
   107
duke@0
   108
        // Get bottom-up list of nodes from p to root, excluding root
duke@0
   109
        List ancestors = new ArrayList();
duke@0
   110
duke@0
   111
        for (Preferences kid = p, dad = kid.parent(); dad != null;
duke@0
   112
                                   kid = dad, dad = kid.parent()) {
duke@0
   113
            ancestors.add(kid);
duke@0
   114
        }
duke@0
   115
        Element e = xmlRoot;
duke@0
   116
        for (int i=ancestors.size()-1; i >= 0; i--) {
duke@0
   117
            e.appendChild(doc.createElement("map"));
duke@0
   118
            e = (Element) e.appendChild(doc.createElement("node"));
duke@0
   119
            e.setAttribute("name", ((Preferences)ancestors.get(i)).name());
duke@0
   120
        }
duke@0
   121
        putPreferencesInXml(e, doc, p, subTree);
duke@0
   122
duke@0
   123
        writeDoc(doc, os);
duke@0
   124
    }
duke@0
   125
duke@0
   126
    /**
duke@0
   127
     * Put the preferences in the specified Preferences node into the
duke@0
   128
     * specified XML element which is assumed to represent a node
duke@0
   129
     * in the specified XML document which is assumed to conform to
duke@0
   130
     * PREFS_DTD.  If subTree is true, create children of the specified
duke@0
   131
     * XML node conforming to all of the children of the specified
duke@0
   132
     * Preferences node and recurse.
duke@0
   133
     *
duke@0
   134
     * @throws BackingStoreException if it is not possible to read
duke@0
   135
     *         the preferences or children out of the specified
duke@0
   136
     *         preferences node.
duke@0
   137
     */
duke@0
   138
    private static void putPreferencesInXml(Element elt, Document doc,
duke@0
   139
               Preferences prefs, boolean subTree) throws BackingStoreException
duke@0
   140
    {
duke@0
   141
        Preferences[] kidsCopy = null;
duke@0
   142
        String[] kidNames = null;
duke@0
   143
duke@0
   144
        // Node is locked to export its contents and get a
duke@0
   145
        // copy of children, then lock is released,
duke@0
   146
        // and, if subTree = true, recursive calls are made on children
duke@0
   147
        synchronized (((AbstractPreferences)prefs).lock) {
duke@0
   148
            // Check if this node was concurrently removed. If yes
duke@0
   149
            // remove it from XML Document and return.
duke@0
   150
            if (((AbstractPreferences)prefs).isRemoved()) {
duke@0
   151
                elt.getParentNode().removeChild(elt);
duke@0
   152
                return;
duke@0
   153
            }
duke@0
   154
            // Put map in xml element
duke@0
   155
            String[] keys = prefs.keys();
duke@0
   156
            Element map = (Element) elt.appendChild(doc.createElement("map"));
duke@0
   157
            for (int i=0; i<keys.length; i++) {
duke@0
   158
                Element entry = (Element)
duke@0
   159
                    map.appendChild(doc.createElement("entry"));
duke@0
   160
                entry.setAttribute("key", keys[i]);
duke@0
   161
                // NEXT STATEMENT THROWS NULL PTR EXC INSTEAD OF ASSERT FAIL
duke@0
   162
                entry.setAttribute("value", prefs.get(keys[i], null));
duke@0
   163
            }
duke@0
   164
            // Recurse if appropriate
duke@0
   165
            if (subTree) {
duke@0
   166
                /* Get a copy of kids while lock is held */
duke@0
   167
                kidNames = prefs.childrenNames();
duke@0
   168
                kidsCopy = new Preferences[kidNames.length];
duke@0
   169
                for (int i = 0; i <  kidNames.length; i++)
duke@0
   170
                    kidsCopy[i] = prefs.node(kidNames[i]);
duke@0
   171
            }
duke@0
   172
            // release lock
duke@0
   173
        }
duke@0
   174
duke@0
   175
        if (subTree) {
duke@0
   176
            for (int i=0; i < kidNames.length; i++) {
duke@0
   177
                Element xmlKid = (Element)
duke@0
   178
                    elt.appendChild(doc.createElement("node"));
duke@0
   179
                xmlKid.setAttribute("name", kidNames[i]);
duke@0
   180
                putPreferencesInXml(xmlKid, doc, kidsCopy[i], subTree);
duke@0
   181
            }
duke@0
   182
        }
duke@0
   183
    }
duke@0
   184
duke@0
   185
    /**
duke@0
   186
     * Import preferences from the specified input stream, which is assumed
duke@0
   187
     * to contain an XML document in the format described in the Preferences
duke@0
   188
     * spec.
duke@0
   189
     *
duke@0
   190
     * @throws IOException if reading from the specified output stream
duke@0
   191
     *         results in an <tt>IOException</tt>.
duke@0
   192
     * @throws InvalidPreferencesFormatException Data on input stream does not
duke@0
   193
     *         constitute a valid XML document with the mandated document type.
duke@0
   194
     */
duke@0
   195
    static void importPreferences(InputStream is)
duke@0
   196
        throws IOException, InvalidPreferencesFormatException
duke@0
   197
    {
duke@0
   198
        try {
duke@0
   199
            Document doc = loadPrefsDoc(is);
duke@0
   200
            String xmlVersion =
duke@0
   201
                doc.getDocumentElement().getAttribute("EXTERNAL_XML_VERSION");
duke@0
   202
            if (xmlVersion.compareTo(EXTERNAL_XML_VERSION) > 0)
duke@0
   203
                throw new InvalidPreferencesFormatException(
duke@0
   204
                "Exported preferences file format version " + xmlVersion +
duke@0
   205
                " is not supported. This java installation can read" +
duke@0
   206
                " versions " + EXTERNAL_XML_VERSION + " or older. You may need" +
duke@0
   207
                " to install a newer version of JDK.");
duke@0
   208
duke@0
   209
            Element xmlRoot = (Element) doc.getDocumentElement().
duke@0
   210
                                               getChildNodes().item(0);
duke@0
   211
            Preferences prefsRoot =
duke@0
   212
                (xmlRoot.getAttribute("type").equals("user") ?
duke@0
   213
                            Preferences.userRoot() : Preferences.systemRoot());
duke@0
   214
            ImportSubtree(prefsRoot, xmlRoot);
duke@0
   215
        } catch(SAXException e) {
duke@0
   216
            throw new InvalidPreferencesFormatException(e);
duke@0
   217
        }
duke@0
   218
    }
duke@0
   219
duke@0
   220
    /**
duke@0
   221
     * Create a new prefs XML document.
duke@0
   222
     */
duke@0
   223
    private static Document createPrefsDoc( String qname ) {
duke@0
   224
        try {
duke@0
   225
            DOMImplementation di = DocumentBuilderFactory.newInstance().
duke@0
   226
                newDocumentBuilder().getDOMImplementation();
duke@0
   227
            DocumentType dt = di.createDocumentType(qname, null, PREFS_DTD_URI);
duke@0
   228
            return di.createDocument(null, qname, dt);
duke@0
   229
        } catch(ParserConfigurationException e) {
duke@0
   230
            throw new AssertionError(e);
duke@0
   231
        }
duke@0
   232
    }
duke@0
   233
duke@0
   234
    /**
duke@0
   235
     * Load an XML document from specified input stream, which must
duke@0
   236
     * have the requisite DTD URI.
duke@0
   237
     */
duke@0
   238
    private static Document loadPrefsDoc(InputStream in)
duke@0
   239
        throws SAXException, IOException
duke@0
   240
    {
duke@0
   241
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
duke@0
   242
        dbf.setIgnoringElementContentWhitespace(true);
duke@0
   243
        dbf.setValidating(true);
duke@0
   244
        dbf.setCoalescing(true);
duke@0
   245
        dbf.setIgnoringComments(true);
duke@0
   246
        try {
duke@0
   247
            DocumentBuilder db = dbf.newDocumentBuilder();
duke@0
   248
            db.setEntityResolver(new Resolver());
duke@0
   249
            db.setErrorHandler(new EH());
duke@0
   250
            return db.parse(new InputSource(in));
duke@0
   251
        } catch (ParserConfigurationException e) {
duke@0
   252
            throw new AssertionError(e);
duke@0
   253
        }
duke@0
   254
    }
duke@0
   255
duke@0
   256
    /**
duke@0
   257
     * Write XML document to the specified output stream.
duke@0
   258
     */
duke@0
   259
    private static final void writeDoc(Document doc, OutputStream out)
duke@0
   260
        throws IOException
duke@0
   261
    {
duke@0
   262
        try {
duke@0
   263
            TransformerFactory tf = TransformerFactory.newInstance();
duke@0
   264
            try {
duke@0
   265
                tf.setAttribute("indent-number", new Integer(2));
duke@0
   266
            } catch (IllegalArgumentException iae) {
duke@0
   267
                //Ignore the IAE. Should not fail the writeout even the
duke@0
   268
                //transformer provider does not support "indent-number".
duke@0
   269
            }
duke@0
   270
            Transformer t = tf.newTransformer();
duke@0
   271
            t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
duke@0
   272
            t.setOutputProperty(OutputKeys.INDENT, "yes");
duke@0
   273
            //Transformer resets the "indent" info if the "result" is a StreamResult with
duke@0
   274
            //an OutputStream object embedded, creating a Writer object on top of that
duke@0
   275
            //OutputStream object however works.
duke@0
   276
            t.transform(new DOMSource(doc),
duke@0
   277
                        new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));
duke@0
   278
        } catch(TransformerException e) {
duke@0
   279
            throw new AssertionError(e);
duke@0
   280
        }
duke@0
   281
    }
duke@0
   282
duke@0
   283
    /**
duke@0
   284
     * Recursively traverse the specified preferences node and store
duke@0
   285
     * the described preferences into the system or current user
duke@0
   286
     * preferences tree, as appropriate.
duke@0
   287
     */
duke@0
   288
    private static void ImportSubtree(Preferences prefsNode, Element xmlNode) {
duke@0
   289
        NodeList xmlKids = xmlNode.getChildNodes();
duke@0
   290
        int numXmlKids = xmlKids.getLength();
duke@0
   291
        /*
duke@0
   292
         * We first lock the node, import its contents and get
duke@0
   293
         * child nodes. Then we unlock the node and go to children
duke@0
   294
         * Since some of the children might have been concurrently
duke@0
   295
         * deleted we check for this.
duke@0
   296
         */
duke@0
   297
        Preferences[] prefsKids;
duke@0
   298
        /* Lock the node */
duke@0
   299
        synchronized (((AbstractPreferences)prefsNode).lock) {
duke@0
   300
            //If removed, return silently
duke@0
   301
            if (((AbstractPreferences)prefsNode).isRemoved())
duke@0
   302
                return;
duke@0
   303
duke@0
   304
            // Import any preferences at this node
duke@0
   305
            Element firstXmlKid = (Element) xmlKids.item(0);
duke@0
   306
            ImportPrefs(prefsNode, firstXmlKid);
duke@0
   307
            prefsKids = new Preferences[numXmlKids - 1];
duke@0
   308
duke@0
   309
            // Get involved children
duke@0
   310
            for (int i=1; i < numXmlKids; i++) {
duke@0
   311
                Element xmlKid = (Element) xmlKids.item(i);
duke@0
   312
                prefsKids[i-1] = prefsNode.node(xmlKid.getAttribute("name"));
duke@0
   313
            }
duke@0
   314
        } // unlocked the node
duke@0
   315
        // import children
duke@0
   316
        for (int i=1; i < numXmlKids; i++)
duke@0
   317
            ImportSubtree(prefsKids[i-1], (Element)xmlKids.item(i));
duke@0
   318
    }
duke@0
   319
duke@0
   320
    /**
duke@0
   321
     * Import the preferences described by the specified XML element
duke@0
   322
     * (a map from a preferences document) into the specified
duke@0
   323
     * preferences node.
duke@0
   324
     */
duke@0
   325
    private static void ImportPrefs(Preferences prefsNode, Element map) {
duke@0
   326
        NodeList entries = map.getChildNodes();
duke@0
   327
        for (int i=0, numEntries = entries.getLength(); i < numEntries; i++) {
duke@0
   328
            Element entry = (Element) entries.item(i);
duke@0
   329
            prefsNode.put(entry.getAttribute("key"),
duke@0
   330
                          entry.getAttribute("value"));
duke@0
   331
        }
duke@0
   332
    }
duke@0
   333
duke@0
   334
    /**
duke@0
   335
     * Export the specified Map<String,String> to a map document on
duke@0
   336
     * the specified OutputStream as per the prefs DTD.  This is used
duke@0
   337
     * as the internal (undocumented) format for FileSystemPrefs.
duke@0
   338
     *
duke@0
   339
     * @throws IOException if writing to the specified output stream
duke@0
   340
     *         results in an <tt>IOException</tt>.
duke@0
   341
     */
duke@0
   342
    static void exportMap(OutputStream os, Map map) throws IOException {
duke@0
   343
        Document doc = createPrefsDoc("map");
duke@0
   344
        Element xmlMap = doc.getDocumentElement( ) ;
duke@0
   345
        xmlMap.setAttribute("MAP_XML_VERSION", MAP_XML_VERSION);
duke@0
   346
duke@0
   347
        for (Iterator i = map.entrySet().iterator(); i.hasNext(); ) {
duke@0
   348
            Map.Entry e = (Map.Entry) i.next();
duke@0
   349
            Element xe = (Element)
duke@0
   350
                xmlMap.appendChild(doc.createElement("entry"));
duke@0
   351
            xe.setAttribute("key",   (String) e.getKey());
duke@0
   352
            xe.setAttribute("value", (String) e.getValue());
duke@0
   353
        }
duke@0
   354
duke@0
   355
        writeDoc(doc, os);
duke@0
   356
    }
duke@0
   357
duke@0
   358
    /**
duke@0
   359
     * Import Map from the specified input stream, which is assumed
duke@0
   360
     * to contain a map document as per the prefs DTD.  This is used
duke@0
   361
     * as the internal (undocumented) format for FileSystemPrefs.  The
duke@0
   362
     * key-value pairs specified in the XML document will be put into
duke@0
   363
     * the specified Map.  (If this Map is empty, it will contain exactly
duke@0
   364
     * the key-value pairs int the XML-document when this method returns.)
duke@0
   365
     *
duke@0
   366
     * @throws IOException if reading from the specified output stream
duke@0
   367
     *         results in an <tt>IOException</tt>.
duke@0
   368
     * @throws InvalidPreferencesFormatException Data on input stream does not
duke@0
   369
     *         constitute a valid XML document with the mandated document type.
duke@0
   370
     */
duke@0
   371
    static void importMap(InputStream is, Map m)
duke@0
   372
        throws IOException, InvalidPreferencesFormatException
duke@0
   373
    {
duke@0
   374
        try {
duke@0
   375
            Document doc = loadPrefsDoc(is);
duke@0
   376
            Element xmlMap = doc.getDocumentElement();
duke@0
   377
            // check version
duke@0
   378
            String mapVersion = xmlMap.getAttribute("MAP_XML_VERSION");
duke@0
   379
            if (mapVersion.compareTo(MAP_XML_VERSION) > 0)
duke@0
   380
                throw new InvalidPreferencesFormatException(
duke@0
   381
                "Preferences map file format version " + mapVersion +
duke@0
   382
                " is not supported. This java installation can read" +
duke@0
   383
                " versions " + MAP_XML_VERSION + " or older. You may need" +
duke@0
   384
                " to install a newer version of JDK.");
duke@0
   385
duke@0
   386
            NodeList entries = xmlMap.getChildNodes();
duke@0
   387
            for (int i=0, numEntries=entries.getLength(); i<numEntries; i++) {
duke@0
   388
                Element entry = (Element) entries.item(i);
duke@0
   389
                m.put(entry.getAttribute("key"), entry.getAttribute("value"));
duke@0
   390
            }
duke@0
   391
        } catch(SAXException e) {
duke@0
   392
            throw new InvalidPreferencesFormatException(e);
duke@0
   393
        }
duke@0
   394
    }
duke@0
   395
duke@0
   396
    private static class Resolver implements EntityResolver {
duke@0
   397
        public InputSource resolveEntity(String pid, String sid)
duke@0
   398
            throws SAXException
duke@0
   399
        {
duke@0
   400
            if (sid.equals(PREFS_DTD_URI)) {
duke@0
   401
                InputSource is;
duke@0
   402
                is = new InputSource(new StringReader(PREFS_DTD));
duke@0
   403
                is.setSystemId(PREFS_DTD_URI);
duke@0
   404
                return is;
duke@0
   405
            }
duke@0
   406
            throw new SAXException("Invalid system identifier: " + sid);
duke@0
   407
        }
duke@0
   408
    }
duke@0
   409
duke@0
   410
    private static class EH implements ErrorHandler {
duke@0
   411
        public void error(SAXParseException x) throws SAXException {
duke@0
   412
            throw x;
duke@0
   413
        }
duke@0
   414
        public void fatalError(SAXParseException x) throws SAXException {
duke@0
   415
            throw x;
duke@0
   416
        }
duke@0
   417
        public void warning(SAXParseException x) throws SAXException {
duke@0
   418
            throw x;
duke@0
   419
        }
duke@0
   420
    }
duke@0
   421
}