Debian Codegraph @

net/sf/saxon/dom/DOMSender.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.event.NamespaceReducer;
11 import net.sf.saxon.event.Receiver;
12 import net.sf.saxon.event.ReceiverOptions;
13 import net.sf.saxon.expr.parser.ExplicitLocation;
14 import net.sf.saxon.expr.parser.Location;
15 import net.sf.saxon.lib.NamespaceConstant;
16 import net.sf.saxon.om.FingerprintedQName;
17 import net.sf.saxon.om.NamespaceBinding;
18 import net.sf.saxon.om.NoNamespaceName;
19 import net.sf.saxon.om.NodeName;
20 import net.sf.saxon.trans.XPathException;
21 import net.sf.saxon.type.BuiltInAtomicType;
22 import net.sf.saxon.type.Type;
23 import net.sf.saxon.type.Untyped;
24 import org.w3c.dom.*;
25 import org.w3c.dom.CharacterData;
26
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.util.*;
30
31 /**
32 * DOMSender.java: pseudo-SAX driver for a DOM source document.
33 * This class takes an existing
34 * DOM Document and walks around it in a depth-first traversal,
35 * calling a Receiver to process the nodes as it does so
36 */
37
38 public class DOMSender {
39 private Receiver receiver;
40 protected Node root;
41 protected String systemId;
42 private Stack<List<NamespaceBinding>> namespaces = new Stack<>();
43 private Node currentNode;
44
45 /**
46 * Create a DOMSender that will send events representing the nodes in a tree
47 * to a nominated receiver
48 *
49 * @param startNode the root node of the tree to be send. Usually a document or element node.
50 * @param receiver the object to be notified of the resulting events. The supplied Receiver must
51 * be initialized with a PipelineConfiguration. The caller is responsible for opening
52 * and closing the Receiver.
53 */
54
55 public DOMSender(Node startNode, Receiver receiver) {
56 if (startNode == null) {
57 throw new NullPointerException("startNode");
58 }
59 if (receiver == null) {
60 throw new NullPointerException("receiver");
61 }
62 this.root = startNode;
63 this.receiver = new NamespaceReducer(receiver);
64 }
65
66 /**
67 * Set the systemId of the source document (which will also be
68 * used for the destination)
69 *
70 * @param systemId the systemId of the source document
71 */
72
73 public void setSystemId(String systemId) {
74 this.systemId = systemId;
75 }
76
77 /**
78 * Walk a tree (traversing the nodes depth first).
79 *
80 * @throws IllegalStateException if the
81 * start node is of a node kind other than document, document fragment, element, text,
82 * comment, or processing instruction (for example, if it is an attribute node).
83 * @throws net.sf.saxon.trans.XPathException
84 * On any error in the document
85 */
86
87 public void send() throws XPathException {
88 receiver.setSystemId(systemId);
89
90 //receiver.open();
91 final Location loc = ExplicitLocation.UNKNOWN_LOCATION;
92 switch (root.getNodeType()) {
93 case Node.DOCUMENT_NODE:
94 case Node.DOCUMENT_FRAGMENT_NODE:
95 receiver.startDocument(0);
96 sendUnparsedEntities();
97 walkNode(root);
98 receiver.endDocument();
99 break;
100 case Node.ELEMENT_NODE:
101 sendElement((Element) root);
102 break;
103 case Node.TEXT_NODE:
104 case Node.CDATA_SECTION_NODE:
105 receiver.characters(((CharacterData) root).getData(), loc, 0);
106 break;
107 case Node.COMMENT_NODE:
108 receiver.comment(((Comment) root).getData(), loc, 0);
109 break;
110 case Node.PROCESSING_INSTRUCTION_NODE:
111 receiver.processingInstruction(
112 ((ProcessingInstruction) root).getTarget(),
113 ((ProcessingInstruction) root).getData(), loc, 0);
114 break;
115 default:
116 throw new IllegalStateException("DOMSender: unsupported kind of start node (" + root.getNodeType() + ")");
117 }
118 //receiver.close();
119 }
120
121 private void sendUnparsedEntities() throws XPathException {
122 if (root instanceof Document) {
123 DocumentType docType = ((Document)root).getDoctype();
124 if (docType != null) {
125 NamedNodeMap map = docType.getEntities();
126 if (map != null) {
127 for (int i = 0; i < map.getLength(); i++) {
128 Entity e = (Entity) map.item(i);
129 if (e.getNotationName() != null) {
130 // it is an unparsed entity
131 String name = e.getNodeName();
132 String systemId = e.getSystemId();
133 try {
134 URI systemIdURI = new URI(systemId);
135 if (!systemIdURI.isAbsolute()) {
136 String base = root.getBaseURI();
137 if (base != null) {
138 systemIdURI = new URI(base).resolve(systemIdURI);
139 systemId = systemIdURI.toString();
140 } else {
141 // base URI unknown: return the relative URI as written
142 }
143 }
144 } catch (URISyntaxException err) {
145 // invalid URI: no action - return the "URI" as written
146 }
147 String publicId = e.getPublicId();
148 receiver.setUnparsedEntity(name, systemId, publicId);
149 }
150 }
151 }
152 }
153 }
154 }
155
156 /**
157 * Walk a tree starting from a particular element node. This has to make
158 * sure that all the namespace declarations in scope for the element are
159 * treated as if they were namespace declarations on the element itself.
160 *
161 * @param startNode the start element node from which the walk will start
162 * @throws net.sf.saxon.trans.XPathException
163 * if a dynamic error occurs
164 */
165
166 private void sendElement(Element startNode) throws XPathException {
167 List<Element> ancestors = new ArrayList<>();
168 List<NamespaceBinding> bindings = new ArrayList<>();
169 Node parent = startNode;
170 while (parent != null && parent.getNodeType() == Type.ELEMENT) {
171 ancestors.add((Element) parent);
172 parent = parent.getParentNode();
173 }
174 for (int i=ancestors.size()-1; i>=0; i--) {
175 gatherNamespaces(ancestors.get(i), bindings);
176 }
177 // Eliminate duplicate bindings. We need to take the last binding for each prefix. We can't leave this to
178 // the NamespaceReducer, because it does it the wrong way.
179 Map<String, String> distinctNamespaces = new HashMap<>();
180 for (NamespaceBinding nb : bindings) {
181 distinctNamespaces.put(nb.getPrefix(), nb.getURI());
182 }
183 if (distinctNamespaces.size() != bindings.size()) {
184 bindings = new ArrayList<>();
185 for (Map.Entry<String, String> entry : distinctNamespaces.entrySet()) {
186 bindings.add(new NamespaceBinding(entry.getKey(), entry.getValue()));
187 }
188 }
189 namespaces.push(bindings);
190 outputElement(startNode, true);
191 namespaces.pop();
192 }
193
194 /**
195 * Convert a lexical QName to a NodeName object encapsulating the prefix, local part, and namespace URI
196 * @param name the lexical QName
197 * @param useDefaultNS true for an element name, false for an attribute name
198 * @return the expanded node name
199 */
200
201 private NodeName getNodeName(String name, boolean useDefaultNS) {
202 int colon = name.indexOf(':');
203 if (colon < 0) {
204 if (useDefaultNS) {
205 String uri = getUriForPrefix("");
206 if (!uri.isEmpty()) {
207 return new FingerprintedQName("", uri, name);
208 }
209 }
210 return new NoNamespaceName(name);
211 } else {
212 String prefix = name.substring(0, colon);
213 String uri = getUriForPrefix(prefix);
214 if (uri == null) {
215 throw new IllegalStateException("Prefix " + prefix + " is not bound to any namespace");
216 }
217 return new FingerprintedQName(prefix, uri, name.substring(colon+1));
218 }
219 }
220
221 /**
222 * Walk an element of a document (traversing the children depth first)
223 *
224 * @param node The DOM Element object to walk
225 * @throws net.sf.saxon.trans.XPathException
226 * On any error in the document
227 */
228
229 private void walkNode(Node node) throws XPathException {
230 final Location loc = ExplicitLocation.UNKNOWN_LOCATION;
231 if (node.hasChildNodes()) {
232 NodeList nit = node.getChildNodes();
233 final int len = nit.getLength();
234 for (int i = 0; i < len; i++) {
235 Node child = nit.item(i);
236 currentNode = child;
237 switch (child.getNodeType()) {
238 case Node.DOCUMENT_NODE:
239 case Node.DOCUMENT_FRAGMENT_NODE:
240 break; // should not happen
241 case Node.ELEMENT_NODE:
242 Element element = (Element) child;
243 List<NamespaceBinding> bindings = new ArrayList<>();
244 namespaces.push(bindings);
245 gatherNamespaces(element, bindings);
246 outputElement(element, !bindings.isEmpty());
247 namespaces.pop();
248 break;
249 case Node.ATTRIBUTE_NODE: // have already dealt with attributes
250 break;
251 case Node.PROCESSING_INSTRUCTION_NODE:
252 receiver.processingInstruction(
253 ((ProcessingInstruction) child).getTarget(),
254 ((ProcessingInstruction) child).getData(),
255 loc, 0);
256 break;
257 case Node.COMMENT_NODE: {
258 String text = ((Comment) child).getData();
259 if (text != null) {
260 receiver.comment(text, loc, 0);
261 }
262 break;
263 }
264 case Node.TEXT_NODE:
265 case Node.CDATA_SECTION_NODE: {
266 String text = ((CharacterData) child).getData();
267 if (text != null) {
268 receiver.characters(text, loc, 0);
269 }
270 break;
271 }
272 case Node.ENTITY_REFERENCE_NODE:
273 walkNode(child);
274 break;
275 default:
276 break; // should not happen
277 }
278 }
279 }
280
281 }
282
283 /**
284 * While an event is being processed by the receiver, the DOM Node to which it relates
285 * is available as the value of currentNode
286 * @return the node currently being processed by the Receiver
287 */
288
289 public Node getCurrentNode() {
290 return currentNode;
291 }
292
293 /**
294 * Process an element node. On entry, the namespace bindings have already been added to the stack,
295 * and this method removes them from the stack before exit.
296 * @param element the element to be processed.
297 * @param hasNamespaceDeclarations true if the attributes of the element contain namespace declaration
298 * attributes (which the method then ignores)
299 * @throws XPathException if a dynamic error occurs
300 */
301
302 private void outputElement(Element element, boolean hasNamespaceDeclarations) throws XPathException {
303
304 NodeName name = getNodeName(element.getTagName(), true);
305 final Location loc = new ExplicitLocation(systemId, -1, -1);
306 receiver.startElement(name, Untyped.getInstance(), loc, 0);
307 for (NamespaceBinding ns : namespaces.peek()) {
308 receiver.namespace(ns, 0);
309 }
310
311 NamedNodeMap atts = element.getAttributes();
312 if (atts != null) {
313 final int len = atts.getLength();
314 for (int a2 = 0; a2 < len; a2++) {
315 Attr att = (Attr) atts.item(a2);
316 int props = att.isId() ? ReceiverOptions.IS_ID : 0;
317 String attname = att.getName();
318 if (hasNamespaceDeclarations && (attname.equals("xmlns") || attname.startsWith("xmlns:"))) {
319 // do nothing: namespace declarations have already been processed
320 } else {
321 //System.err.println("Processing attribute " + attname);
322 NodeName attNodeName = getNodeName(attname, false);
323
324 // Note, DOM gives no guarantee that the prefix and URI are actually consistent. For example,
325 // it's possible programmatically to construct attribute nodes that have a namespace URI but
326 // no prefix. We don't attempt to deal with such situations: garbage in, garbage out.
327
328 receiver.attribute(attNodeName, BuiltInAtomicType.UNTYPED_ATOMIC, att.getValue(), loc, props);
329 }
330 }
331 }
332 receiver.startContent();
333
334 walkNode(element);
335
336 receiver.endElement();
337 }
338
339 /**
340 * Get the namespace URI corresponding to a prefix. This is done by searching the stack of namespace
341 * declarations maintained by this method (It could be done using DOM level-3 interfaces, but we need
342 * to extract the namespace declarations anyway, so we can pass them down the receiver pipeline, so
343 * we may as well use our own information to stay in control).
344 * @param prefix the prefix: may be "" to represent the default namespace
345 * @return the corresponding namespace URI: may be "" to represent the null namespace.
346 * @throws IllegalStateException if there is no binding for the prefix (except that there
347 * is always a binding for the prefix "")
348 */
349
350 private String getUriForPrefix(String prefix) {
351 if (prefix.equals("xml")) {
352 return NamespaceConstant.XML;
353 }
354 for (int i=namespaces.size()-1; i>=0; i--) {
355 List<NamespaceBinding> localNamespaces = namespaces.get(i);
356 for (NamespaceBinding n : localNamespaces) {
357 if (n.getPrefix().equals(prefix)) {
358 return n.getURI();
359 }
360 }
361 }
362 if (prefix.equals("")) {
363 return "";
364 } else {
365 throw new IllegalStateException("No binding for namespace prefix " + prefix);
366 }
367 }
368
369 /**
370 * Collect all the namespace attributes declared locally on a given element.
371 *
372 * @param element The element whose namespace declarations are required
373 * @param list Namespace declarations are appended to the supplied list
374 */
375
376 private void gatherNamespaces(Element element, List<NamespaceBinding> list) {
377
378 // we can't rely on namespace declaration attributes being present -
379 // there may be undeclared namespace prefixes. So we
380 // declare all namespaces encountered, to be on the safe side.
381
382 try {
383 String prefix = element.getPrefix();
384 String uri = element.getNamespaceURI();
385 if (prefix == null) {
386 prefix = "";
387 }
388 if (uri == null) {
389 uri = "";
390 }
391
392 if (!(prefix.isEmpty() && uri.isEmpty())) {
393 list.add(new NamespaceBinding(prefix, uri));
394 }
395 } catch (Throwable err) {
396 // it must be a level 1 DOM
397 }
398
399 NamedNodeMap atts = element.getAttributes();
400
401 // Apparently the Oracle DOM returns null if there are no attributes:
402 if (atts == null) {
403 return;
404 }
405 int alen = atts.getLength();
406 for (int a1 = 0; a1 < alen; a1++) {
407 Attr att = (Attr) atts.item(a1);
408 String attname = att.getName();
409 boolean possibleNamespace = attname.startsWith("xmlns");
410 if (possibleNamespace && attname.length() == 5) {
411 String uri = att.getValue();
412 list.add(new NamespaceBinding("", uri));
413 } else if (possibleNamespace && attname.startsWith("xmlns:")) {
414 String prefix = attname.substring(6);
415 String uri = att.getValue();
416 list.add(new NamespaceBinding(prefix, uri));
417 } else if (attname.indexOf(':') >= 0) {
418 try {
419 String prefix = att.getPrefix();
420 String uri = att.getNamespaceURI();
421 list.add(new NamespaceBinding(prefix, uri));
422 } catch (Throwable err) {
423 // it must be a level 1 DOM
424 }
425 }
426 }
427 }
428
429 }
430