src/share/classes/java/util/XMLUtils.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 2003-2004 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;
duke@0
    27
duke@0
    28
import java.io.*;
duke@0
    29
import org.xml.sax.*;
duke@0
    30
import org.xml.sax.helpers.*;
duke@0
    31
import org.w3c.dom.*;
duke@0
    32
import javax.xml.parsers.*;
duke@0
    33
import javax.xml.transform.*;
duke@0
    34
import javax.xml.transform.dom.*;
duke@0
    35
import javax.xml.transform.stream.*;
duke@0
    36
duke@0
    37
/**
duke@0
    38
 * A class used to aid in Properties load and save in XML. Keeping this
duke@0
    39
 * code outside of Properties helps reduce the number of classes loaded
duke@0
    40
 * when Properties is loaded.
duke@0
    41
 *
duke@0
    42
 * @author  Michael McCloskey
duke@0
    43
 * @since   1.3
duke@0
    44
 */
duke@0
    45
class XMLUtils {
duke@0
    46
duke@0
    47
    // XML loading and saving methods for Properties
duke@0
    48
duke@0
    49
    // The required DTD URI for exported properties
duke@0
    50
    private static final String PROPS_DTD_URI =
duke@0
    51
    "http://java.sun.com/dtd/properties.dtd";
duke@0
    52
duke@0
    53
    private static final String PROPS_DTD =
duke@0
    54
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
duke@0
    55
    "<!-- DTD for properties -->"                +
duke@0
    56
    "<!ELEMENT properties ( comment?, entry* ) >"+
duke@0
    57
    "<!ATTLIST properties"                       +
duke@0
    58
        " version CDATA #FIXED \"1.0\">"         +
duke@0
    59
    "<!ELEMENT comment (#PCDATA) >"              +
duke@0
    60
    "<!ELEMENT entry (#PCDATA) >"                +
duke@0
    61
    "<!ATTLIST entry "                           +
duke@0
    62
        " key CDATA #REQUIRED>";
duke@0
    63
duke@0
    64
    /**
duke@0
    65
     * Version number for the format of exported properties files.
duke@0
    66
     */
duke@0
    67
    private static final String EXTERNAL_XML_VERSION = "1.0";
duke@0
    68
duke@0
    69
    static void load(Properties props, InputStream in)
duke@0
    70
        throws IOException, InvalidPropertiesFormatException
duke@0
    71
    {
duke@0
    72
        Document doc = null;
duke@0
    73
        try {
duke@0
    74
            doc = getLoadingDoc(in);
duke@0
    75
        } catch (SAXException saxe) {
duke@0
    76
            throw new InvalidPropertiesFormatException(saxe);
duke@0
    77
        }
duke@0
    78
        Element propertiesElement = (Element)doc.getChildNodes().item(1);
duke@0
    79
        String xmlVersion = propertiesElement.getAttribute("version");
duke@0
    80
        if (xmlVersion.compareTo(EXTERNAL_XML_VERSION) > 0)
duke@0
    81
            throw new InvalidPropertiesFormatException(
duke@0
    82
                "Exported Properties file format version " + xmlVersion +
duke@0
    83
                " is not supported. This java installation can read" +
duke@0
    84
                " versions " + EXTERNAL_XML_VERSION + " or older. You" +
duke@0
    85
                " may need to install a newer version of JDK.");
duke@0
    86
        importProperties(props, propertiesElement);
duke@0
    87
    }
duke@0
    88
duke@0
    89
    static Document getLoadingDoc(InputStream in)
duke@0
    90
        throws SAXException, IOException
duke@0
    91
    {
duke@0
    92
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
duke@0
    93
        dbf.setIgnoringElementContentWhitespace(true);
duke@0
    94
        dbf.setValidating(true);
duke@0
    95
        dbf.setCoalescing(true);
duke@0
    96
        dbf.setIgnoringComments(true);
duke@0
    97
        try {
duke@0
    98
            DocumentBuilder db = dbf.newDocumentBuilder();
duke@0
    99
            db.setEntityResolver(new Resolver());
duke@0
   100
            db.setErrorHandler(new EH());
duke@0
   101
            InputSource is = new InputSource(in);
duke@0
   102
            return db.parse(is);
duke@0
   103
        } catch (ParserConfigurationException x) {
duke@0
   104
            throw new Error(x);
duke@0
   105
        }
duke@0
   106
    }
duke@0
   107
duke@0
   108
    static void importProperties(Properties props, Element propertiesElement) {
duke@0
   109
        NodeList entries = propertiesElement.getChildNodes();
duke@0
   110
        int numEntries = entries.getLength();
duke@0
   111
        int start = numEntries > 0 &&
duke@0
   112
            entries.item(0).getNodeName().equals("comment") ? 1 : 0;
duke@0
   113
        for (int i=start; i<numEntries; i++) {
duke@0
   114
            Element entry = (Element)entries.item(i);
duke@0
   115
            if (entry.hasAttribute("key")) {
duke@0
   116
                Node n = entry.getFirstChild();
duke@0
   117
                String val = (n == null) ? "" : n.getNodeValue();
duke@0
   118
                props.setProperty(entry.getAttribute("key"), val);
duke@0
   119
            }
duke@0
   120
        }
duke@0
   121
    }
duke@0
   122
duke@0
   123
    static void save(Properties props, OutputStream os, String comment,
duke@0
   124
                     String encoding)
duke@0
   125
        throws IOException
duke@0
   126
    {
duke@0
   127
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
duke@0
   128
        DocumentBuilder db = null;
duke@0
   129
        try {
duke@0
   130
            db = dbf.newDocumentBuilder();
duke@0
   131
        } catch (ParserConfigurationException pce) {
duke@0
   132
            assert(false);
duke@0
   133
        }
duke@0
   134
        Document doc = db.newDocument();
duke@0
   135
        Element properties =  (Element)
duke@0
   136
            doc.appendChild(doc.createElement("properties"));
duke@0
   137
duke@0
   138
        if (comment != null) {
duke@0
   139
            Element comments = (Element)properties.appendChild(
duke@0
   140
                doc.createElement("comment"));
duke@0
   141
            comments.appendChild(doc.createTextNode(comment));
duke@0
   142
        }
duke@0
   143
duke@0
   144
        Set keys = props.keySet();
duke@0
   145
        Iterator i = keys.iterator();
duke@0
   146
        while(i.hasNext()) {
duke@0
   147
            String key = (String)i.next();
duke@0
   148
            Element entry = (Element)properties.appendChild(
duke@0
   149
                doc.createElement("entry"));
duke@0
   150
            entry.setAttribute("key", key);
duke@0
   151
            entry.appendChild(doc.createTextNode(props.getProperty(key)));
duke@0
   152
        }
duke@0
   153
        emitDocument(doc, os, encoding);
duke@0
   154
    }
duke@0
   155
duke@0
   156
    static void emitDocument(Document doc, OutputStream os, String encoding)
duke@0
   157
        throws IOException
duke@0
   158
    {
duke@0
   159
        TransformerFactory tf = TransformerFactory.newInstance();
duke@0
   160
        Transformer t = null;
duke@0
   161
        try {
duke@0
   162
            t = tf.newTransformer();
duke@0
   163
            t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, PROPS_DTD_URI);
duke@0
   164
            t.setOutputProperty(OutputKeys.INDENT, "yes");
duke@0
   165
            t.setOutputProperty(OutputKeys.METHOD, "xml");
duke@0
   166
            t.setOutputProperty(OutputKeys.ENCODING, encoding);
duke@0
   167
        } catch (TransformerConfigurationException tce) {
duke@0
   168
            assert(false);
duke@0
   169
        }
duke@0
   170
        DOMSource doms = new DOMSource(doc);
duke@0
   171
        StreamResult sr = new StreamResult(os);
duke@0
   172
        try {
duke@0
   173
            t.transform(doms, sr);
duke@0
   174
        } catch (TransformerException te) {
duke@0
   175
            IOException ioe = new IOException();
duke@0
   176
            ioe.initCause(te);
duke@0
   177
            throw ioe;
duke@0
   178
        }
duke@0
   179
    }
duke@0
   180
duke@0
   181
    private static class Resolver implements EntityResolver {
duke@0
   182
        public InputSource resolveEntity(String pid, String sid)
duke@0
   183
            throws SAXException
duke@0
   184
        {
duke@0
   185
            if (sid.equals(PROPS_DTD_URI)) {
duke@0
   186
                InputSource is;
duke@0
   187
                is = new InputSource(new StringReader(PROPS_DTD));
duke@0
   188
                is.setSystemId(PROPS_DTD_URI);
duke@0
   189
                return is;
duke@0
   190
            }
duke@0
   191
            throw new SAXException("Invalid system identifier: " + sid);
duke@0
   192
        }
duke@0
   193
    }
duke@0
   194
duke@0
   195
    private static class EH implements ErrorHandler {
duke@0
   196
        public void error(SAXParseException x) throws SAXException {
duke@0
   197
            throw x;
duke@0
   198
        }
duke@0
   199
        public void fatalError(SAXParseException x) throws SAXException {
duke@0
   200
            throw x;
duke@0
   201
        }
duke@0
   202
        public void warning(SAXParseException x) throws SAXException {
duke@0
   203
            throw x;
duke@0
   204
        }
duke@0
   205
    }
duke@0
   206
duke@0
   207
}