Debian Codegraph @

net/sf/saxon/dom/DOMNodeWrapper.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.lib.NamespaceConstant;
11 import net.sf.saxon.om.AxisInfo;
12 import net.sf.saxon.om.NamespaceBinding;
13 import net.sf.saxon.om.NodeInfo;
14 import net.sf.saxon.pattern.AnyNodeTest;
15 import net.sf.saxon.pattern.NameTest;
16 import net.sf.saxon.pattern.NodeTest;
17 import net.sf.saxon.tree.iter.AxisIterator;
18 import net.sf.saxon.tree.iter.LookaheadIterator;
19 import net.sf.saxon.tree.util.FastStringBuffer;
20 import net.sf.saxon.tree.util.Navigator;
21 import net.sf.saxon.tree.util.SteppingNavigator;
22 import net.sf.saxon.tree.util.SteppingNode;
23 import net.sf.saxon.tree.wrapper.AbstractNodeWrapper;
24 import net.sf.saxon.tree.wrapper.SiblingCountingNode;
25 import net.sf.saxon.type.Type;
26 import net.sf.saxon.type.UType;
27 import org.jetbrains.annotations.NotNull;
28 import org.w3c.dom.*;
29
30 import java.util.ArrayList;
31 import java.util.Arrays;
32
33
34 /**
35 * A node in the XML parse tree representing an XML element, character content, or attribute.
36 * This is the implementation of the NodeInfo interface used as a wrapper for DOM nodes.
37 * <p>Because the DOM is not thread-safe even when reading, and because Saxon-EE can spawn multiple
38 * threads that access the same input tree, all methods that invoke DOM methods are synchronized
39 * on the Document object.</p>
40 */
41
42 @SuppressWarnings({"SynchronizeOnNonFinalField"})
43 public class DOMNodeWrapper extends AbstractNodeWrapper implements SiblingCountingNode, SteppingNode<DOMNodeWrapper> {
44
45 protected Node node;
46 protected short nodeKind;
47 private DOMNodeWrapper parent; // null means unknown
48 protected DocumentWrapper docWrapper; // effectively final
49 protected int index; // -1 means unknown
50 protected int span = 1; // the number of adjacent text nodes wrapped by this NodeWrapper.
51 // If span>1, node will always be the first of a sequence of adjacent text nodes
52 private NamespaceBinding[] localNamespaces = null;
53
54 /**
55 * This constructor is protected: nodes should be created using the makeWrapper
56 * factory method
57 *
58 * @param node The DOM node to be wrapped
59 * @param docWrapper The wrapper for the Document node at the root of the DOM tree. Never null
60 * except in the case where we are creating the DocumentWrapper itself (which is a subclass).
61 * @param parent The DOMNodeWrapper that wraps the parent of this node. May be null if unknown.
62 * @param index Position of this node among its siblings, 0-based. May be -1 if unknown.
63 */
64 protected DOMNodeWrapper(Node node, DocumentWrapper docWrapper, /*@Nullable*/ DOMNodeWrapper parent, int index) {
65 this.node = node;
66 this.parent = parent;
67 this.index = index;
68 this.docWrapper = docWrapper;
69 }
70
71 /**
72 * Factory method to wrap a DOM node with a wrapper that implements the Saxon
73 * NodeInfo interface.
74 *
75 * @param node The DOM node
76 * @param docWrapper The wrapper for the containing Document node
77 * @return The new wrapper for the supplied node
78 * @throws NullPointerException if the node or the document wrapper are null
79 */
80 protected static DOMNodeWrapper makeWrapper(Node node, DocumentWrapper docWrapper) {
81 if (node == null) {
82 throw new NullPointerException("NodeWrapper#makeWrapper: Node must not be null");
83 }
84 if (docWrapper == null) {
85 throw new NullPointerException("NodeWrapper#makeWrapper: DocumentWrapper must not be null");
86 }
87 return makeWrapper(node, docWrapper, null, -1);
88 }
89
90 /**
91 * Factory method to wrap a DOM node with a wrapper that implements the Saxon
92 * NodeInfo interface.
93 *
94 * @param node The DOM node
95 * @param docWrapper The wrapper for the containing Document node *
96 * @param parent The wrapper for the parent of the JDOM node
97 * @param index The position of this node relative to its siblings
98 * @return The new wrapper for the supplied node
99 */
100
101 protected static DOMNodeWrapper makeWrapper(Node node, DocumentWrapper docWrapper,
102 /*@Nullable*/ DOMNodeWrapper parent, int index) {
103 DOMNodeWrapper wrapper;
104 switch (node.getNodeType()) {
105 case Node.DOCUMENT_NODE:
106 case Node.DOCUMENT_FRAGMENT_NODE:
107 wrapper = (DOMNodeWrapper)docWrapper.getRootNode();
108 if (wrapper == null) {
109 wrapper = new DOMNodeWrapper(node, docWrapper, parent, index);
110 wrapper.nodeKind = Type.DOCUMENT;
111 }
112 break;
113 case Node.ELEMENT_NODE:
114 wrapper = new DOMNodeWrapper(node, docWrapper, parent, index);
115 wrapper.nodeKind = Type.ELEMENT;
116 break;
117 case Node.ATTRIBUTE_NODE:
118 wrapper = new DOMNodeWrapper(node, docWrapper, parent, index);
119 wrapper.nodeKind = Type.ATTRIBUTE;
120 break;
121 case Node.TEXT_NODE:
122 wrapper = new DOMNodeWrapper(node, docWrapper, parent, index);
123 wrapper.nodeKind = Type.TEXT;
124 break;
125 case Node.CDATA_SECTION_NODE:
126 wrapper = new DOMNodeWrapper(node, docWrapper, parent, index);
127 wrapper.nodeKind = Type.TEXT;
128 break;
129 case Node.COMMENT_NODE:
130 wrapper = new DOMNodeWrapper(node, docWrapper, parent, index);
131 wrapper.nodeKind = Type.COMMENT;
132 break;
133 case Node.PROCESSING_INSTRUCTION_NODE:
134 wrapper = new DOMNodeWrapper(node, docWrapper, parent, index);
135 wrapper.nodeKind = Type.PROCESSING_INSTRUCTION;
136 break;
137 case Node.ENTITY_REFERENCE_NODE:
138 throw new IllegalStateException("DOM contains entity reference nodes, which Saxon does not support. The DOM should be built using the expandEntityReferences() option");
139
140 default:
141 throw new IllegalArgumentException("Unsupported node type in DOM! " + node.getNodeType() + " instance " + node);
142 }
143 wrapper.treeInfo = docWrapper;
144 return wrapper;
145 }
146
147 public DocumentWrapper getTreeInfo() {
148 return (DocumentWrapper)treeInfo;
149 }
150
151 /**
152 * Get the underlying DOM node, to implement the VirtualNode interface
153 */
154
155 public Node getUnderlyingNode() {
156 return node;
157 }
158
159 /**
160 * Return the kind of node.
161 *
162 * @return one of the values Node.ELEMENT, Node.TEXT, Node.ATTRIBUTE, etc.
163 */
164
165 public int getNodeKind() {
166 return nodeKind;
167 }
168
169 /**
170 * Determine whether this is the same node as another node.
171 * <p>Note: a.equals(b) if and only if generateId(a)==generateId(b)</p>
172 *
173 * @return true if this Node object and the supplied Node object represent the
174 * same node in the tree.
175 */
176
177 public boolean equals(Object other) {
178 if (!(other instanceof DOMNodeWrapper)) {
179 return false;
180 }
181 if (docWrapper.domLevel3) {
182 synchronized (docWrapper.docNode) {
183 return node.isSameNode(((DOMNodeWrapper) other).node);
184 }
185 } else {
186 DOMNodeWrapper ow = (DOMNodeWrapper) other;
187 return getNodeKind() == ow.getNodeKind() &&
188 equalOrNull(getLocalPart(), ow.getLocalPart()) && // redundant, but gives a quick exit
189 getSiblingPosition() == ow.getSiblingPosition() &&
190 getParent().equals(ow.getParent());
191 }
192 }
193
194 private boolean equalOrNull(String a, String b) {
195 return a==null ? b==null : a.equals(b);
196 }
197
198 /**
199 * Determine the relative position of this node and another node, in document order.
200 * The other node will always be in the same document.
201 *
202 * @param other The other node, whose position is to be compared with this node
203 * @return -1 if this node precedes the other node, +1 if it follows the other
204 * node, or 0 if they are the same node. (In this case, isSameNode() will always
205 * return true, and the two nodes will produce the same result for generateId())
206 */
207
208 public int compareOrder(NodeInfo other) {
209 // Use the DOM Level-3 compareDocumentPosition() method
210 if (other instanceof DOMNodeWrapper && docWrapper.domLevel3) {
211 if (equals(other)) {
212 return 0;
213 }
214 try {
215 synchronized (docWrapper.docNode) {
216 short relationship = node.compareDocumentPosition(((DOMNodeWrapper) other).node);
217 if ((relationship &
218 (Node.DOCUMENT_POSITION_PRECEDING | Node.DOCUMENT_POSITION_CONTAINS)) != 0) {
219 return +1;
220 } else if ((relationship &
221 (Node.DOCUMENT_POSITION_FOLLOWING | Node.DOCUMENT_POSITION_CONTAINED_BY)) != 0) {
222 return -1;
223 }
224 }
225 // otherwise use fallback implementation (e.g. nodes in different documents)
226 } catch (DOMException e) {
227 // can happen if nodes are from different DOM implementations.
228 // use fallback implementation
229 }
230 }
231
232 if (other instanceof SiblingCountingNode) {
233 return Navigator.compareOrder(this, (SiblingCountingNode) other);
234 } else {
235 // it's presumably a Namespace Node
236 return -other.compareOrder(this);
237 }
238 }
239
240 /**
241 * Get the value of the item as a CharSequence. This is in some cases more efficient than
242 * the version of the method that returns a String.
243 */
244
245 public CharSequence getStringValueCS() {
246 synchronized (docWrapper.docNode) {
247 switch (nodeKind) {
248 case Type.DOCUMENT:
249 case Type.ELEMENT:
250 NodeList children1 = node.getChildNodes();
251 FastStringBuffer sb1 = new FastStringBuffer(16);
252 expandStringValue(children1, sb1);
253 return sb1;
254
255 case Type.ATTRIBUTE:
256 return emptyIfNull(((Attr) node).getValue());
257
258 case Type.TEXT:
259 if (span == 1) {
260 return emptyIfNull(node.getNodeValue());
261 } else {
262 FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C64);
263 Node textNode = node;
264 for (int i = 0; i < span; i++) {
265 fsb.append(emptyIfNull(textNode.getNodeValue()));
266 textNode = textNode.getNextSibling();
267 }
268 return fsb.condense();
269 }
270
271 case Type.COMMENT:
272 case Type.PROCESSING_INSTRUCTION:
273 return emptyIfNull(node.getNodeValue());
274
275 default:
276 return "";
277 }
278 }
279 }
280
281 /**
282 * Treat a node value of null as an empty string.
283 *
284 * @param s the node value
285 * @return a zero-length string if s is null, otherwise s
286 */
287
288 private static String emptyIfNull(String s) {
289 return s == null ? "" : s;
290 }
291
292 public static void expandStringValue(NodeList list, FastStringBuffer sb) {
293 final int len = list.getLength();
294 for (int i = 0; i < len; i++) {
295 Node child = list.item(i);
296 switch (child.getNodeType()) {
297 case Node.ELEMENT_NODE:
298 expandStringValue(child.getChildNodes(), sb);
299 break;
300 case Node.COMMENT_NODE:
301 case Node.PROCESSING_INSTRUCTION_NODE:
302 break;
303 case Node.DOCUMENT_TYPE_NODE:
304 break;
305 default:
306 sb.append(emptyIfNull(child.getNodeValue()));
307 break;
308 }
309 }
310 }
311
312
313 /**
314 * Get the local part of the name of this node. This is the name after the ":" if any.
315 *
316 * @return the local part of the name. For an unnamed node, returns "".
317 */
318
319 public String getLocalPart() {
320 synchronized (docWrapper.docNode) {
321 switch (getNodeKind()) {
322 case Type.ELEMENT:
323 case Type.ATTRIBUTE:
324 return getLocalName(node);
325 case Type.PROCESSING_INSTRUCTION:
326 return node.getNodeName();
327 default:
328 return "";
329 }
330 }
331 }
332
333 /**
334 * Get the local name of a DOM element or attribute node.
335 *
336 * @param node the DOM element or attribute node
337 * @return the local name as defined in XDM
338 */
339
340 public static String getLocalName(Node node) {
341 String s = node.getLocalName();
342 if (s == null) {
343 // true if the node was created using a DOM level 1 method
344 String n = node.getNodeName();
345 int colon = n.indexOf(':');
346 if (colon >= 0) {
347 return n.substring(colon + 1);
348 }
349 return n;
350 } else {
351 return s;
352 }
353 }
354
355 /**
356 * Get the URI part of the name of this node. This is the URI corresponding to the
357 * prefix, or the URI of the default namespace if appropriate.
358 *
359 * @return The URI of the namespace of this node. For an unnamed node,
360 * or for a node with an empty prefix, return an empty
361 * string.
362 */
363
364 public String getURI() {
365 synchronized (docWrapper.docNode) {
366 if (nodeKind == Type.ELEMENT) {
367 return getElementURI((Element) node);
368 } else if (nodeKind == Type.ATTRIBUTE) {
369 return getAttributeURI((Attr) node);
370 }
371 return "";
372 }
373 }
374
375 private static String getElementURI(Element element) {
376
377 // The DOM methods getPrefix() and getNamespaceURI() do not always
378 // return the prefix and the URI; they both return null, unless the
379 // prefix and URI have been explicitly set in the node by using DOM
380 // level 2 interfaces. There's no obvious way of deciding whether
381 // an element whose name has no prefix is in the default namespace,
382 // other than searching for a default namespace declaration. So we have to
383 // be prepared to search.
384
385 // If getPrefix() and getNamespaceURI() are non-null, however,
386 // we can use the values.
387
388 String uri = element.getNamespaceURI();
389 if (uri != null) {
390 return uri;
391 }
392
393 // Otherwise we have to work it out the hard way...
394
395 String displayName = element.getNodeName();
396 int colon = displayName.indexOf(':');
397 String attName = colon < 0 ? "xmlns" : "xmlns:" + displayName.substring(0, colon);
398
399 if (attName.equals("xmlns:xml")) {
400 return NamespaceConstant.XML;
401 }
402
403 Node node = element;
404 do {
405 if (((Element) node).hasAttribute(attName)) {
406 return ((Element) node).getAttribute(attName);
407 }
408 node = node.getParentNode();
409 } while (node != null && node.getNodeType() == Node.ELEMENT_NODE);
410
411 if (colon < 0) {
412 return "";
413 } else {
414 throw new IllegalStateException("Undeclared namespace prefix in element name " + displayName + " in DOM input");
415 }
416
417 }
418
419
420 private static String getAttributeURI(Attr attr) {
421
422 String uri = attr.getNamespaceURI();
423 if (uri != null) {
424 return uri;
425 }
426
427 // Otherwise we have to work it out the hard way...
428
429 String displayName = attr.getNodeName();
430 int colon = displayName.indexOf(':');
431 if (colon < 0) {
432 return "";
433 }
434 String attName = "xmlns:" + displayName.substring(0, colon);
435
436 if (attName.equals("xmlns:xml")) {
437 return NamespaceConstant.XML;
438 }
439
440 Node node = attr.getOwnerElement();
441 do {
442 if (((Element) node).hasAttribute(attName)) {
443 return ((Element) node).getAttribute(attName);
444 }
445 node = node.getParentNode();
446 } while (node != null && node.getNodeType() == Node.ELEMENT_NODE);
447
448 throw new IllegalStateException("Undeclared namespace prefix in attribute name " + displayName + " in DOM input");
449
450 }
451
452
453 /**
454 * Get the prefix of the name of the node. This is defined only for elements and attributes.
455 * If the node has no prefix, or for other kinds of node, return a zero-length string.
456 *
457 * @return The prefix of the name of the node.
458 */
459
460 public String getPrefix() {
461 synchronized (docWrapper.docNode) {
462 int kind = getNodeKind();
463 if (kind == Type.ELEMENT || kind == Type.ATTRIBUTE) {
464 String name = node.getNodeName();
465 int colon = name.indexOf(':');
466 if (colon < 0) {
467 return "";
468 } else {
469 return name.substring(0, colon);
470 }
471 }
472 return "";
473 }
474 }
475
476 /**
477 * Get the display name of this node. For elements and attributes this is [prefix:]localname.
478 * For unnamed nodes, it is an empty string.
479 *
480 * @return The display name of this node.
481 * For a node with no name, return an empty string.
482 */
483
484 public String getDisplayName() {
485 switch (nodeKind) {
486 case Type.ELEMENT:
487 case Type.ATTRIBUTE:
488 case Type.PROCESSING_INSTRUCTION:
489 synchronized (docWrapper.docNode) {
490 return node.getNodeName();
491 }
492 default:
493 return "";
494
495 }
496 }
497
498 /**
499 * Get the NodeInfo object representing the parent of this node
500 */
501
502 public DOMNodeWrapper getParent() {
503 if (parent == null) {
504 synchronized (docWrapper.docNode) {
505 switch (getNodeKind()) {
506 case Type.ATTRIBUTE:
507 parent = makeWrapper(((Attr) node).getOwnerElement(), docWrapper);
508 break;
509 default:
510 Node p = node.getParentNode();
511 if (p == null) {
512 return null;
513 } else {
514 parent = makeWrapper(p, docWrapper);
515 }
516 }
517 }
518 }
519 return parent;
520 }
521
522 /**
523 * Get the index position of this node among its siblings (starting from 0).
524 * In the case of a text node that maps to several adjacent siblings in the DOM,
525 * the numbering actually refers to the position of the underlying DOM nodes;
526 * thus the sibling position for the text node is that of the first DOM node
527 * to which it relates, and the numbering of subsequent XPath nodes is not necessarily
528 * consecutive.
529 * <p>Despite the name, this method also returns a meaningful result for attribute
530 * nodes; it returns the position of the attribute among the attributes of its
531 * parent element, when they are listed in document order.</p>
532 */
533
534 public int getSiblingPosition() {
535 if (index == -1) {
536 synchronized (docWrapper.docNode) {
537 switch (nodeKind) {
538 case Type.ELEMENT:
539 case Type.TEXT:
540 case Type.COMMENT:
541 case Type.PROCESSING_INSTRUCTION:
542 int ix = 0;
543 Node start = node;
544 while (true) {
545 start = start.getPreviousSibling();
546 if (start == null) {
547 index = ix;
548 return ix;
549 }
550 ix++;
551 }
552 case Type.ATTRIBUTE:
553 ix = 0;
554 AxisIterator iter = parent.iterateAxis(AxisInfo.ATTRIBUTE);
555 while (true) {
556 NodeInfo n = iter.next();
557 if (n == null || Navigator.haveSameName(this, n)) {
558 index = ix;
559 return ix;
560 }
561 ix++;
562 }
563
564 case Type.NAMESPACE:
565 ix = 0;
566 iter = parent.iterateAxis(AxisInfo.NAMESPACE);
567 while (true) {
568 NodeInfo n = iter.next();
569 if (n == null || Navigator.haveSameName(this, n)) {
570 index = ix;
571 return ix;
572 }
573 ix++;
574 }
575 default:
576 index = 0;
577 return index;
578 }
579 }
580 }
581 return index;
582 }
583
584 @Override
585 protected AxisIterator iterateAttributes(NodeTest nodeTest) {
586 AxisIterator iter = new AttributeEnumeration(this);
587 if (nodeTest != AnyNodeTest.getInstance()) {
588 iter = new Navigator.AxisFilter(iter, nodeTest);
589 }
590 return iter;
591 }
592
593 @Override
594 protected AxisIterator iterateChildren(NodeTest nodeTest) {
595 boolean elementOnly = nodeTest.getUType() == UType.ELEMENT;
596 AxisIterator iter = new Navigator.EmptyTextFilter(
597 new ChildEnumeration(this, true, true, elementOnly));
598 if (nodeTest != AnyNodeTest.getInstance()) {
599 iter = new Navigator.AxisFilter(iter, nodeTest);
600 }
601 return iter;
602 }
603
604 @Override
605 protected AxisIterator iterateSiblings(NodeTest nodeTest, boolean forwards) {
606 boolean elementOnly = nodeTest.getUType() == UType.ELEMENT;
607 AxisIterator iter = new Navigator.EmptyTextFilter(
608 new ChildEnumeration(this, false, forwards, elementOnly));
609 if (nodeTest != AnyNodeTest.getInstance()) {
610 iter = new Navigator.AxisFilter(iter, nodeTest);
611 }
612 return iter;
613 }
614
615 @Override
616 protected AxisIterator iterateDescendants(NodeTest nodeTest, boolean includeSelf) {
617 return new SteppingNavigator.DescendantAxisIterator(this, includeSelf, nodeTest);
618 }
619
620 /**
621 * Get the string value of a given attribute of this node
622 *
623 * @param uri the namespace URI of the attribute name. Supply the empty string for an attribute
624 * that is in no namespace
625 * @param local the local part of the attribute name.
626 * @return the attribute value if it exists, or null if it does not exist. Always returns null
627 * if this node is not an element.
628 * @since 9.4
629 */
630 public String getAttributeValue(/*@NotNull*/ String uri, /*@NotNull*/ String local) {
631 NameTest test = new NameTest(Type.ATTRIBUTE, uri, local, getNamePool());
632 AxisIterator iterator = iterateAxis(AxisInfo.ATTRIBUTE, test);
633 NodeInfo attribute = iterator.next();
634 if (attribute == null) {
635 return null;
636 } else {
637 return attribute.getStringValue();
638 }
639 }
640
641 /**
642 * Get the root node - always a document node with this tree implementation
643 *
644 * @return the NodeInfo representing the containing document
645 */
646
647 public NodeInfo getRoot() {
648 return docWrapper.getRootNode();
649 }
650
651 /**
652 * Determine whether the node has any children.
653 * <p>Note: the result is equivalent to
654 * <code>getEnumeration(Axis.CHILD, AnyNodeTest.getInstance()).hasNext()</code></p>
655 */
656
657 public boolean hasChildNodes() {
658 // An attribute node has child text nodes
659 synchronized (docWrapper.docNode) {
660 return node.getNodeType() != Node.ATTRIBUTE_NODE && node.hasChildNodes();
661 }
662 }
663
664 /**
665 * Get a character string that uniquely identifies this node.
666 * Note: a.isSameNode(b) if and only if generateId(a)==generateId(b)
667 *
668 * @param buffer a buffer to contain a string that uniquely identifies this node, across all
669 * documents
670 */
671
672 public void generateId(FastStringBuffer buffer) {
673 Navigator.appendSequentialKey(this, buffer, true);
674 }
675
676 /**
677 * Get all namespace undeclarations and undeclarations defined on this element.
678 *
679 * @param buffer If this is non-null, and the result array fits in this buffer, then the result
680 * may overwrite the contents of this array, to avoid the cost of allocating a new array on the heap.
681 * @return An array of integers representing the namespace declarations and undeclarations present on
682 * this element. For a node other than an element, return null. Otherwise, the returned array is a
683 * sequence of namespace codes, whose meaning may be interpreted by reference to the name pool. The
684 * top half word of each namespace code represents the prefix, the bottom half represents the URI.
685 * If the bottom half is zero, then this is a namespace undeclaration rather than a declaration.
686 * The XML namespace is never included in the list. If the supplied array is larger than required,
687 * then the first unused entry will be set to -1.
688 * <p>For a node other than an element, the method returns null.</p>
689 */
690
691 public NamespaceBinding[] getDeclaredNamespaces(NamespaceBinding[] buffer) {
692 synchronized (docWrapper.docNode) {
693 if (node.getNodeType() == Node.ELEMENT_NODE) {
694 if (localNamespaces != null) {
695 return localNamespaces;
696 }
697 Element elem = (Element) node;
698 NamedNodeMap atts = elem.getAttributes();
699
700 if (atts == null) {
701 localNamespaces = NamespaceBinding.EMPTY_ARRAY;
702 return NamespaceBinding.EMPTY_ARRAY;
703 }
704 int count = 0;
705 final int attsLen = atts.getLength();
706 for (int i = 0; i < attsLen; i++) {
707 Attr att = (Attr) atts.item(i);
708 String attName = att.getName();
709 if (attName.equals("xmlns")) {
710 count++;
711 } else if (attName.startsWith("xmlns:")) {
712 count++;
713 }
714 }
715 if (count == 0) {
716 localNamespaces = NamespaceBinding.EMPTY_ARRAY;
717 return NamespaceBinding.EMPTY_ARRAY;
718 } else {
719 NamespaceBinding[] result = buffer == null || count > buffer.length ? new NamespaceBinding[count] : buffer;
720 int n = 0;
721 for (int i = 0; i < attsLen; i++) {
722 Attr att = (Attr) atts.item(i);
723 String attName = att.getName();
724 if (attName.equals("xmlns")) {
725 String prefix = "";
726 String uri = att.getValue();
727 result[n++] = new NamespaceBinding(prefix, uri);
728 } else if (attName.startsWith("xmlns:")) {
729 String prefix = attName.substring(6);
730 String uri = att.getValue();
731 result[n++] = new NamespaceBinding(prefix, uri);
732 }
733 }
734 if (count < result.length) {
735 result[count] = null;
736 }
737 localNamespaces = Arrays.copyOf(result, result.length);
738 return result;
739 }
740 } else {
741 return null;
742 }
743 }
744 }
745
746
747 /**
748 * Determine whether this node has the is-id property
749 *
750 * @return true if the node is an ID
751 */
752
753 public boolean isId() {
754 synchronized (docWrapper.docNode) {
755 return (node instanceof Attr) && ((Attr) node).isId();
756 }
757 }
758
759 public DOMNodeWrapper getNextSibling() {
760 synchronized (docWrapper.docNode) {
761 Node currNode = node;
762 for (int i=0; i<span; i++) {
763 currNode = currNode.getNextSibling();
764 }
765 if (currNode != null) {
766 short type = currNode.getNodeType();
767 if (type == Node.DOCUMENT_TYPE_NODE) {
768 currNode = currNode.getNextSibling();
769 } else if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) {
770 return spannedWrapper(currNode);
771 }
772 return makeWrapper(currNode, docWrapper);
773 }
774 return null;
775 }
776 }
777
778 @NotNull
779 private DOMNodeWrapper spannedWrapper(Node currNode) {
780 Node currText = currNode;
781 int thisSpan = 1;
782 while (true) {
783 currText = currText.getNextSibling();
784 if (currText != null && (currText.getNodeType() == Node.TEXT_NODE || currText.getNodeType() == Node.CDATA_SECTION_NODE)) {
785 thisSpan++;
786 } else {
787 break;
788 }
789 }
790 DOMNodeWrapper spannedText = makeWrapper(currNode, docWrapper);
791 spannedText.span = thisSpan;
792 return spannedText;
793 }
794
795
796 public DOMNodeWrapper getFirstChild() {
797 synchronized (docWrapper.docNode) {
798 Node currNode = node.getFirstChild();
799 if (currNode != null) {
800 if (currNode.getNodeType() == Node.DOCUMENT_TYPE_NODE) {
801 currNode = currNode.getNextSibling();
802 }
803 if (currNode.getNodeType() == Node.TEXT_NODE || currNode.getNodeType() == Node.CDATA_SECTION_NODE) {
804 return spannedWrapper(currNode);
805 }
806 return makeWrapper(currNode, docWrapper);
807 }
808 return null;
809 }
810 }
811
812 public DOMNodeWrapper getPreviousSibling() {
813 synchronized (docWrapper.docNode) {
814 Node currNode = node.getPreviousSibling();
815 if (currNode != null) {
816 short type = currNode.getNodeType();
817 if (type == Node.DOCUMENT_TYPE_NODE) {
818 return null;
819 } else if (type == Node.TEXT_NODE || type == Node.CDATA_SECTION_NODE) {
820 int span = 1;
821 while (true) {
822 Node prev = currNode.getPreviousSibling();
823 if (prev != null && (prev.getNodeType() == Node.TEXT_NODE || prev.getNodeType() == Node.CDATA_SECTION_NODE)) {
824 span++;
825 currNode = prev;
826 } else {
827 break;
828 }
829 }
830 DOMNodeWrapper wrapper = makeWrapper(currNode, docWrapper);
831 wrapper.span = span;
832 return wrapper;
833 }
834 return makeWrapper(currNode, docWrapper);
835 }
836 return null;
837 }
838 }
839
840 public DOMNodeWrapper getSuccessorElement(DOMNodeWrapper anchor, String uri, String local) {
841 synchronized (docWrapper.docNode) {
842 Node stop = anchor == null ? null : anchor.node;
843 Node next = node;
844 do {
845 next = getSuccessorNode(next, stop);
846 } while (next != null &&
847 !(next.getNodeType() == Node.ELEMENT_NODE &&
848 (local == null || local.equals(getLocalName(next))) &&
849 (uri == null || uri.equals(getElementURI((Element) next)))));
850 if (next == null) {
851 return null;
852 } else {
853 return makeWrapper(next, docWrapper);
854 }
855 }
856 }
857
858 /**
859 * Get the following DOM node in an iteration of a subtree
860 *
861 * @param start the start DOM node
862 * @param anchor the DOM node marking the root of the subtree within which navigation takes place (may be null)
863 * @return the next DOM node in document order after the start node, excluding attributes and namespaces
864 */
865
866 private static Node getSuccessorNode(Node start, Node anchor) {
867 if (start.hasChildNodes()) {
868 return start.getFirstChild();
869 }
870 if (anchor != null && start.isSameNode(anchor)) {
871 return null;
872 }
873 Node p = start;
874 while (true) {
875 Node s = p.getNextSibling();
876 if (s != null) {
877 return s;
878 }
879 p = p.getParentNode();
880 if (p == null || (anchor != null && p.isSameNode(anchor))) {
881 return null;
882 }
883 }
884 }
885
886 private final class AttributeEnumeration implements AxisIterator, LookaheadIterator<NodeInfo> {
887
888 private ArrayList<Node> attList = new ArrayList<>(10);
889 private int ix = 0;
890 private DOMNodeWrapper start;
891 private DOMNodeWrapper current;
892
893 public AttributeEnumeration(DOMNodeWrapper start) {
894 synchronized (start.docWrapper.docNode) {
895 this.start = start;
896 NamedNodeMap atts = start.node.getAttributes();
897 if (atts != null) {
898 final int attsLen = atts.getLength();
899 for (int i = 0; i < attsLen; i++) {
900 String name = atts.item(i).getNodeName();
901 if (!(name.startsWith("xmlns") &&
902 (name.length() == 5 || name.charAt(5) == ':'))) {
903 attList.add(atts.item(i));
904 }
905 }
906 }
907 ix = 0;
908 }
909 }
910
911 public boolean hasNext() {
912 return ix < attList.size();
913 }
914
915 public NodeInfo next() {
916 if (ix >= attList.size()) {
917 return null;
918 }
919 current = makeWrapper(attList.get(ix), docWrapper, start, ix);
920 ix++;
921 return current;
922 }
923
924 /**
925 * Get properties of this iterator, as a bit-significant integer.
926 *
927 * @return the properties of this iterator. This will be some combination of
928 * properties such as {@link #GROUNDED}, {@link #LAST_POSITION_FINDER},
929 * and {@link #LOOKAHEAD}. It is always
930 * acceptable to return the value zero, indicating that there are no known special properties.
931 * It is acceptable for the properties of the iterator to change depending on its state.
932 */
933
934 public int getProperties() {
935 return LOOKAHEAD;
936 }
937 }
938
939
940 /**
941 * The class ChildEnumeration handles not only the child axis, but also the
942 * following-sibling and preceding-sibling axes. It can also iterate the children
943 * of the start node in reverse order, something that is needed to support the
944 * preceding and preceding-or-ancestor axes (the latter being used by xsl:number)
945 */
946
947 private final class ChildEnumeration implements AxisIterator, LookaheadIterator<NodeInfo> {
948
949 private DOMNodeWrapper start;
950 private DOMNodeWrapper commonParent;
951 private boolean downwards; // iterate children of start node (not siblings)
952 private boolean forwards; // iterate in document order (not reverse order)
953 private boolean elementsOnly;
954 NodeList childNodes;
955 private int childNodesLength;
956 private int ix; // index of the current DOM node within childNodes;
957 // in the case of adjacent text nodes, index of the first in the group
958 private int currentSpan; // number of DOM nodes mapping to the current XPath node
959
960 /**
961 * Create an iterator over the children or siblings of a given node
962 *
963 * @param start the start node for the iteration
964 * @param downwards if true, iterate over the children of the start node; if false, iterate
965 * over the following or preceding siblings
966 * @param forwards if true, iterate in forwards document order; if false, iterate in reverse
967 * document order
968 * @param elementsOnly if true, retrieve element nodes only; if false, retrieve all nodes
969 */
970 public ChildEnumeration(DOMNodeWrapper start,
971 boolean downwards, boolean forwards, boolean elementsOnly) {
972 synchronized (start.docWrapper.docNode) {
973 this.start = start;
974 this.downwards = downwards;
975 this.forwards = forwards;
976 this.elementsOnly = elementsOnly;
977 currentSpan = 1;
978
979 if (downwards) {
980 commonParent = start;
981 } else {
982 commonParent = start.getParent();
983 }
984
985 childNodes = commonParent.node.getChildNodes();
986 childNodesLength = childNodes.getLength();
987 if (downwards) {
988 currentSpan = 1;
989 if (forwards) {
990 ix = -1; // just before first
991 } else {
992 ix = childNodesLength; // just after last
993 }
994 } else {
995 ix = start.getSiblingPosition(); // at current node
996 currentSpan = start.span;
997 }
998 }
999 }
1000
1001 /**
1002 * Starting with ix positioned at a node, which in the last in a span, calculate the length
1003 * of the span, that is the number of DOM nodes mapped to this XPath node.
1004 *
1005 * @return the number of nodes spanned
1006 */
1007
1008 private int skipPrecedingTextNodes() {
1009 int count = 0;
1010 while (ix >= count) {
1011 Node node = childNodes.item(ix - count);
1012 short kind = node.getNodeType();
1013 if (kind == Node.TEXT_NODE || kind == Node.CDATA_SECTION_NODE) {
1014 count++;
1015 } else {
1016 break;
1017 }
1018 }
1019 return count == 0 ? 1 : count;
1020 }
1021
1022 /**
1023 * Starting with ix positioned at a node, which in the first in a span, calculate the length
1024 * of the span, that is the number of DOM nodes mapped to this XPath node.
1025 *
1026 * @return the number of nodes spanned
1027 */
1028
1029 private int skipFollowingTextNodes() {
1030 int count = 0;
1031 int pos = ix;
1032 final int len = childNodesLength;
1033 while (pos < len) {
1034 Node node = childNodes.item(pos);
1035 short kind = node.getNodeType();
1036 if (kind == Node.TEXT_NODE || kind == Node.CDATA_SECTION_NODE) {
1037 pos++;
1038 count++;
1039 } else {
1040 break;
1041 }
1042 }
1043 return count == 0 ? 1 : count;
1044 }
1045
1046 public boolean hasNext() {
1047 if (forwards) {
1048 return ix + currentSpan < childNodesLength;
1049 } else {
1050 return ix > 0;
1051 }
1052 }
1053
1054 /*@Nullable*/
1055 public NodeInfo next() {
1056 synchronized(start.docWrapper.docNode) {
1057 while (true) {
1058 if (forwards) {
1059 ix += currentSpan;
1060 if (ix >= childNodesLength) {
1061 return null;
1062 } else {
1063 currentSpan = skipFollowingTextNodes();
1064 Node currentDomNode = childNodes.item(ix);
1065 switch (currentDomNode.getNodeType()) {
1066 case Node.DOCUMENT_TYPE_NODE:
1067 continue;
1068 case Node.ELEMENT_NODE:
1069 break;
1070 default:
1071 if (elementsOnly) {
1072 continue;
1073 } else {
1074 break;
1075 }
1076 }
1077 DOMNodeWrapper wrapper = makeWrapper(currentDomNode, docWrapper, commonParent, ix);
1078 wrapper.span = currentSpan;
1079 return wrapper;
1080 }
1081 } else {
1082 ix--;
1083 if (ix < 0) {
1084 return null;
1085 } else {
1086 currentSpan = skipPrecedingTextNodes();
1087 ix -= currentSpan - 1;
1088 Node currentDomNode = childNodes.item(ix);
1089 switch (currentDomNode.getNodeType()) {
1090 case Node.DOCUMENT_TYPE_NODE:
1091 continue;
1092 case Node.ELEMENT_NODE:
1093 break;
1094 default:
1095 if (elementsOnly) {
1096 continue;
1097 } else {
1098 break;
1099 }
1100 }
1101 DOMNodeWrapper wrapper = makeWrapper(currentDomNode, docWrapper, commonParent, ix);
1102 wrapper.span = currentSpan;
1103 return wrapper;
1104 }
1105 }
1106 }
1107 }
1108 }
1109
1110 /**
1111 * Get properties of this iterator, as a bit-significant integer.
1112 *
1113 * @return the properties of this iterator. This will be some combination of
1114 * properties such as {@link #GROUNDED}, {@link #LAST_POSITION_FINDER},
1115 * and {@link #LOOKAHEAD}. It is always
1116 * acceptable to return the value zero, indicating that there are no known special properties.
1117 * It is acceptable for the properties of the iterator to change depending on its state.
1118 */
1119
1120 public int getProperties() {
1121 return LOOKAHEAD;
1122 }
1123
1124 } // end of class ChildEnumeration
1125
1126
1127 }
1128