-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathDOMHandle.java
More file actions
451 lines (424 loc) · 14.8 KB
/
DOMHandle.java
File metadata and controls
451 lines (424 loc) · 14.8 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
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
/*
* Copyright (c) 2010-2026 Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved.
*/
package com.marklogic.client.io;
import com.marklogic.client.MarkLogicIOException;
import com.marklogic.client.MarkLogicInternalException;
import com.marklogic.client.impl.XmlFactories;
import com.marklogic.client.io.marker.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ls.*;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* A DOM Handle represents XML content as a DOM document for reading or writing.
*/
public class DOMHandle
extends BaseHandle<InputStream, OutputStreamSender>
implements ResendableContentHandle<Document, InputStream>, OutputStreamSender,
XMLReadHandle, XMLWriteHandle,
StructureReadHandle, StructureWriteHandle, CtsQueryWriteHandle
{
static final private Logger logger = LoggerFactory.getLogger(DOMHandle.class);
private LSResourceResolver resolver;
private Document content;
private DocumentBuilderFactory factory;
private XPath xpathProcessor;
/**
* Creates a factory to create a DOMHandle instance for a DOM document.
* @return the factory
*/
static public ContentHandleFactory newFactory() {
return new ContentHandleFactory() {
@Override
public Class<?>[] getHandledClasses() {
return new Class<?>[]{ Document.class };
}
@Override
public boolean isHandled(Class<?> type) {
return Document.class.isAssignableFrom(type);
}
@Override
public <C> ContentHandle<C> newHandle(Class<C> type) {
@SuppressWarnings("unchecked")
ContentHandle<C> handle = isHandled(type) ?
(ContentHandle<C>) new DOMHandle() : null;
return handle;
}
};
}
/**
* Zero-argument constructor.
*/
public DOMHandle() {
super();
setResendable(true);
super.setFormat(Format.XML);
}
/**
* Initializes the handle with a DOM document for the content.
* @param content a DOM document
*/
public DOMHandle(Document content) {
this();
set(content);
}
/**
* Returns the resolver for resolving references while parsing the document.
* @return the resolver
*/
public LSResourceResolver getResolver() {
return resolver;
}
/**
* Specifies the resolver for resolving references while parsing the document.
* @param resolver the reference resolver
*/
public void setResolver(LSResourceResolver resolver) {
this.resolver = resolver;
}
/**
* Returns the DOM document for the content.
* @return the DOM document
*/
@Override
public Document get() {
return content;
}
/**
* Assigns a DOM document as the content.
* @param content a DOM document
*/
@Override
public void set(Document content) {
this.content = content;
}
/**
* Assigns a DOM document as the content and returns the handle
* as a fluent convenience.
* @param content a DOM document
* @return this handle
*/
public DOMHandle with(Document content) {
set(content);
return this;
}
@Override
public Class<Document> getContentClass() {
return Document.class;
}
@Override
public DOMHandle newHandle() {
return new DOMHandle().withMimetype(getMimetype());
}
@Override
public DOMHandle[] newHandleArray(int length) {
if (length < 0) throw new IllegalArgumentException("array length less than zero: "+length);
return new DOMHandle[length];
}
@Override
public Document[] newArray(int length) {
if (length < 0) throw new IllegalArgumentException("array length less than zero: "+length);
return new Document[length];
}
/**
* Restricts the format to XML.
*/
@Override
public void setFormat(Format format) {
if (format != Format.XML)
throw new IllegalArgumentException("DOMHandle supports the XML format only");
}
/**
* Specifies the mime type of the content and returns the handle
* as a fluent convenience.
* @param mimetype the mime type of the content
* @return this handle
*/
public DOMHandle withMimetype(String mimetype) {
setMimetype(mimetype);
return this;
}
@Override
public void fromBuffer(byte[] buffer) {
set(bytesToContent(buffer));
}
@Override
public byte[] toBuffer() {
return contentToBytes(get());
}
/**
* Returns the DOM document as an XML string.
*/
@Override
public String toString() {
byte[] buffer = toBuffer();
return (buffer == null) ? null : new String(buffer, StandardCharsets.UTF_8);
}
/**
* Returns the factory for building DOM documents.
* @return the document factory
* @throws ParserConfigurationException if it occurs while initializing the new factory
*/
public DocumentBuilderFactory getFactory() throws ParserConfigurationException {
if (factory == null)
factory = XmlFactories.getDocumentBuilderFactory();
return factory;
}
/**
* Specifies the factory for building DOM documents.
* @param factory the document factory
*/
public void setFactory(DocumentBuilderFactory factory) {
this.factory = factory;
}
/**
* Get the processor used to evaluate XPath expressions.
* You might get the XPath processor to configure it. For instance,
* you can configure the XPath processor to declare namespace
* bindings or to set a function or variable resolver.
* @see com.marklogic.client.util.EditableNamespaceContext
* @return the XPath expression processor
*/
public XPath getXPathProcessor() {
if (xpathProcessor == null)
xpathProcessor = makeXPathProcessorFactory().newXPath();
return xpathProcessor;
}
/**
* Specifies the processor used to evaluate XPath expressions against
* the document.
* @param xpathProcessor the XPath expression processor
*/
public void setXPathProcessor(XPath xpathProcessor) {
this.xpathProcessor = xpathProcessor;
}
protected XPathFactory makeXPathProcessorFactory() {
return XPathFactory.newInstance();
}
/**
* Evaluate a string XPath expression against the retrieved document.
* An XPath expression can return a Node or subinterface such as
* Element or Text, a NodeList, or a Boolean, Number, or String value.
* @param xpathExpression the XPath expression as a string
* @param as the type expected to be matched by the xpath
* @param <T> the type to return
* @return the value produced by the XPath expression
* @throws XPathExpressionException if xpathExpression cannot be evaluated
*/
public <T> T evaluateXPath(String xpathExpression, Class<T> as)
throws XPathExpressionException {
return evaluateXPath(xpathExpression, get(), as);
}
/**
* Evaluate a string XPath expression relative to a node such as a node
* returned by a previous XPath expression.
* An XPath expression can return a Node or subinterface such as
* Element or Text, a NodeList, or a Boolean, Number, or String value.
* @param xpathExpression the XPath expression as a string
* @param context the node for evaluating the expression
* @param as the type expected to be matched by the xpath
* @param <T> the type to return
* @return the value produced by the XPath expression
* @throws XPathExpressionException if xpathExpression cannot be evaluated
*/
public <T> T evaluateXPath(String xpathExpression, Node context, Class<T> as)
throws XPathExpressionException {
checkContext(context);
return castAs(
getXPathProcessor().evaluate(xpathExpression, context, returnXPathConstant(as)),
as
);
}
/**
* Compile an XPath string expression for efficient evaluation later.
* @param xpathExpression the XPath expression as a string
* @return the compiled XPath expression
* @throws XPathExpressionException if xpathExpression cannot be compiled
*/
public XPathExpression compileXPath(String xpathExpression)
throws XPathExpressionException {
return getXPathProcessor().compile(xpathExpression);
}
/**
* Evaluate a compiled XPath expression against the retrieved document.
* An XPath expression can return a Node or subinterface such as
* Element or Text, a NodeList, or a Boolean, Number, or String value.
* @param xpathExpression an XPath expression compiled previously
* @param as the type expected to be matched by the xpath
* @param <T> the type to return
* @return the value produced by the XPath expression
* @throws XPathExpressionException if xpathExpression cannot be evaluated
*/
public <T> T evaluateXPath(XPathExpression xpathExpression, Class<T> as)
throws XPathExpressionException {
return evaluateXPath(xpathExpression, get(), as);
}
/**
* Evaluate a compiled XPath expression relative to a node such as a node
* returned by a previous XPath expression.
* An XPath expression can return a Node or subinterface such as
* Element or Text, a NodeList, or a Boolean, Number, or String value.
* @param xpathExpression an XPath expression compiled previously
* @param context the node for evaluating the expression
* @param as the type expected to be matched by the xpath
* @param <T> the type to return
* @return the value produced by the XPath expression
* @throws XPathExpressionException if xpathExpression cannot be evaluated
*/
public <T> T evaluateXPath(XPathExpression xpathExpression, Node context, Class<T> as)
throws XPathExpressionException {
checkContext(context);
return castAs(
xpathExpression.evaluate(context, returnXPathConstant(as)),
as
);
}
protected void checkContext(Node context) {
if (context == null) {
throw new IllegalStateException("Cannot process empty context");
}
}
protected QName returnXPathConstant(Class<?> as) {
if (as == null) {
throw new IllegalArgumentException("cannot execute XPath as null");
} else if (Node.class.isAssignableFrom(as)) {
return XPathConstants.NODE;
} else if (NodeList.class.isAssignableFrom(as)) {
return XPathConstants.NODESET;
} else if (String.class.isAssignableFrom(as)) {
return XPathConstants.STRING;
} else if (Number.class.isAssignableFrom(as)) {
return XPathConstants.NUMBER;
} else if (Boolean.class.isAssignableFrom(as)) {
return XPathConstants.BOOLEAN;
}
throw new IllegalArgumentException("cannot execute XPath as "+as.getName());
}
protected <T> T castAs(Object result, Class<?> as) {
if (result == null) {
return null;
}
if (!as.isAssignableFrom(result.getClass())) {
throw new IllegalArgumentException("cannot cast "+result.getClass().getName()+" to "+as.getName());
}
@SuppressWarnings("unchecked")
T typedResult = (T) result;
return typedResult;
}
@Override
public Document bytesToContent(byte[] buffer) {
if (buffer == null || buffer.length == 0) return null;
return toContent(new ByteArrayInputStream(buffer));
}
@Override
public byte[] contentToBytes(Document content) {
try {
if (content == null)
return null;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
sendContent(content).write(buffer);
return buffer.toByteArray();
} catch (IOException e) {
throw new MarkLogicIOException(e);
}
}
@Override
public Document toContent(InputStream serialization) {
if (serialization == null) return null;
try {
if (logger.isDebugEnabled())
logger.debug("Parsing DOM document from input stream");
DocumentBuilderFactory factory = getFactory();
if (factory == null) {
throw new MarkLogicInternalException("Failed to make DOM document builder factory");
}
DOMImplementationLS domImpl = (DOMImplementationLS) factory.newDocumentBuilder().getDOMImplementation();
LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
if (resolver != null) {
parser.getDomConfig().setParameter("resource-resolver", resolver);
}
LSInput domInput = domImpl.createLSInput();
domInput.setEncoding("UTF-8");
domInput.setByteStream(serialization);
return parser.parse(domInput);
} catch (ParserConfigurationException e) {
logger.error("Failed to parse DOM document from input stream",e);
throw new MarkLogicInternalException(e);
} finally {
try {
serialization.close();
} catch (IOException e) {
//ignore
}
}
}
@Override
protected Class<InputStream> receiveAs() {
return InputStream.class;
}
@Override
protected void receiveContent(InputStream content) {
set(toContent(content));
}
@Override
protected OutputStreamSender sendContent() {
return sendContent(get());
}
private OutputStreamSender sendContent(Document content) {
try {
return new OutputStreamSenderImpl(getFactory(), content);
} catch (ParserConfigurationException e) {
logger.error("Failed to create output stream sender",e);
throw new MarkLogicInternalException(e);
}
}
@Override
public void write(OutputStream out) throws IOException {
sendContent().write(out);
}
static private class OutputStreamSenderImpl implements OutputStreamSender {
private final DocumentBuilderFactory factory;
private final Document content;
private OutputStreamSenderImpl(DocumentBuilderFactory factory, Document content) {
if (factory == null) {
throw new MarkLogicInternalException("Failed to make DOM document builder factory");
}
if (content == null) {
throw new IllegalStateException("No document to write");
}
this.factory = factory;
this.content = content;
}
@Override
public void write(OutputStream out) throws IOException {
try {
if (logger.isDebugEnabled())
logger.debug("Serializing DOM document to output stream");
DOMImplementationLS domImpl = (DOMImplementationLS) factory.newDocumentBuilder().getDOMImplementation();
LSOutput domOutput = domImpl.createLSOutput();
domOutput.setEncoding("UTF-8");
domOutput.setByteStream(out);
domImpl.createLSSerializer().write(content, domOutput);
} catch (DOMException e) {
logger.error("Failed to serialize DOM document to output stream",e);
throw new MarkLogicInternalException(e);
} catch (LSException e) {
logger.error("Failed to serialize DOM document to output stream",e);
throw new MarkLogicInternalException(e);
} catch (ParserConfigurationException e) {
logger.error("Failed to serialize DOM document to output stream",e);
throw new MarkLogicInternalException(e);
}
}
}
}