1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/src/share/classes/sun/util/xml/DefaultPrefsXmlSupport.java Wed Jun 24 17:29:29 2009 +0200
1.3 @@ -0,0 +1,385 @@
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 sun.util.xml;
1.30 +
1.31 +import java.util.*;
1.32 +import java.util.prefs.*;
1.33 +import java.io.*;
1.34 +
1.35 +/**
1.36 + * Simplified XML Support for java.util.prefs. Methods to import and export preference
1.37 + * nodes and subtrees.
1.38 + *
1.39 + * @author Jaroslav Tulach
1.40 + * @since 1.7
1.41 + */
1.42 +public class DefaultPrefsXmlSupport extends sun.util.xml.PrefsXmlSupport {
1.43 + public void export(OutputStream os, final Preferences p, boolean subTree)
1.44 + throws IOException, BackingStoreException {
1.45 + if (isRemoved(p))
1.46 + throw new IllegalStateException("Node has been removed");
1.47 + PrintWriter w = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
1.48 + w.println("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
1.49 + w.println("<!DOCTYPE preferences SYSTEM \"http://java.sun.com/dtd/preferences.dtd\">");
1.50 + w.println("<preferences EXTERNAL_XML_VERSION=\"1.0\">");
1.51 + w.print(" <root type=\"");
1.52 + w.print(p.isUserNode() ? "user" : "system");
1.53 + w.println("\">");
1.54 + LinkedList<Preferences> ancestors = new LinkedList<Preferences>();
1.55 + for (Preferences kid = p, dad = kid.parent(); dad != null;
1.56 + kid = dad, dad = kid.parent()) {
1.57 + ancestors.addFirst(kid);
1.58 + }
1.59 + String indent = " ";
1.60 + for (Preferences pref : ancestors) {
1.61 + indent = " " + indent;
1.62 + w.print(indent); w.println("<map/>");
1.63 + w.print(indent); w.print("<node name=\""); w.print(pref.name()); w.println("\">");
1.64 + }
1.65 +
1.66 + putPreferencesInXml(w, indent + " ", p, subTree);
1.67 + for (Preferences pref : ancestors) {
1.68 + w.print(indent); w.println("</node>");
1.69 + indent = indent.substring(2);
1.70 + }
1.71 +
1.72 + w.println(" </root>");
1.73 + w.println("</preferences>");
1.74 + w.flush();
1.75 + }
1.76 +
1.77 + private static void putPreferencesInXml(
1.78 + PrintWriter w, String indent, Preferences prefs, boolean subTree
1.79 + ) throws BackingStoreException {
1.80 + Preferences[] kidsCopy = null;
1.81 + String[] kidNames = null;
1.82 +
1.83 + // Node is locked to export its contents and get a
1.84 + // copy of children, then lock is released,
1.85 + // and, if subTree = true, recursive calls are made on children
1.86 + synchronized (lock(prefs)) {
1.87 + // Check if this node was concurrently removed. If yes
1.88 + // don't print it
1.89 + if (isRemoved(prefs)) {
1.90 + return;
1.91 + }
1.92 + // Put map in xml element
1.93 + String[] keys = prefs.keys();
1.94 + if (keys.length == 0) {
1.95 + w.print(indent); w.println("<map/>");
1.96 + } else {
1.97 + w.print(indent); w.println("<map>");
1.98 + for (int i=0; i<keys.length; i++) {
1.99 + w.print(indent); w.print(" <entry key=\"");
1.100 + w.print(keys[i]);
1.101 + w.print("\" value=\"");
1.102 + w.print(prefs.get(keys[i], null));
1.103 + w.println("\"/>");
1.104 + }
1.105 + w.print(indent); w.println("</map>");
1.106 + }
1.107 + // Recurse if appropriate
1.108 + if (subTree) {
1.109 + /* Get a copy of kids while lock is held */
1.110 + kidNames = prefs.childrenNames();
1.111 + kidsCopy = new Preferences[kidNames.length];
1.112 + for (int i = 0; i < kidNames.length; i++)
1.113 + kidsCopy[i] = prefs.node(kidNames[i]);
1.114 + }
1.115 + // release lock
1.116 + }
1.117 +
1.118 + if (subTree) {
1.119 + for (int i=0; i < kidNames.length; i++) {
1.120 + w.print(indent); w.print("<node name=\"");
1.121 + w.print(kidNames[i]);
1.122 + w.println("\">");
1.123 + putPreferencesInXml(w, " " + indent, kidsCopy[i], subTree);
1.124 + w.print(indent); w.println("</node>");
1.125 + }
1.126 + }
1.127 + }
1.128 +
1.129 + /**
1.130 + * Import preferences from the specified input stream, which is assumed
1.131 + * to contain an XML document in the format described in the Preferences
1.132 + * spec.
1.133 + *
1.134 + * @throws IOException if reading from the specified output stream
1.135 + * results in an <tt>IOException</tt>.
1.136 + * @throws InvalidPreferencesFormatException Data on input stream does not
1.137 + * constitute a valid XML document with the mandated document type.
1.138 + */
1.139 + public void importPreferences(InputStream is)
1.140 + throws IOException, InvalidPreferencesFormatException
1.141 + {
1.142 + /*
1.143 + try {
1.144 + Document doc = loadPrefsDoc(is);
1.145 + String xmlVersion =
1.146 + doc.getDocumentElement().getAttribute("EXTERNAL_XML_VERSION");
1.147 + if (xmlVersion.compareTo(EXTERNAL_XML_VERSION) > 0)
1.148 + throw new InvalidPreferencesFormatException(
1.149 + "Exported preferences file format version " + xmlVersion +
1.150 + " is not supported. This java installation can read" +
1.151 + " versions " + EXTERNAL_XML_VERSION + " or older. You may need" +
1.152 + " to install a newer version of JDK.");
1.153 +
1.154 + Element xmlRoot = (Element) doc.getDocumentElement().
1.155 + getChildNodes().item(0);
1.156 + Preferences prefsRoot =
1.157 + (xmlRoot.getAttribute("type").equals("user") ?
1.158 + Preferences.userRoot() : Preferences.systemRoot());
1.159 + ImportSubtree(prefsRoot, xmlRoot);
1.160 + } catch(SAXException e) {
1.161 + throw new InvalidPreferencesFormatException(e);
1.162 + }
1.163 + */
1.164 + }
1.165 +
1.166 + /**
1.167 + * Create a new prefs XML document.
1.168 + *
1.169 + private static Document createPrefsDoc( String qname ) {
1.170 + try {
1.171 + DOMImplementation di = DocumentBuilderFactory.newInstance().
1.172 + newDocumentBuilder().getDOMImplementation();
1.173 + DocumentType dt = di.createDocumentType(qname, null, PREFS_DTD_URI);
1.174 + return di.createDocument(null, qname, dt);
1.175 + } catch(ParserConfigurationException e) {
1.176 + throw new AssertionError(e);
1.177 + }
1.178 + }
1.179 +
1.180 + /**
1.181 + * Load an XML document from specified input stream, which must
1.182 + * have the requisite DTD URI.
1.183 + *
1.184 + private static Document loadPrefsDoc(InputStream in)
1.185 + throws SAXException, IOException
1.186 + {
1.187 + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1.188 + dbf.setIgnoringElementContentWhitespace(true);
1.189 + dbf.setValidating(true);
1.190 + dbf.setCoalescing(true);
1.191 + dbf.setIgnoringComments(true);
1.192 + try {
1.193 + DocumentBuilder db = dbf.newDocumentBuilder();
1.194 + db.setEntityResolver(new Resolver());
1.195 + db.setErrorHandler(new EH());
1.196 + return db.parse(new InputSource(in));
1.197 + } catch (ParserConfigurationException e) {
1.198 + throw new AssertionError(e);
1.199 + }
1.200 + }
1.201 +
1.202 + /**
1.203 + * Write XML document to the specified output stream.
1.204 + *
1.205 + private static final void writeDoc(Document doc, OutputStream out)
1.206 + throws IOException
1.207 + {
1.208 + try {
1.209 + TransformerFactory tf = TransformerFactory.newInstance();
1.210 + try {
1.211 + tf.setAttribute("indent-number", new Integer(2));
1.212 + } catch (IllegalArgumentException iae) {
1.213 + //Ignore the IAE. Should not fail the writeout even the
1.214 + //transformer provider does not support "indent-number".
1.215 + }
1.216 + Transformer t = tf.newTransformer();
1.217 + t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
1.218 + t.setOutputProperty(OutputKeys.INDENT, "yes");
1.219 + //Transformer resets the "indent" info if the "result" is a StreamResult with
1.220 + //an OutputStream object embedded, creating a Writer object on top of that
1.221 + //OutputStream object however works.
1.222 + t.transform(new DOMSource(doc),
1.223 + new StreamResult(new BufferedWriter(new OutputStreamWriter(out, "UTF-8"))));
1.224 + } catch(TransformerException e) {
1.225 + throw new AssertionError(e);
1.226 + }
1.227 + }
1.228 +
1.229 + /**
1.230 + * Recursively traverse the specified preferences node and store
1.231 + * the described preferences into the system or current user
1.232 + * preferences tree, as appropriate.
1.233 + *
1.234 + private static void ImportSubtree(Preferences prefsNode, Element xmlNode) {
1.235 + NodeList xmlKids = xmlNode.getChildNodes();
1.236 + int numXmlKids = xmlKids.getLength();
1.237 + /*
1.238 + * We first lock the node, import its contents and get
1.239 + * child nodes. Then we unlock the node and go to children
1.240 + * Since some of the children might have been concurrently
1.241 + * deleted we check for this.
1.242 + * /
1.243 + Preferences[] prefsKids;
1.244 + /* Lock the node * /
1.245 + synchronized (lock(prefsNode)) {
1.246 + //If removed, return silently
1.247 + if (isRemoved(prefsNode))
1.248 + return;
1.249 +
1.250 + // Import any preferences at this node
1.251 + Element firstXmlKid = (Element) xmlKids.item(0);
1.252 + ImportPrefs(prefsNode, firstXmlKid);
1.253 + prefsKids = new Preferences[numXmlKids - 1];
1.254 +
1.255 + // Get involved children
1.256 + for (int i=1; i < numXmlKids; i++) {
1.257 + Element xmlKid = (Element) xmlKids.item(i);
1.258 + prefsKids[i-1] = prefsNode.node(xmlKid.getAttribute("name"));
1.259 + }
1.260 + } // unlocked the node
1.261 + // import children
1.262 + for (int i=1; i < numXmlKids; i++)
1.263 + ImportSubtree(prefsKids[i-1], (Element)xmlKids.item(i));
1.264 + }
1.265 +
1.266 + /**
1.267 + * Import the preferences described by the specified XML element
1.268 + * (a map from a preferences document) into the specified
1.269 + * preferences node.
1.270 + * /
1.271 + private static void ImportPrefs(Preferences prefsNode, Element map) {
1.272 + NodeList entries = map.getChildNodes();
1.273 + for (int i=0, numEntries = entries.getLength(); i < numEntries; i++) {
1.274 + Element entry = (Element) entries.item(i);
1.275 + prefsNode.put(entry.getAttribute("key"),
1.276 + entry.getAttribute("value"));
1.277 + }
1.278 + }
1.279 +
1.280 + /**
1.281 + * Export the specified Map<String,String> to a map document on
1.282 + * the specified OutputStream as per the prefs DTD. This is used
1.283 + * as the internal (undocumented) format for FileSystemPrefs.
1.284 + *
1.285 + * @throws IOException if writing to the specified output stream
1.286 + * results in an <tt>IOException</tt>.
1.287 + */
1.288 + public void exportMap(OutputStream os, Map map) throws IOException {
1.289 + /*
1.290 + Document doc = createPrefsDoc("map");
1.291 + Element xmlMap = doc.getDocumentElement( ) ;
1.292 + xmlMap.setAttribute("MAP_XML_VERSION", MAP_XML_VERSION);
1.293 +
1.294 + for (Iterator i = map.entrySet().iterator(); i.hasNext(); ) {
1.295 + Map.Entry e = (Map.Entry) i.next();
1.296 + Element xe = (Element)
1.297 + xmlMap.appendChild(doc.createElement("entry"));
1.298 + xe.setAttribute("key", (String) e.getKey());
1.299 + xe.setAttribute("value", (String) e.getValue());
1.300 + }
1.301 +
1.302 + writeDoc(doc, os);
1.303 + */
1.304 + }
1.305 +
1.306 + /**
1.307 + * Import Map from the specified input stream, which is assumed
1.308 + * to contain a map document as per the prefs DTD. This is used
1.309 + * as the internal (undocumented) format for FileSystemPrefs. The
1.310 + * key-value pairs specified in the XML document will be put into
1.311 + * the specified Map. (If this Map is empty, it will contain exactly
1.312 + * the key-value pairs int the XML-document when this method returns.)
1.313 + *
1.314 + * @throws IOException if reading from the specified output stream
1.315 + * results in an <tt>IOException</tt>.
1.316 + * @throws InvalidPreferencesFormatException Data on input stream does not
1.317 + * constitute a valid XML document with the mandated document type.
1.318 + */
1.319 + public void importMap(InputStream is, Map m)
1.320 + throws IOException, InvalidPreferencesFormatException
1.321 + {
1.322 + /*
1.323 + try {
1.324 + Document doc = loadPrefsDoc(is);
1.325 + Element xmlMap = doc.getDocumentElement();
1.326 + // check version
1.327 + String mapVersion = xmlMap.getAttribute("MAP_XML_VERSION");
1.328 + if (mapVersion.compareTo(MAP_XML_VERSION) > 0)
1.329 + throw new InvalidPreferencesFormatException(
1.330 + "Preferences map file format version " + mapVersion +
1.331 + " is not supported. This java installation can read" +
1.332 + " versions " + MAP_XML_VERSION + " or older. You may need" +
1.333 + " to install a newer version of JDK.");
1.334 +
1.335 + NodeList entries = xmlMap.getChildNodes();
1.336 + for (int i=0, numEntries=entries.getLength(); i<numEntries; i++) {
1.337 + Element entry = (Element) entries.item(i);
1.338 + m.put(entry.getAttribute("key"), entry.getAttribute("value"));
1.339 + }
1.340 + } catch(SAXException e) {
1.341 + throw new InvalidPreferencesFormatException(e);
1.342 + }
1.343 + */
1.344 + }
1.345 +/*
1.346 + private static class Resolver implements EntityResolver {
1.347 + public InputSource resolveEntity(String pid, String sid)
1.348 + throws SAXException
1.349 + {
1.350 + if (sid.equals(PREFS_DTD_URI)) {
1.351 + InputSource is;
1.352 + is = new InputSource(new StringReader(PREFS_DTD));
1.353 + is.setSystemId(PREFS_DTD_URI);
1.354 + return is;
1.355 + }
1.356 + throw new SAXException("Invalid system identifier: " + sid);
1.357 + }
1.358 + }
1.359 +
1.360 + private static class EH implements ErrorHandler {
1.361 + public void error(SAXParseException x) throws SAXException {
1.362 + throw x;
1.363 + }
1.364 + public void fatalError(SAXParseException x) throws SAXException {
1.365 + throw x;
1.366 + }
1.367 + public void warning(SAXParseException x) throws SAXException {
1.368 + throw x;
1.369 + }
1.370 + }
1.371 +*/
1.372 + private static boolean isRemoved(Preferences p) {
1.373 + try {
1.374 + p.parent(); // throws IllegalStateException if removed;
1.375 + return false;
1.376 + } catch (IllegalStateException ex) {
1.377 + return true;
1.378 + }
1.379 + }
1.380 +
1.381 + private static Object lock(Preferences p) {
1.382 + /** JST-XXX: Needs reflection or accessor:
1.383 + * http://wiki.apidesign.org/wiki/FriendPackages
1.384 + return ((AbstractPreferences)prefs).lock;
1.385 + */
1.386 + return p;
1.387 + }
1.388 +}