Debian Codegraph @

net/sf/saxon/dom/DOMObjectModel.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.dom;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.Builder;
12 import net.sf.saxon.event.PipelineConfiguration;
13 import net.sf.saxon.event.Receiver;
14 import net.sf.saxon.event.Sender;
15 import net.sf.saxon.expr.JPConverter;
16 import net.sf.saxon.expr.PJConverter;
17 import net.sf.saxon.expr.StaticProperty;
18 import net.sf.saxon.expr.XPathContext;
19 import net.sf.saxon.lib.ExternalObjectModel;
20 import net.sf.saxon.om.*;
21 import net.sf.saxon.pattern.AnyNodeTest;
22 import net.sf.saxon.trans.XPathException;
23 import net.sf.saxon.tree.wrapper.VirtualNode;
24 import net.sf.saxon.type.ItemType;
25 import net.sf.saxon.type.Type;
26 import net.sf.saxon.value.SequenceExtent;
27 import org.w3c.dom.Document;
28 import org.w3c.dom.DocumentFragment;
29 import org.w3c.dom.Node;
30 import org.w3c.dom.NodeList;
31
32 import javax.xml.parsers.DocumentBuilder;
33 import javax.xml.parsers.DocumentBuilderFactory;
34 import javax.xml.parsers.ParserConfigurationException;
35 import javax.xml.transform.Result;
36 import javax.xml.transform.Source;
37 import javax.xml.transform.dom.DOMResult;
38 import javax.xml.transform.dom.DOMSource;
39 import javax.xml.xpath.XPathConstants;
40 import java.util.ArrayList;
41 import java.util.HashSet;
42 import java.util.List;
43
44 /**
45 * This interface must be implemented by any third-party object model that can
46 * be wrapped with a wrapper that implements the Saxon Object Model (the NodeInfo interface).
47 * This implementation of the interface supports wrapping of DOM Documents.
48 */
49
50 public class DOMObjectModel extends TreeModel implements ExternalObjectModel {
51
52 private static DOMObjectModel THE_INSTANCE = new DOMObjectModel();
53 private static DocumentBuilderFactory factory = null;
54
55 /**
56 * Get a reusable instance instance of this class.
57 * <p>Note, this is not actually a singleton instance; the class also has a public constructor,
58 * which is needed to support the automatic loading of object models into the Configuration.</p>
59 *
60 * @return the singleton instance
61 */
62
63 public static DOMObjectModel getInstance() {
64 return THE_INSTANCE;
65 }
66
67 /**
68 * Create an instance of the DOMObjectModel class.
69 * <p>When possible, use the getInstance() method in preference, as the instance is then reusable.</p>
70 */
71
72 public DOMObjectModel() {
73 }
74
75 /**
76 * Get the name of a characteristic class, which, if it can be loaded, indicates that the supporting libraries
77 * for this object model implementation are available on the classpath
78 *
79 * @return by convention (but not necessarily) the class that implements a document node in the relevant
80 * external model
81 */
82 public String getDocumentClassName() {
83 return "org.w3c.dom.Document";
84 }
85
86 /**
87 * Get the URI of the external object model as used in the JAXP factory interfaces for obtaining
88 * an XPath implementation
89 */
90
91 public String getIdentifyingURI() {
92 return XPathConstants.DOM_OBJECT_MODEL;
93 }
94
95 public String getName() {
96 return "DOM";
97 }
98
99 /**
100 * Get a converter from XPath values to values in the external object model
101 *
102 * @param targetClass the required class of the result of the conversion. If this class represents
103 * a node or list of nodes in the external object model, the method should return a converter that takes
104 * a native node or sequence of nodes as input and returns a node or sequence of nodes in the
105 * external object model representation. Otherwise, it should return null.
106 * @return a converter, if the targetClass is recognized as belonging to this object model;
107 * otherwise null
108 */
109
110 public PJConverter getPJConverter(Class<?> targetClass) {
111 if (Node.class.isAssignableFrom(targetClass) && !NodeOverNodeInfo.class.isAssignableFrom(targetClass)) {
112 return new PJConverter() {
113 public Object convert(Sequence<?> value, Class<?> targetClass, XPathContext context) throws XPathException {
114 return convertXPathValueToObject(value, targetClass);
115 }
116 };
117 } else if (NodeList.class == targetClass) {
118 return new PJConverter() {
119 public Object convert(Sequence<?> value, Class<?> targetClass, XPathContext context) throws XPathException {
120 return convertXPathValueToObject(value, targetClass);
121 }
122 };
123 } else {
124 return null;
125 }
126 }
127
128 //public NodeSet ns;
129 public JPConverter getJPConverter(Class sourceClass, Configuration config) {
130 if (Node.class.isAssignableFrom(sourceClass) && !NodeOverNodeInfo.class.isAssignableFrom(sourceClass)) {
131 return new JPConverter() {
132 public Sequence<?> convert(Object obj, XPathContext context) {
133 return wrapOrUnwrapNode((Node) obj, context.getConfiguration());
134 }
135
136 public ItemType getItemType() {
137 return AnyNodeTest.getInstance();
138 }
139 };
140 } else if (NodeList.class.isAssignableFrom(sourceClass)) {
141 return new JPConverter() {
142 public Sequence<?> convert(Object obj, XPathContext context) {
143 Configuration config = context.getConfiguration();
144 NodeList list = (NodeList) obj;
145 final int len = list.getLength();
146 NodeInfo[] nodes = new NodeInfo[len];
147 for (int i = 0; i < len; i++) {
148 nodes[i] = wrapOrUnwrapNode(list.item(i), config);
149 }
150 return new SequenceExtent<>(nodes);
151 }
152
153 public ItemType getItemType() {
154 return AnyNodeTest.getInstance();
155 }
156
157 public int getCardinality() {
158 return StaticProperty.ALLOWS_ZERO_OR_MORE;
159 }
160 };
161 } else if (DOMSource.class.isAssignableFrom(sourceClass)) {
162 return new JPConverter() {
163 public Sequence<?> convert(Object obj, XPathContext context) {
164 return unravel((DOMSource) obj, context.getConfiguration());
165 }
166
167 public ItemType getItemType() {
168 return AnyNodeTest.getInstance();
169 }
170 };
171 } else if (DocumentWrapper.class == sourceClass) {
172 return new JPConverter() {
173 public Sequence<?> convert(Object obj, XPathContext context) {
174 return ((DocumentWrapper) obj).getRootNode();
175 }
176
177 public ItemType getItemType() {
178 return AnyNodeTest.getInstance();
179 }
180 };
181 } else {
182 return null;
183 }
184 }
185
186 /**
187 * Get a converter that converts a sequence of XPath nodes to this model's representation
188 * of a node list.
189 *
190 * @param node an example of the kind of node used in this model
191 * @return if the model does not recognize this node as one of its own, return null. Otherwise
192 * return a PJConverter that takes a list of XPath nodes (represented as NodeInfo objects) and
193 * returns a collection of nodes in this object model
194 */
195
196 public PJConverter getNodeListCreator(Object node) {
197 if (node == null ||
198 node instanceof Node ||
199 node instanceof DOMSource ||
200 node instanceof DocumentWrapper ||
201 (node instanceof VirtualNode && ((VirtualNode) node).getRealNode() instanceof Node)) {
202 return new PJConverter() {
203 /*@Nullable*/
204 public Object convert(Sequence<?> value, Class<?> targetClass, XPathContext context) throws XPathException {
205 return convertXPathValueToObject(value, NodeList.class);
206 }
207 };
208 } else {
209 return null;
210 }
211 }
212
213 /**
214 * Test whether this object model recognizes a particular kind of JAXP Result object,
215 * and if it does, return a Receiver that builds an instance of this data model from
216 * a sequence of events. If the Result is not recognised, return null.
217 */
218
219 public Receiver getDocumentBuilder(Result result) throws XPathException {
220 if (result instanceof DOMResult) {
221 DOMWriter emitter = new DOMWriter();
222 Node root = ((DOMResult) result).getNode();
223 if (root instanceof NodeOverNodeInfo && !(((NodeOverNodeInfo) root).getUnderlyingNodeInfo() instanceof MutableNodeInfo)) {
224 throw new XPathException("Supplied DOMResult is a non-mutable Saxon implementation");
225 }
226 // JDK 1.5 adds a nextSibling() property to identify the insertion point among the siblings
227 Node nextSibling = ((DOMResult) result).getNextSibling();
228 if (root == null) {
229 try {
230 if (factory == null) {
231 factory = DocumentBuilderFactory.newInstance();
232 }
233 DocumentBuilder docBuilder = factory.newDocumentBuilder();
234 Document out = docBuilder.newDocument();
235 ((DOMResult) result).setNode(out);
236 emitter.setNode(out);
237 } catch (ParserConfigurationException e) {
238 throw new XPathException(e);
239 }
240 } else {
241 emitter.setNode(root);
242 emitter.setNextSibling(nextSibling);
243 }
244 return emitter;
245 }
246 return null;
247 }
248
249 @Override
250 public Builder makeBuilder(PipelineConfiguration pipe) {
251 DOMWriter dw = new DOMWriter();
252 dw.setPipelineConfiguration(pipe);
253 return dw;
254 }
255
256 /**
257 * Test whether this object model recognizes a particular kind of JAXP Source object,
258 * and if it does, send the contents of the document to a supplied Receiver, and return true.
259 * Otherwise, return false
260 */
261
262 public boolean sendSource(Source source, Receiver receiver) throws XPathException {
263 if (source instanceof DOMSource) {
264 sendDOMSource((DOMSource)source, receiver);
265 return true;
266 }
267 return false;
268 }
269
270 public static void sendDOMSource(DOMSource source, Receiver receiver) throws XPathException {
271 Node startNode = source.getNode();
272 if (startNode == null) {
273 // Send an empty document
274 receiver.open();
275 receiver.startDocument(0);
276 receiver.endDocument();
277 receiver.close();
278 } else {
279 DOMSender driver = new DOMSender(startNode, receiver);
280 driver.setSystemId(source.getSystemId());
281 receiver.open();
282 driver.send();
283 receiver.close();
284 }
285 }
286
287 /**
288 * Wrap a DOM node using this object model to return the corresponding Saxon node.
289 *
290 * @param node the DOM node to be wrapped
291 * @param config the Saxon Configuration
292 * @return the wrapped DOM node
293 * @since 9.2
294 */
295
296 public NodeInfo wrap(Node node, Configuration config) {
297 // Supplied source is an ordinary DOM Node: wrap it
298 Document dom;
299 if (node.getNodeType() == Node.DOCUMENT_NODE) {
300 dom = (Document) node;
301 } else {
302 dom = node.getOwnerDocument();
303 }
304 DocumentWrapper docWrapper = new DocumentWrapper(dom, node.getBaseURI(), config);
305 return docWrapper.wrap(node);
306 }
307
308 /**
309 * Copy a DOM node to create a node in a different tree model
310 *
311 * @param node the DOM node to be copied
312 * @param model the target tree model
313 * @param config the Saxon Configuration
314 * @return the copied node
315 * @throws net.sf.saxon.trans.XPathException
316 * if the operation fails
317 * @since 9.2
318 */
319
320 public NodeInfo copy(Node node, TreeModel model, Configuration config) throws XPathException {
321 PipelineConfiguration pipe = config.makePipelineConfiguration();
322 Builder builder = model.makeBuilder(pipe);
323 builder.open();
324 Sender.send(new DOMSource(node), builder, null);
325 NodeInfo result = builder.getCurrentRoot();
326 builder.close();
327 return result;
328 }
329
330 /**
331 * Wrap or unwrap a node using this object model to return the corresponding Saxon node. If the supplied
332 * source does not belong to this object model, return null
333 */
334
335 public NodeInfo unravel(Source source, Configuration config) {
336
337 if (source instanceof DOMSource) {
338 Node dsnode = ((DOMSource) source).getNode();
339 if (!(dsnode instanceof NodeOverNodeInfo)) {
340 // Supplied source is an ordinary DOM Node: wrap it
341 Document dom;
342 if (dsnode.getNodeType() == Node.DOCUMENT_NODE) {
343 dom = (Document) dsnode;
344 } else {
345 dom = dsnode.getOwnerDocument();
346 }
347 DocumentWrapper docWrapper = new DocumentWrapper(dom, source.getSystemId(), config);
348 return docWrapper.wrap(dsnode);
349 }
350 }
351 return null;
352 }
353
354 /**
355 * Wrap a DOM Node as a NodeInfo, unless it already wraps a NodeInfo, inwhich case unwrap it
356 *
357 * @param node the node to be wrapped
358 * @param config the Saxon Configuration. This must be the same Configuration, or one that is compatible with,
359 * the Configuration used to compile and execute the query or stylesheet.
360 * @return the new wrapper node
361 */
362
363 private NodeInfo wrapOrUnwrapNode(Node node, Configuration config) {
364 if (node instanceof NodeOverNodeInfo) {
365 return ((NodeOverNodeInfo) node).getUnderlyingNodeInfo();
366 } else {
367 TreeInfo doc = wrapDocument(node, "", config);
368 return wrapNode(doc, node);
369 }
370 }
371
372 /**
373 * Convert an XPath value to an object in this object model. If the supplied value can be converted
374 * to an object in this model, of the specified class, then the conversion should be done and the
375 * resulting object returned. If the value cannot be converted, the method should return null. Note
376 * that the supplied class might be a List, in which case the method should inspect the contents of the
377 * Value to see whether they belong to this object model.
378 *
379 * @param value the XPath value to be converted
380 * @param target the class of object required
381 * @return the result of the conversion
382 * @throws XPathException if the target class is explicitly associated with this object model, but the
383 * supplied value cannot be converted to the appropriate class
384 */
385
386 public static Object convertXPathValueToObject(Sequence<?> value, Class<?> target) throws XPathException {
387 // We accept the object if (a) the target class is Node, Node[], or NodeList,
388 // or (b) the supplied object is a node, or sequence of nodes, that wrap DOM nodes,
389 // provided that the target class is Object or a collection class
390 boolean requireDOM =
391 Node.class.isAssignableFrom(target) || (target == NodeList.class) ||
392 (target.isArray() && Node.class.isAssignableFrom(target.getComponentType()));
393
394 // Note: we allow the declared type of the method argument to be a subclass of Node. If the actual
395 // node supplied is the wrong kind of node, this will result in a Java exception.
396
397 boolean allowDOM =
398 target == Object.class || target.isAssignableFrom(ArrayList.class) ||
399 target.isAssignableFrom(HashSet.class) ||
400 (target.isArray() && target.getComponentType() == Object.class);
401 if (!(requireDOM || allowDOM)) {
402 return null;
403 }
404 List<Node> nodes = new ArrayList<>(20);
405
406 SequenceIterator iter = value.iterate();
407 Item item;
408 while ((item = iter.next()) != null) {
409 if (item instanceof VirtualNode) {
410 Object o = ((VirtualNode) item).getRealNode();
411 if (o instanceof Node) {
412 nodes.add((Node) o);
413 continue;
414 }
415 }
416 if (requireDOM) {
417 if (item instanceof NodeInfo) {
418 nodes.add(NodeOverNodeInfo.wrap((NodeInfo) item));
419 } else {
420 throw new XPathException(
421 "Cannot convert XPath value to Java object: required class is " + target.getName() +
422 "; supplied value has type " + Type.displayTypeName(item));
423 }
424 } else {
425 return null; // DOM Nodes are not actually required; let someone else try the conversion
426 }
427 }
428
429 if (nodes.isEmpty() && !requireDOM) {
430 return null; // empty sequence supplied - try a different mapping
431 }
432 if (Node.class.isAssignableFrom(target)) {
433 if (nodes.size() != 1) {
434 throw new XPathException("Cannot convert XPath value to Java object: requires a single DOM Node" +
435 "but supplied value contains " + nodes.size() + " nodes");
436 }
437 return nodes.get(0);
438 // could fail if the node is of the wrong kind
439 } else if (target == NodeList.class) {
440 return new DOMNodeList(nodes);
441 } else if (target.isArray() && target.getComponentType() == Node.class) {
442 return nodes.toArray(new Node[0]);
443 } else if (target.isAssignableFrom(ArrayList.class)) {
444 return nodes;
445 } else if (target.isAssignableFrom(HashSet.class)) {
446 return new HashSet<>(nodes);
447 } else {
448 // after all this work, give up
449 return null;
450 }
451 }
452
453 /**
454 * Wrap a document node in the external object model in a document wrapper that implements
455 * the Saxon DocumentInfo interface. (However, if the supplied object is a wrapper for a Saxon
456 * NodeInfo object, then we <i>unwrap</i> it.
457 *
458 * @param node a node (any node) in the third party document
459 * @param baseURI the base URI of the node (supply "" if unknown)
460 * @param config the Saxon configuration (which among other things provides access to the NamePool)
461 * @return the wrapper, which must implement DocumentInfo
462 */
463
464 private TreeInfo wrapDocument(Object node, String baseURI, Configuration config) {
465 if (node instanceof DocumentOverNodeInfo) {
466 return (TreeInfo) ((DocumentOverNodeInfo) node).getUnderlyingNodeInfo();
467 }
468 if (node instanceof NodeOverNodeInfo) {
469 return ((NodeOverNodeInfo) node).getUnderlyingNodeInfo().getTreeInfo();
470 }
471 if (node instanceof org.w3c.dom.Node) {
472 if (((Node) node).getNodeType() == Node.DOCUMENT_NODE) {
473 Document doc = (org.w3c.dom.Document) node;
474 return new DocumentWrapper(doc, baseURI, config);
475 } else if (((Node) node).getNodeType() == Node.DOCUMENT_FRAGMENT_NODE) {
476 DocumentFragment doc = (org.w3c.dom.DocumentFragment) node;
477 return new DocumentWrapper(doc, baseURI, config);
478 } else {
479 Document doc = ((org.w3c.dom.Node) node).getOwnerDocument();
480 return new DocumentWrapper(doc, baseURI, config);
481 }
482 }
483 throw new IllegalArgumentException("Unknown node class " + node.getClass());
484 }
485
486 /**
487 * Wrap a node within the external object model in a node wrapper that implements the Saxon
488 * VirtualNode interface (which is an extension of NodeInfo)
489 *
490 * @param document the document wrapper, as a DocumentInfo object
491 * @param node the node to be wrapped. This must be a node within the document wrapped by the
492 * DocumentInfo provided in the first argument
493 * @return the wrapper for the node, as an instance of VirtualNode
494 */
495
496 private NodeInfo wrapNode(TreeInfo document, Object node) {
497 return ((DocumentWrapper) document).wrap((Node) node);
498 }
499
500
501 }
502