1 /*
   2  * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.util.xml;
  27 
  28 import java.io.*;
  29 import java.util.*;
  30 import org.xml.sax.*;
  31 import org.w3c.dom.*;
  32 import javax.xml.parsers.*;
  33 import javax.xml.transform.*;
  34 import javax.xml.transform.dom.*;
  35 import javax.xml.transform.stream.*;
  36 
  37 import sun.util.spi.XmlPropertiesProvider;
  38 
  39 /**
  40  * A {@code XmlPropertiesProvider} implementation that uses the JAXP API
  41  * for parsing.
  42  *
  43  * @author  Michael McCloskey
  44  * @since   1.3
  45  */
  46 public class PlatformXmlPropertiesProvider extends XmlPropertiesProvider {
  47 
  48     // XML loading and saving methods for Properties
  49 
  50     // The required DTD URI for exported properties
  51     private static final String PROPS_DTD_URI =
  52     "http://java.sun.com/dtd/properties.dtd";
  53 
  54     private static final String PROPS_DTD =
  55     "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
  56     "<!-- DTD for properties -->"                +
  57     "<!ELEMENT properties ( comment?, entry* ) >"+
  58     "<!ATTLIST properties"                       +
  59         " version CDATA #FIXED \"1.0\">"         +
  60     "<!ELEMENT comment (#PCDATA) >"              +
  61     "<!ELEMENT entry (#PCDATA) >"                +
  62     "<!ATTLIST entry "                           +
  63         " key CDATA #REQUIRED>";
  64 
  65     /**
  66      * Version number for the format of exported properties files.
  67      */
  68     private static final String EXTERNAL_XML_VERSION = "1.0";
  69 
  70     @Override
  71     public void load(Properties props, InputStream in)
  72         throws IOException, InvalidPropertiesFormatException
  73     {
  74         Document doc = null;
  75         try {
  76             doc = getLoadingDoc(in);
  77         } catch (SAXException saxe) {
  78             throw new InvalidPropertiesFormatException(saxe);
  79         }
  80         Element propertiesElement = doc.getDocumentElement();
  81         String xmlVersion = propertiesElement.getAttribute("version");
  82         if (xmlVersion.compareTo(EXTERNAL_XML_VERSION) > 0)
  83             throw new InvalidPropertiesFormatException(
  84                 "Exported Properties file format version " + xmlVersion +
  85                 " is not supported. This java installation can read" +
  86                 " versions " + EXTERNAL_XML_VERSION + " or older. You" +
  87                 " may need to install a newer version of JDK.");
  88         importProperties(props, propertiesElement);
  89     }
  90 
  91     static Document getLoadingDoc(InputStream in)
  92         throws SAXException, IOException
  93     {
  94         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  95         dbf.setIgnoringElementContentWhitespace(true);
  96         dbf.setValidating(true);
  97         dbf.setCoalescing(true);
  98         dbf.setIgnoringComments(true);
  99         try {
 100             DocumentBuilder db = dbf.newDocumentBuilder();
 101             db.setEntityResolver(new Resolver());
 102             db.setErrorHandler(new EH());
 103             InputSource is = new InputSource(in);
 104             return db.parse(is);
 105         } catch (ParserConfigurationException x) {
 106             throw new Error(x);
 107         }
 108     }
 109 
 110     static void importProperties(Properties props, Element propertiesElement) {
 111         NodeList entries = propertiesElement.getChildNodes();
 112         int numEntries = entries.getLength();
 113         int start = numEntries > 0 &&
 114             entries.item(0).getNodeName().equals("comment") ? 1 : 0;
 115         for (int i=start; i<numEntries; i++) {
 116             Element entry = (Element)entries.item(i);
 117             if (entry.hasAttribute("key")) {
 118                 Node n = entry.getFirstChild();
 119                 String val = (n == null) ? "" : n.getNodeValue();
 120                 props.setProperty(entry.getAttribute("key"), val);
 121             }
 122         }
 123     }
 124 
 125     @Override
 126     public void store(Properties props, OutputStream os, String comment,
 127                       String encoding)
 128         throws IOException
 129     {
 130         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
 131         DocumentBuilder db = null;
 132         try {
 133             db = dbf.newDocumentBuilder();
 134         } catch (ParserConfigurationException pce) {
 135             assert(false);
 136         }
 137         Document doc = db.newDocument();
 138         Element properties =  (Element)
 139             doc.appendChild(doc.createElement("properties"));
 140 
 141         if (comment != null) {
 142             Element comments = (Element)properties.appendChild(
 143                 doc.createElement("comment"));
 144             comments.appendChild(doc.createTextNode(comment));
 145         }
 146 
 147         synchronized (props) {
 148             for (String key : props.stringPropertyNames()) {
 149                 Element entry = (Element)properties.appendChild(
 150                     doc.createElement("entry"));
 151                 entry.setAttribute("key", key);
 152                 entry.appendChild(doc.createTextNode(props.getProperty(key)));
 153             }
 154         }
 155         emitDocument(doc, os, encoding);
 156     }
 157 
 158     static void emitDocument(Document doc, OutputStream os, String encoding)
 159         throws IOException
 160     {
 161         TransformerFactory tf = TransformerFactory.newInstance();
 162         Transformer t = null;
 163         try {
 164             t = tf.newTransformer();
 165             t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, PROPS_DTD_URI);
 166             t.setOutputProperty(OutputKeys.INDENT, "yes");
 167             t.setOutputProperty(OutputKeys.METHOD, "xml");
 168             t.setOutputProperty(OutputKeys.ENCODING, encoding);
 169         } catch (TransformerConfigurationException tce) {
 170             assert(false);
 171         }
 172         DOMSource doms = new DOMSource(doc);
 173         StreamResult sr = new StreamResult(os);
 174         try {
 175             t.transform(doms, sr);
 176         } catch (TransformerException te) {
 177             throw new IOException(te);
 178         }
 179     }
 180 
 181     private static class Resolver implements EntityResolver {
 182         public InputSource resolveEntity(String pid, String sid)
 183             throws SAXException
 184         {
 185             if (sid.equals(PROPS_DTD_URI)) {
 186                 InputSource is;
 187                 is = new InputSource(new StringReader(PROPS_DTD));
 188                 is.setSystemId(PROPS_DTD_URI);
 189                 return is;
 190             }
 191             throw new SAXException("Invalid system identifier: " + sid);
 192         }
 193     }
 194 
 195     private static class EH implements ErrorHandler {
 196         public void error(SAXParseException x) throws SAXException {
 197             throw x;
 198         }
 199         public void fatalError(SAXParseException x) throws SAXException {
 200             throw x;
 201         }
 202         public void warning(SAXParseException x) throws SAXException {
 203             throw x;
 204         }
 205     }
 206 
 207 }