forked from scijava/scijava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXML.java
More file actions
272 lines (241 loc) · 8.25 KB
/
XML.java
File metadata and controls
272 lines (241 loc) · 8.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/*
* #%L
* Utility functions to introspect metadata of SciJava libraries.
* %%
* Copyright (C) 2022 - 2025 SciJava developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package org.scijava.meta;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.StringWriter;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.scijava.common3.Classes;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Helper class for working with XML documents.
*
* @author Curtis Rueden
*/
public class XML {
/** Path to the XML document (e.g., a file or URL). */
private final String path;
/** The parsed XML DOM. */
private final Document doc;
/** XPath evaluation mechanism. */
private final XPath xpath;
private final boolean debug =
"debug".equals(System.getProperty("scijava.log.level"));
/** Parses XML from the given file. */
public XML(final File file) throws IOException {
this(file.getAbsolutePath(), loadXML(file));
}
/** Parses XML from the given URL. */
public XML(final URL url) throws IOException {
this(url.getPath(), loadXML(url));
}
/** Parses XML from the given input stream. */
public XML(final InputStream in) throws IOException {
this(null, loadXML(in));
}
/** Parses XML from the given string. */
public XML(final String s) throws IOException {
this(null, loadXML(s));
}
/** Creates an XML object for an existing document. */
private XML(final String path, final Document doc) {
this.path = path;
this.doc = doc;
// Protect against class skew: some projects find it funny to ship outdated
// xalan, causing problems due to incompatible xalan/xerces combinations.
//
// We work around that by letting the XPathFactory try with the current
// context class loader, and fall back onto its parent until it succeeds
// (because the XPathFactory will ask the context class loader to find the
// configured services, including the
// com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl).
if (debug) {
System.err.println(Classes.location(XPathFactory.class));
}
XPath xp;
final var thread = Thread.currentThread();
final var contextClassLoader = thread.getContextClassLoader();
try {
var loader = contextClassLoader;
while (true) {
try {
xp = XPathFactory.newInstance().newXPath();
try {
// make sure that the current xalan/xerces pair can evaluate
// expressions (i.e. *not* throw NoSuchMethodErrors).
xp.evaluate("//dummy", doc);
}
catch (Throwable t) {
if (debug) {
System.err.println("There was a problem with " + xp.getClass() +
" in " + Classes.location(xp.getClass()) + ":");
t.printStackTrace();
}
throw new Error(t);
}
break;
}
catch (Error e) {
if (debug) e.printStackTrace();
if (loader == null) throw e;
loader = loader.getParent();
if (loader == null) throw e;
thread.setContextClassLoader(loader);
}
}
xpath = xp;
}
finally {
if (contextClassLoader != null) {
thread.setContextClassLoader(contextClassLoader);
}
}
}
// -- XML methods --
/** Gets the path to the XML document, or null if none. */
public String path() {
return path;
}
/** Obtains the CDATA identified by the given XPath expression. */
public String cdata(final String expression) {
final var nodes = xpath(expression);
if (nodes == null || nodes.getLength() == 0) return null;
return cdata(nodes.item(0));
}
// -- Object methods --
@Override
public String toString() {
try {
return dumpXML(doc);
}
catch (final TransformerException exc) {
// NB: Return the exception stack trace as the string.
// Although this is a bad idea, I find it somehow hilarious.
final var out = new ByteArrayOutputStream();
exc.printStackTrace(new PrintStream(out));
return out.toString();
}
}
// -- Utility methods --
/** Gets the CData beneath the given node. */
private static String cdata(final Node item) {
final var children = item.getChildNodes();
if (children.getLength() == 0) return null;
for (var i = 0; i < children.getLength(); i++) {
final var child = children.item(i);
if (child.getNodeType() != Node.TEXT_NODE) continue;
return child.getNodeValue();
}
return null;
}
// -- Helper methods --
/** Loads an XML document from the given file. */
private static Document loadXML(final File file) throws IOException {
try {
return createBuilder().parse(file.getAbsolutePath());
}
catch (ParserConfigurationException | SAXException exc) {
throw new IOException(exc);
}
}
/** Loads an XML document from the given URL. */
private static Document loadXML(final URL url) throws IOException {
try (final var in = url.openStream()) {
return loadXML(in);
}
}
/** Loads an XML document from the given input stream. */
private static Document loadXML(final InputStream in) throws IOException {
try {
return createBuilder().parse(in);
}
catch (ParserConfigurationException | SAXException exc) {
throw new IOException(exc);
}
}
/** Loads an XML document from the given input stream. */
private static Document loadXML(final String s) throws IOException {
try {
return createBuilder().parse(new ByteArrayInputStream(s.getBytes()));
}
catch (ParserConfigurationException | SAXException exc) {
throw new IOException(exc);
}
}
/** Creates an XML document builder. */
private static DocumentBuilder createBuilder()
throws ParserConfigurationException
{
return DocumentBuilderFactory.newInstance().newDocumentBuilder();
}
/** Converts the given DOM to a string. */
private static String dumpXML(final Document doc)
throws TransformerException
{
final Source source = new DOMSource(doc);
final var stringWriter = new StringWriter();
final Result result = new StreamResult(stringWriter);
final var factory = TransformerFactory.newInstance();
final var transformer = factory.newTransformer();
transformer.transform(source, result);
return stringWriter.getBuffer().toString();
}
/** Obtains the nodes identified by the given XPath expression. */
private NodeList xpath(final String expression) {
final Object result;
try {
result = xpath.evaluate(expression, doc, XPathConstants.NODESET);
}
catch (final XPathExpressionException e) {
return null;
}
return (NodeList) result;
}
}