-
Notifications
You must be signed in to change notification settings - Fork 20
/
DOMUtils.java
475 lines (434 loc) · 15.5 KB
/
DOMUtils.java
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jboss.ws.common;
import static org.jboss.ws.common.Loggers.ROOT_LOGGER;
import static org.jboss.ws.common.Messages.MESSAGES;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
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.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* DOM2 utilities: this extends the {@link org.jboss.wsf.util.DOMUtils} adding parse and creation methods.
* These leverage static thread-local instances of {@link org.w3c.dom.Document} and {@link javax.xml.parsers.DocumentBuilder}.
* The ThreadLocal attributes can be reset using the clearThreadLocals() method.
*
* @author Thomas.Diesler@jboss.org
* @author alessio.soldano@jboss.com
*/
public final class DOMUtils extends org.jboss.ws.api.util.DOMUtils
{
private static final String DISABLE_DEFERRED_NODE_EXPANSION = "org.jboss.ws.disable_deferred_node_expansion";
private static final String DEFER_NODE_EXPANSION_FEATURE = "http://apache.org/xml/features/dom/defer-node-expansion";
private static final String ENABLE_DOCTYPE_DECL = "org.jboss.ws.enable_doctype_decl";
private static final String DISALLOW_DOCTYPE_DECL_FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
private static final String documentBuilderFactoryName;
private static final DocumentBuilderFactory documentBuilderFactory;
private static final boolean disableDeferedNodeExpansion = Boolean.getBoolean(DISABLE_DEFERRED_NODE_EXPANSION);
private static final boolean enableDoctypeDeclaration = Boolean.getBoolean(ENABLE_DOCTYPE_DECL);
static
{
//load default document builder factory using the DOMUtils' defining classloader
final ClassLoader classLoader = SecurityActions.getContextClassLoader();
SecurityActions.setContextClassLoader(DOMUtils.class.getClassLoader());
try
{
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
initializeFactory(factory);
documentBuilderFactoryName = factory.getClass().getCanonicalName();
documentBuilderFactory = factory;
}
finally
{
SecurityActions.setContextClassLoader(classLoader);
}
}
// All elements created by the same thread are created by the same builder and belong to the same doc
private static ThreadLocal<Document> documentThreadLocal = new ThreadLocal<Document>();
private static ThreadLocal<DocumentBuilder> builderThreadLocal = new ThreadLocal<DocumentBuilder>() {
protected DocumentBuilder initialValue()
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//check if the factory we'd get for this thread is equivalent to the default one;
//in that case re-use the default one and skip the initialization, which is time-consuming
final DocumentBuilderFactory threadFactory ;
if (factory.getClass().getClassLoader() == documentBuilderFactory.getClass().getClassLoader() &&
documentBuilderFactoryName.equals(factory.getClass().getCanonicalName()))
{
threadFactory = documentBuilderFactory ;
}
else
{
threadFactory = factory ;
initializeFactory(threadFactory) ;
}
DocumentBuilder builder = threadFactory.newDocumentBuilder();
return builder;
}
catch (Exception e)
{
throw MESSAGES.unableToCreateInstanceOf(e, DocumentBuilder.class.getName());
}
}
};
private static void initializeFactory(final DocumentBuilderFactory factory)
{
factory.setValidating(false);
factory.setNamespaceAware(true);
factory.setExpandEntityReferences(false);
try
{
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
if (disableDeferedNodeExpansion)
{
factory.setFeature(DEFER_NODE_EXPANSION_FEATURE, false);
}
if (!enableDoctypeDeclaration)
{
factory.setFeature(DISALLOW_DOCTYPE_DECL_FEATURE, true);
}
}
catch (ParserConfigurationException pce)
{
ROOT_LOGGER.error(pce);
}
}
public static void clearThreadLocals()
{
documentThreadLocal.remove();
builderThreadLocal.remove();
}
// Hide the constructor
private DOMUtils()
{
}
/**
* Creates a new DocumentBuilder instance using the provided DocumentBuilderFactory
*
* @param factory
* @return
*/
public static DocumentBuilder newDocumentBuilder(final DocumentBuilderFactory factory)
{
try
{
final DocumentBuilder builder = factory.newDocumentBuilder();
return builder;
}
catch (Exception e)
{
throw MESSAGES.unableToCreateInstanceOf(e, DocumentBuilder.class.getName());
}
}
/**
* Initialize the DocumentBuilder, set the current thread association and returns it
*/
public static DocumentBuilder getDocumentBuilder()
{
return builderThreadLocal.get();
}
/**
* Parse the given XML string and return the root Element
* This uses the document builder associated with the current thread.
*/
public static Element parse(String xmlString) throws IOException
{
try
{
return parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8")));
}
catch (IOException e)
{
ROOT_LOGGER.cannotParse(xmlString);
throw e;
}
}
/**
* Parse the given XML stream and return the root Element
*/
public static Element parse(InputStream xmlStream, DocumentBuilder builder) throws IOException
{
try
{
Document doc;
synchronized (builder) //synchronize to prevent concurrent parsing on the same DocumentBuilder
{
doc = builder.parse(xmlStream);
}
return doc.getDocumentElement();
}
catch (SAXException se)
{
throw new IOException(se.toString());
}
finally
{
xmlStream.close();
}
}
/**
* Parse the given XML stream and return the root Element
* This uses the document builder associated with the current thread.
*/
public static Element parse(InputStream xmlStream) throws IOException
{
DocumentBuilder builder = getDocumentBuilder();
return parse(xmlStream, builder);
}
/**
* Parse the given input source and return the root Element.
* This uses the document builder associated with the current thread.
*/
public static Element parse(InputSource source) throws IOException
{
try
{
Document doc;
DocumentBuilder builder = getDocumentBuilder();
synchronized (builder) //synchronize to prevent concurrent parsing on the same DocumentBuilder
{
doc = builder.parse(source);
}
return doc.getDocumentElement();
}
catch (SAXException se)
{
throw new IOException(se.toString());
}
finally
{
InputStream is = source.getByteStream();
if (is != null)
{
is.close();
}
Reader r = source.getCharacterStream();
if (r != null)
{
r.close();
}
}
}
/**
* Create an Element for a given name.
* This uses the document builder associated with the current thread.
*/
public static Element createElement(String localPart)
{
Document doc = getOwnerDocument();
if (ROOT_LOGGER.isTraceEnabled()) ROOT_LOGGER.trace("createElement {}" + localPart);
return doc.createElement(localPart);
}
/**
* Create an Element for a given name and prefix.
* This uses the document builder associated with the current thread.
*/
public static Element createElement(String localPart, String prefix)
{
Document doc = getOwnerDocument();
if (ROOT_LOGGER.isTraceEnabled()) ROOT_LOGGER.trace("createElement {}" + prefix + ":" + localPart);
return doc.createElement(prefix + ":" + localPart);
}
/**
* Create an Element for a given name, prefix and uri.
* This uses the document builder associated with the current thread.
*/
public static Element createElement(String localPart, String prefix, String uri)
{
Document doc = getOwnerDocument();
if (prefix == null || prefix.length() == 0)
{
if (ROOT_LOGGER.isTraceEnabled()) ROOT_LOGGER.trace("createElement {" + uri + "}" + localPart);
return doc.createElementNS(uri, localPart);
}
else
{
if (ROOT_LOGGER.isTraceEnabled()) ROOT_LOGGER.trace("createElement {" + uri + "}" + prefix + ":" + localPart);
return doc.createElementNS(uri, prefix + ":" + localPart);
}
}
/**
* Create an Element for a given QName.
* This uses the document builder associated with the current thread.
*/
public static Element createElement(QName qname)
{
return createElement(qname.getLocalPart(), qname.getPrefix(), qname.getNamespaceURI());
}
/**
* Create a org.w3c.dom.Text node.
* This uses the document builder associated with the current thread.
*/
public static Text createTextNode(String value)
{
Document doc = getOwnerDocument();
return doc.createTextNode(value);
}
/** Peek at the owner document without creating a new one if not set. */
public static Document peekOwnerDocument()
{
return documentThreadLocal.get();
}
public static void setOwnerDocument(Document doc)
{
documentThreadLocal.set(doc);
}
/** Get the owner document that is associated with the current thread */
public static Document getOwnerDocument()
{
Document doc = documentThreadLocal.get();
if (doc == null)
{
doc = getDocumentBuilder().newDocument();
documentThreadLocal.set(doc);
}
return doc;
}
/**
* Parse the contents of the provided source into an element.
* This uses the document builder associated with the current thread.
*
* @param source
* @return
* @throws IOException
*/
public static Element sourceToElement(Source source) throws IOException
{
Element retElement = null;
if (source instanceof StreamSource)
{
StreamSource streamSource = (StreamSource)source;
InputStream ins = streamSource.getInputStream();
if (ins != null)
{
retElement = DOMUtils.parse(ins);
}
Reader reader = streamSource.getReader();
if (reader != null)
{
retElement = DOMUtils.parse(new InputSource(reader));
}
}
else if (source instanceof DOMSource)
{
DOMSource domSource = (DOMSource)source;
Node node = domSource.getNode();
if (node instanceof Element)
{
retElement = (Element)node;
}
else if (node instanceof Document)
{
retElement = ((Document)node).getDocumentElement();
}
}
else if (source instanceof SAXSource)
{
// The fact that JAXBSource derives from SAXSource is an implementation detail.
// Thus in general applications are strongly discouraged from accessing methods defined on SAXSource.
// The XMLReader object obtained by the getXMLReader method shall be used only for parsing the InputSource object returned by the getInputSource method.
final boolean hasInputSource = ((SAXSource) source).getInputSource() != null;
final boolean hasXMLReader = ((SAXSource) source).getXMLReader() != null;
if (hasInputSource || hasXMLReader)
{
try
{
TransformerFactory tf = TransformerFactory.newInstance();
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.transform(source, new StreamResult(baos));
retElement = DOMUtils.parse(new ByteArrayInputStream(baos.toByteArray()));
}
catch (TransformerException ex)
{
throw new IOException(ex);
}
}
}
else
{
throw MESSAGES.sourceTypeNotImplemented(source.getClass());
}
return retElement;
}
/**
* Converts XML node in pretty mode using UTF-8 encoding to string.
*
* @param node XML document or element
* @return XML string
* @throws Exception if some error occurs
*/
public static String node2String(final Node node) throws UnsupportedEncodingException
{
return node2String(node, true, Constants.DEFAULT_XML_CHARSET);
}
/**
* Converts XML node in specified pretty mode using UTF-8 encoding to string.
*
* @param node XML document or element
* @param prettyPrint whether XML have to be pretty formated
* @return XML string
* @throws Exception if some error occurs
*/
public static String node2String(final Node node, boolean prettyPrint) throws UnsupportedEncodingException
{
return node2String(node, prettyPrint, Constants.DEFAULT_XML_CHARSET);
}
/**
* Converts XML node in specified pretty mode and encoding to string.
*
* @param node XML document or element
* @param prettyPrint whether XML have to be pretty formated
* @param encoding to use
* @return XML string
* @throws UnsupportedEncodingException
*/
public static String node2String(final Node node, boolean prettyPrint, String encoding) throws UnsupportedEncodingException
{
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
new DOMWriter(new PrintWriter(baos), encoding).setPrettyprint(prettyPrint).print(node);
return baos.toString(encoding);
}
}