Debian Codegraph @

rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XmlNode.java

raw symbols SCIP
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 package org.mozilla.javascript.xmlimpl;
6
7 import java.io.Serializable;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.List;
11 import java.util.Map;
12
13 import org.mozilla.javascript.Undefined;
14 import org.w3c.dom.Attr;
15 import org.w3c.dom.Document;
16 import org.w3c.dom.Element;
17 import org.w3c.dom.NamedNodeMap;
18 import org.w3c.dom.Node;
19 import org.w3c.dom.NodeList;
20 import org.w3c.dom.ProcessingInstruction;
21 import org.w3c.dom.UserDataHandler;
22
23 class XmlNode implements Serializable {
24 private static final String XML_NAMESPACES_NAMESPACE_URI = "http://www.w3.org/2000/xmlns/";
25
26 private static final String USER_DATA_XMLNODE_KEY = XmlNode.class.getName();
27
28 private static final boolean DOM_LEVEL_3 = true;
29
30 private static XmlNode getUserData(Node node) {
31 if (DOM_LEVEL_3) {
32 return (XmlNode)node.getUserData(USER_DATA_XMLNODE_KEY);
33 }
34 return null;
35 }
36
37 private static void setUserData(Node node, XmlNode wrap) {
38 if (DOM_LEVEL_3) {
39 node.setUserData(USER_DATA_XMLNODE_KEY, wrap, wrap.events);
40 }
41 }
42
43 private static XmlNode createImpl(Node node) {
44 if (node instanceof Document) throw new IllegalArgumentException();
45 XmlNode rv = null;
46 if (getUserData(node) == null) {
47 rv = new XmlNode();
48 rv.dom = node;
49 setUserData(node, rv);
50 } else {
51 rv = getUserData(node);
52 }
53 return rv;
54 }
55
56 static XmlNode newElementWithText(XmlProcessor processor, XmlNode reference, XmlNode.QName qname, String value) {
57 if (reference instanceof org.w3c.dom.Document) throw new IllegalArgumentException("Cannot use Document node as reference");
58 Document document = null;
59 if (reference != null) {
60 document = reference.dom.getOwnerDocument();
61 } else {
62 document = processor.newDocument();
63 }
64 Node referenceDom = (reference != null) ? reference.dom : null;
65 Namespace ns = qname.getNamespace();
66 Element e = (ns == null || ns.getUri().length() == 0)
67 ? document.createElementNS(null, qname.getLocalName())
68 : document.createElementNS(ns.getUri(),
69 qname.qualify(referenceDom));
70 if (value != null) {
71 e.appendChild(document.createTextNode(value));
72 }
73 return XmlNode.createImpl(e);
74 }
75
76 static XmlNode createText(XmlProcessor processor, String value) {
77 return createImpl( processor.newDocument().createTextNode(value) );
78 }
79
80 static XmlNode createElementFromNode(Node node) {
81 if (node instanceof Document)
82 node = ((Document) node).getDocumentElement();
83 return createImpl(node);
84 }
85
86 static XmlNode createElement(XmlProcessor processor, String namespaceUri, String xml) throws org.xml.sax.SAXException {
87 return createImpl( processor.toXml(namespaceUri, xml) );
88 }
89
90 static XmlNode createEmpty(XmlProcessor processor) {
91 return createText(processor, "");
92 }
93
94 private static XmlNode copy(XmlNode other) {
95 return createImpl( other.dom.cloneNode(true) );
96 }
97
98 private static final long serialVersionUID = 1L;
99
100 private UserDataHandler events = new XmlNodeUserDataHandler();
101
102 private Node dom;
103
104 private XML xml;
105
106 private XmlNode() {
107 }
108
109 String debug() {
110 XmlProcessor raw = new XmlProcessor();
111 raw.setIgnoreComments(false);
112 raw.setIgnoreProcessingInstructions(false);
113 raw.setIgnoreWhitespace(false);
114 raw.setPrettyPrinting(false);
115 return raw.ecmaToXmlString(this.dom);
116 }
117
118 @Override
119 public String toString() {
120 return "XmlNode: type=" + dom.getNodeType() + " dom=" + dom.toString();
121 }
122
123 XML getXml() {
124 return xml;
125 }
126
127 void setXml(XML xml) {
128 this.xml = xml;
129 }
130
131 int getChildCount() {
132 return this.dom.getChildNodes().getLength();
133 }
134
135 XmlNode parent() {
136 Node domParent = dom.getParentNode();
137 if (domParent instanceof Document) return null;
138 if (domParent == null) return null;
139 return createImpl(domParent);
140 }
141
142 int getChildIndex() {
143 if (this.isAttributeType()) return -1;
144 if (parent() == null) return -1;
145 org.w3c.dom.NodeList siblings = this.dom.getParentNode().getChildNodes();
146 for (int i=0; i<siblings.getLength(); i++) {
147 if (siblings.item(i) == dom) {
148 return i;
149 }
150 }
151 // Either the parent is -1 or one of the this node's parent's children is this node.
152 throw new RuntimeException("Unreachable.");
153 }
154
155 void removeChild(int index) {
156 this.dom.removeChild( this.dom.getChildNodes().item(index) );
157 }
158
159 String toXmlString(XmlProcessor processor) {
160 return processor.ecmaToXmlString(this.dom);
161 }
162
163 String ecmaValue() {
164 // TODO See ECMA 357 Section 9.1
165 if (isTextType()) {
166 return ((org.w3c.dom.Text)dom).getData();
167 } else if (isAttributeType()) {
168 return ((org.w3c.dom.Attr)dom).getValue();
169 } else if (isProcessingInstructionType()) {
170 return ((org.w3c.dom.ProcessingInstruction)dom).getData();
171 } else if (isCommentType()) {
172 return ((org.w3c.dom.Comment)dom).getNodeValue();
173 } else if (isElementType()) {
174 throw new RuntimeException("Unimplemented ecmaValue() for elements.");
175 } else {
176 throw new RuntimeException("Unimplemented for node " + dom);
177 }
178 }
179
180 void deleteMe() {
181 if (dom instanceof Attr) {
182 Attr attr = (Attr)this.dom;
183 attr.getOwnerElement().getAttributes().removeNamedItemNS(attr.getNamespaceURI(), attr.getLocalName());
184 } else {
185 if (this.dom.getParentNode() != null) {
186 this.dom.getParentNode().removeChild(this.dom);
187 } else {
188 // This case can be exercised at least when executing the regression
189 // tests under https://bugzilla.mozilla.org/show_bug.cgi?id=354145
190 }
191 }
192 }
193
194 void normalize() {
195 this.dom.normalize();
196 }
197
198 void insertChildAt(int index, XmlNode node) {
199 Node parent = this.dom;
200 Node child = parent.getOwnerDocument().importNode( node.dom, true );
201 if (parent.getChildNodes().getLength() < index) {
202 // TODO Check ECMA for what happens here
203 throw new IllegalArgumentException("index=" + index + " length=" + parent.getChildNodes().getLength());
204 }
205 if (parent.getChildNodes().getLength() == index) {
206 parent.appendChild(child);
207 } else {
208 parent.insertBefore(child, parent.getChildNodes().item(index));
209 }
210 }
211
212 void insertChildrenAt(int index, XmlNode[] nodes) {
213 for (int i=0; i<nodes.length; i++) {
214 insertChildAt(index+i, nodes[i]);
215 }
216 }
217
218 XmlNode getChild(int index) {
219 Node child = dom.getChildNodes().item(index);
220 return createImpl(child);
221 }
222
223 // Helper method for XML.hasSimpleContent()
224 boolean hasChildElement() {
225 org.w3c.dom.NodeList nodes = this.dom.getChildNodes();
226 for (int i=0; i<nodes.getLength(); i++) {
227 if (nodes.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) return true;
228 }
229 return false;
230 }
231
232 boolean isSameNode(XmlNode other) {
233 // TODO May need to be changed if we allow XmlNode to refer to several Node objects
234 return this.dom == other.dom;
235 }
236
237 private String toUri(String ns) {
238 return (ns == null) ? "" : ns;
239 }
240
241 private void addNamespaces(Namespaces rv, Element element) {
242 if (element == null) throw new RuntimeException("element must not be null");
243 String myDefaultNamespace = toUri(element.lookupNamespaceURI(null));
244 String parentDefaultNamespace = "";
245 if (element.getParentNode() != null) {
246 parentDefaultNamespace = toUri(element.getParentNode().lookupNamespaceURI(null));
247 }
248 if (!myDefaultNamespace.equals(parentDefaultNamespace) || !(element.getParentNode() instanceof Element) ) {
249 rv.declare(Namespace.create("", myDefaultNamespace));
250 }
251 NamedNodeMap attributes = element.getAttributes();
252 for (int i=0; i<attributes.getLength(); i++) {
253 Attr attr = (Attr)attributes.item(i);
254 if (attr.getPrefix() != null && attr.getPrefix().equals("xmlns")) {
255 rv.declare(Namespace.create(attr.getLocalName(), attr.getValue()));
256 }
257 }
258 }
259
260 private Namespaces getAllNamespaces() {
261 Namespaces rv = new Namespaces();
262
263 Node target = this.dom;
264 if (target instanceof Attr) {
265 target = ((Attr)target).getOwnerElement();
266 }
267 while(target != null) {
268 if (target instanceof Element) {
269 addNamespaces(rv, (Element)target);
270 }
271 target = target.getParentNode();
272 }
273 // Fallback in case no namespace was declared
274 rv.declare(Namespace.create("", ""));
275 return rv;
276 }
277
278 Namespace[] getInScopeNamespaces() {
279 Namespaces rv = getAllNamespaces();
280 return rv.getNamespaces();
281 }
282
283 Namespace[] getNamespaceDeclarations() {
284 // ECMA357 13.4.4.24
285 if (this.dom instanceof Element) {
286 Namespaces rv = new Namespaces();
287 addNamespaces( rv, (Element)this.dom );
288 return rv.getNamespaces();
289 } else {
290 return new Namespace[0];
291 }
292 }
293
294 Namespace getNamespaceDeclaration(String prefix) {
295 if (prefix.equals("") && dom instanceof Attr) {
296 // Default namespaces do not apply to attributes; see XML Namespaces section 5.2
297 return Namespace.create("", "");
298 }
299 Namespaces rv = getAllNamespaces();
300 return rv.getNamespace(prefix);
301 }
302
303 Namespace getNamespaceDeclaration() {
304 if (dom.getPrefix() == null) return getNamespaceDeclaration("");
305 return getNamespaceDeclaration(dom.getPrefix());
306 }
307
308 static class XmlNodeUserDataHandler implements UserDataHandler, Serializable {
309 private static final long serialVersionUID = 4666895518900769588L;
310
311 public void handle(short operation, String key, Object data, Node src, Node dest) {
312 }
313 }
314
315 private static class Namespaces {
316 private Map<String,String> map = new HashMap<String,String>();
317 private Map<String,String> uriToPrefix = new HashMap<String,String>();
318
319 Namespaces() {
320 }
321
322 void declare(Namespace n) {
323 if (map.get(n.prefix) == null) {
324 map.put(n.prefix, n.uri);
325 }
326 // TODO I think this is analogous to the other way, but have not really thought it through ... should local scope
327 // matter more than outer scope?
328 if (uriToPrefix.get(n.uri) == null) {
329 uriToPrefix.put(n.uri, n.prefix);
330 }
331 }
332
333 Namespace getNamespaceByUri(String uri) {
334 if (uriToPrefix.get(uri) == null) return null;
335 return Namespace.create(uri, uriToPrefix.get(uri));
336 }
337
338 Namespace getNamespace(String prefix) {
339 if (map.get(prefix) == null) return null;
340 return Namespace.create(prefix, map.get(prefix));
341 }
342
343 Namespace[] getNamespaces() {
344 ArrayList<Namespace> rv = new ArrayList<Namespace>();
345 for (String prefix: map.keySet()) {
346 String uri = map.get(prefix);
347 Namespace n = Namespace.create(prefix, uri);
348 if (!n.isEmpty()) {
349 rv.add(n);
350 }
351 }
352 return rv.toArray(new Namespace[rv.size()]);
353 }
354 }
355
356 final XmlNode copy() {
357 return copy( this );
358 }
359
360 // Returns whether this node is capable of being a parent
361 final boolean isParentType() {
362 return isElementType();
363 }
364
365 final boolean isTextType() {
366 return dom.getNodeType() == Node.TEXT_NODE || dom.getNodeType() == Node.CDATA_SECTION_NODE;
367 }
368
369 final boolean isAttributeType() {
370 return dom.getNodeType() == Node.ATTRIBUTE_NODE;
371 }
372
373 final boolean isProcessingInstructionType() {
374 return dom.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE;
375 }
376
377 final boolean isCommentType() {
378 return dom.getNodeType() == Node.COMMENT_NODE;
379 }
380
381 final boolean isElementType() {
382 return dom.getNodeType() == Node.ELEMENT_NODE;
383 }
384
385 final void renameNode(QName qname) {
386 this.dom = dom.getOwnerDocument().renameNode(dom, qname.getNamespace().getUri(), qname.qualify(dom));
387 }
388
389 void invalidateNamespacePrefix() {
390 if (!(dom instanceof Element)) throw new IllegalStateException();
391 String prefix = this.dom.getPrefix();
392 QName after = QName.create(this.dom.getNamespaceURI(), this.dom.getLocalName(), null);
393 renameNode(after);
394 NamedNodeMap attrs = this.dom.getAttributes();
395 for (int i=0; i<attrs.getLength(); i++) {
396 if (attrs.item(i).getPrefix().equals(prefix)) {
397 createImpl( attrs.item(i) ).renameNode( QName.create(attrs.item(i).getNamespaceURI(), attrs.item(i).getLocalName(), null) );
398 }
399 }
400 }
401
402 private void declareNamespace(Element e, String prefix, String uri) {
403 if (prefix.length() > 0) {
404 e.setAttributeNS(XML_NAMESPACES_NAMESPACE_URI, "xmlns:" + prefix, uri);
405 } else {
406 e.setAttribute("xmlns", uri);
407 }
408 }
409
410 void declareNamespace(String prefix, String uri) {
411 if (!(dom instanceof Element)) throw new IllegalStateException();
412 if (dom.lookupNamespaceURI(uri) != null && dom.lookupNamespaceURI(uri).equals(prefix)) {
413 // do nothing
414 } else {
415 Element e = (Element)dom;
416 declareNamespace(e, prefix, uri);
417 }
418 }
419
420 private Namespace getDefaultNamespace() {
421 String prefix = "";
422 String uri = (dom.lookupNamespaceURI(null) == null) ? "" : dom.lookupNamespaceURI(null);
423 return Namespace.create(prefix, uri);
424 }
425
426 private String getExistingPrefixFor(Namespace namespace) {
427 if (getDefaultNamespace().getUri().equals(namespace.getUri())) {
428 return "";
429 }
430 return dom.lookupPrefix(namespace.getUri());
431 }
432
433 private Namespace getNodeNamespace() {
434 String uri = dom.getNamespaceURI();
435 String prefix = dom.getPrefix();
436 if (uri == null) uri = "";
437 if (prefix == null) prefix = "";
438 return Namespace.create(prefix, uri);
439 }
440
441 Namespace getNamespace() {
442 return getNodeNamespace();
443 }
444
445 void removeNamespace(Namespace namespace) {
446 Namespace current = getNodeNamespace();
447
448 // Do not remove in-use namespace
449 if (namespace.is(current)) return;
450 NamedNodeMap attrs = this.dom.getAttributes();
451 for (int i=0; i<attrs.getLength(); i++) {
452 XmlNode attr = XmlNode.createImpl(attrs.item(i));
453 if (namespace.is(attr.getNodeNamespace())) return;
454 }
455
456 // TODO I must confess I am not sure I understand the spec fully. See ECMA357 13.4.4.31
457 String existingPrefix = getExistingPrefixFor(namespace);
458 if (existingPrefix != null) {
459 if (namespace.isUnspecifiedPrefix()) {
460 // we should remove any namespace with this URI from scope; we do this by declaring a namespace with the same
461 // prefix as the existing prefix and setting its URI to the default namespace
462 declareNamespace(existingPrefix, getDefaultNamespace().getUri());
463 } else {
464 if (existingPrefix.equals(namespace.getPrefix())) {
465 declareNamespace(existingPrefix, getDefaultNamespace().getUri());
466 }
467 }
468 } else {
469 // the argument namespace is not declared in this scope, so do nothing.
470 }
471 }
472
473 private void setProcessingInstructionName(String localName) {
474 org.w3c.dom.ProcessingInstruction pi = (ProcessingInstruction)this.dom;
475 // We cannot set the node name; Document.renameNode() only supports elements and attributes. So we replace it
476 pi.getParentNode().replaceChild(
477 pi,
478 pi.getOwnerDocument().createProcessingInstruction(localName, pi.getData())
479 );
480 }
481
482 final void setLocalName(String localName) {
483 if (dom instanceof ProcessingInstruction) {
484 setProcessingInstructionName(localName);
485 } else {
486 String prefix = dom.getPrefix();
487 if (prefix == null) prefix = "";
488 this.dom = dom.getOwnerDocument().renameNode(dom, dom.getNamespaceURI(), QName.qualify(prefix, localName));
489 }
490 }
491
492 final QName getQname() {
493 String uri = (dom.getNamespaceURI()) == null ? "" : dom.getNamespaceURI();
494 String prefix = (dom.getPrefix() == null) ? "" : dom.getPrefix();
495 return QName.create( uri, dom.getLocalName(), prefix );
496 }
497
498 void addMatchingChildren(XMLList result, XmlNode.Filter filter) {
499 Node node = this.dom;
500 NodeList children = node.getChildNodes();
501 for(int i=0; i<children.getLength(); i++) {
502 Node childnode = children.item(i);
503 XmlNode child = XmlNode.createImpl(childnode);
504 if (filter.accept(childnode)) {
505 result.addToList(child);
506 }
507 }
508 }
509
510 XmlNode[] getMatchingChildren(Filter filter) {
511 ArrayList<XmlNode> rv = new ArrayList<XmlNode>();
512 NodeList nodes = this.dom.getChildNodes();
513 for (int i=0; i<nodes.getLength(); i++) {
514 Node node = nodes.item(i);
515 if (filter.accept(node)) {
516 rv.add(createImpl(node));
517 }
518 }
519 return rv.toArray(new XmlNode[rv.size()]);
520 }
521
522 XmlNode[] getAttributes() {
523 NamedNodeMap attrs = this.dom.getAttributes();
524 // TODO Or could make callers handle null?
525 if (attrs == null) throw new IllegalStateException("Must be element.");
526 XmlNode[] rv = new XmlNode[attrs.getLength()];
527 for (int i=0; i<attrs.getLength(); i++) {
528 rv[i] = createImpl( attrs.item(i) );
529 }
530 return rv;
531 }
532
533 String getAttributeValue() {
534 return ((Attr)dom).getValue();
535 }
536
537 void setAttribute(QName name, String value) {
538 if (!(dom instanceof Element)) throw new IllegalStateException("Can only set attribute on elements.");
539 name.setAttribute( (Element)dom, value );
540 }
541
542 void replaceWith(XmlNode other) {
543 Node replacement = other.dom;
544 if (replacement.getOwnerDocument() != this.dom.getOwnerDocument()) {
545 replacement = this.dom.getOwnerDocument().importNode(replacement, true);
546 }
547 this.dom.getParentNode().replaceChild(replacement, this.dom);
548 }
549
550 String ecmaToXMLString(XmlProcessor processor) {
551 if (this.isElementType()) {
552 Element copy = (Element)this.dom.cloneNode(true);
553 Namespace[] inScope = this.getInScopeNamespaces();
554 for (int i=0; i<inScope.length; i++) {
555 declareNamespace(copy, inScope[i].getPrefix(), inScope[i].getUri());
556 }
557 return processor.ecmaToXmlString(copy);
558 } else {
559 return processor.ecmaToXmlString(dom);
560 }
561 }
562
563 static class Namespace implements Serializable {
564
565 /**
566 * Serial version id for Namespace with fields prefix and uri
567 */
568 private static final long serialVersionUID = 4073904386884677090L;
569
570 static Namespace create(String prefix, String uri) {
571 if (prefix == null) {
572 throw new IllegalArgumentException(
573 "Empty string represents default namespace prefix");
574 }
575 if (uri == null) {
576 throw new IllegalArgumentException(
577 "Namespace may not lack a URI");
578 }
579 Namespace rv = new Namespace();
580 rv.prefix = prefix;
581 rv.uri = uri;
582 return rv;
583 }
584
585 static Namespace create(String uri) {
586 Namespace rv = new Namespace();
587 rv.uri = uri;
588
589 // Avoid null prefix for "" namespace
590 if (uri == null || uri.length() == 0) {
591 rv.prefix = "";
592 }
593
594 return rv;
595 }
596
597 static final Namespace GLOBAL = create("", "");
598
599 private String prefix;
600 private String uri;
601
602 private Namespace() {
603 }
604
605 @Override
606 public String toString() {
607 if (prefix == null) return "XmlNode.Namespace [" + uri + "]";
608 return "XmlNode.Namespace [" + prefix + "{" + uri + "}]";
609 }
610
611 boolean isUnspecifiedPrefix() {
612 return prefix == null;
613 }
614
615 boolean is(Namespace other) {
616 return this.prefix != null && other.prefix != null && this.prefix.equals(other.prefix) && this.uri.equals(other.uri);
617 }
618
619 boolean isEmpty() {
620 return prefix != null && prefix.equals("") && uri.equals("");
621 }
622
623 boolean isDefault() {
624 return prefix != null && prefix.equals("");
625 }
626
627 boolean isGlobal() {
628 return uri != null && uri.equals("");
629 }
630
631 // Called by QName
632 // TODO Move functionality from QName lookupPrefix to here
633 private void setPrefix(String prefix) {
634 if (prefix == null) throw new IllegalArgumentException();
635 this.prefix = prefix;
636 }
637
638 String getPrefix() {
639 return prefix;
640 }
641
642 String getUri() {
643 return uri;
644 }
645 }
646
647 // TODO Where is this class used? No longer using it in QName implementation
648 static class QName implements Serializable {
649 private static final long serialVersionUID = -6587069811691451077L;
650
651 static QName create(Namespace namespace, String localName) {
652 // A null namespace indicates a wild-card match for any namespace
653 // A null localName indicates "*" from the point of view of ECMA357
654 if (localName != null && localName.equals("*")) throw new RuntimeException("* is not valid localName");
655 QName rv = new QName();
656 rv.namespace = namespace;
657 rv.localName = localName;
658 return rv;
659 }
660
661 /** @deprecated */
662 @Deprecated
663 static QName create(String uri, String localName, String prefix) {
664 return create(Namespace.create(prefix, uri), localName);
665 }
666
667 static String qualify(String prefix, String localName) {
668 if (prefix == null) throw new IllegalArgumentException("prefix must not be null");
669 if (prefix.length() > 0) return prefix + ":" + localName;
670 return localName;
671 }
672
673 private Namespace namespace;
674 private String localName;
675
676 private QName() {
677 }
678
679 @Override
680 public String toString() {
681 return "XmlNode.QName [" + localName + "," + namespace + "]";
682 }
683
684 private boolean equals(String one, String two) {
685 if (one == null && two == null) return true;
686 if (one == null || two == null) return false;
687 return one.equals(two);
688 }
689
690 private boolean namespacesEqual(Namespace one, Namespace two) {
691 if (one == null && two == null) return true;
692 if (one == null || two == null) return false;
693 return equals(one.getUri(), two.getUri());
694 }
695
696 final boolean equals(QName other) {
697 if (!namespacesEqual(this.namespace, other.namespace)) return false;
698 if (!equals(this.localName, other.localName)) return false;
699 return true;
700 }
701
702 @Override
703 public boolean equals(Object obj) {
704 if(!(obj instanceof QName)) {
705 return false;
706 }
707 return equals((QName)obj);
708 }
709
710 @Override
711 public int hashCode() {
712 return localName == null ? 0 : localName.hashCode();
713 }
714
715 void lookupPrefix(org.w3c.dom.Node node) {
716 if (node == null) throw new IllegalArgumentException("node must not be null");
717 String prefix = node.lookupPrefix(namespace.getUri());
718 if (prefix == null) {
719 // check to see if we match the default namespace
720 String defaultNamespace = node.lookupNamespaceURI(null);
721 if (defaultNamespace == null) defaultNamespace = "";
722 String nodeNamespace = namespace.getUri();
723 if (nodeNamespace.equals(defaultNamespace)) {
724 prefix = "";
725 }
726 }
727 int i = 0;
728 while(prefix == null) {
729 String generatedPrefix = "e4x_" + i++;
730 String generatedUri = node.lookupNamespaceURI(generatedPrefix);
731 if (generatedUri == null) {
732 prefix = generatedPrefix;
733 org.w3c.dom.Node top = node;
734 while(top.getParentNode() != null && top.getParentNode() instanceof org.w3c.dom.Element) {
735 top = top.getParentNode();
736 }
737 ((org.w3c.dom.Element)top).setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + prefix, namespace.getUri());
738 }
739 }
740 namespace.setPrefix(prefix);
741 }
742
743 String qualify(org.w3c.dom.Node node) {
744 if (namespace.getPrefix() == null) {
745 if (node != null) {
746 lookupPrefix(node);
747 } else {
748 if (namespace.getUri().equals("")) {
749 namespace.setPrefix("");
750 } else {
751 // TODO I am not sure this is right, but if we are creating a standalone node, I think we can set the
752 // default namespace on the node itself and not worry about setting a prefix for that namespace.
753 namespace.setPrefix("");
754 }
755 }
756 }
757 return qualify(namespace.getPrefix(), localName);
758 }
759
760 void setAttribute(org.w3c.dom.Element element, String value) {
761 if (namespace.getPrefix() == null) lookupPrefix(element);
762 element.setAttributeNS(namespace.getUri(), qualify(namespace.getPrefix(), localName), value);
763 }
764
765 Namespace getNamespace() {
766 return namespace;
767 }
768
769 String getLocalName() {
770 return localName;
771 }
772 }
773
774 static class InternalList implements Serializable {
775 private static final long serialVersionUID = -3633151157292048978L;
776 private List<XmlNode> list;
777
778 InternalList() {
779 list = new ArrayList<XmlNode>();
780 }
781
782 private void _add(XmlNode n) {
783 list.add(n);
784 }
785
786 XmlNode item(int index) {
787 return list.get(index);
788 }
789
790 void remove(int index) {
791 list.remove(index);
792 }
793
794 void add(InternalList other) {
795 for (int i=0; i<other.length(); i++) {
796 _add(other.item(i));
797 }
798 }
799
800 void add(InternalList from, int startInclusive, int endExclusive) {
801 for (int i=startInclusive; i<endExclusive; i++) {
802 _add(from.item(i));
803 }
804 }
805
806 void add(XmlNode node) {
807 _add(node);
808 }
809
810 /* TODO: was marked deprecated by original author */
811 void add(XML xml) {
812 _add(xml.getAnnotation());
813 }
814
815 /* TODO: was marked deprecated by original author */
816 void addToList(Object toAdd) {
817 if (toAdd instanceof Undefined) {
818 // Missing argument do nothing...
819 return;
820 }
821
822 if (toAdd instanceof XMLList) {
823 XMLList xmlSrc = (XMLList)toAdd;
824 for (int i = 0; i < xmlSrc.length(); i++) {
825 this._add((xmlSrc.item(i)).getAnnotation());
826 }
827 } else if (toAdd instanceof XML) {
828 this._add(((XML)(toAdd)).getAnnotation());
829 } else if (toAdd instanceof XmlNode) {
830 this._add((XmlNode)toAdd);
831 }
832 }
833
834 int length() {
835 return list.size();
836 }
837 }
838
839 static abstract class Filter {
840 static final Filter COMMENT = new Filter() {
841 @Override
842 boolean accept(Node node) {
843 return node.getNodeType() == Node.COMMENT_NODE;
844 }
845 };
846 static final Filter TEXT = new Filter() {
847 @Override
848 boolean accept(Node node) {
849 return node.getNodeType() == Node.TEXT_NODE;
850 }
851 };
852 static Filter PROCESSING_INSTRUCTION(final XMLName name) {
853 return new Filter() {
854 @Override
855 boolean accept(Node node) {
856 if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
857 ProcessingInstruction pi = (ProcessingInstruction)node;
858 return name.matchesLocalName(pi.getTarget());
859 }
860 return false;
861 }
862 };
863 }
864 static Filter ELEMENT = new Filter() {
865 @Override
866 boolean accept(Node node) {
867 return node.getNodeType() == Node.ELEMENT_NODE;
868 }
869 };
870 static Filter TRUE = new Filter() {
871 @Override
872 boolean accept(Node node) {
873 return true;
874 }
875 };
876 abstract boolean accept(Node node);
877 }
878
879 // Support experimental Java interface
880 org.w3c.dom.Node toDomNode() {
881 return this.dom;
882 }
883 }