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