net.sf.saxon.option.jdom.JDOMNodeWrapper Maven / Gradle / Ivy
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2015 Saxonica Limited.
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package net.sf.saxon.option.jdom;
import net.sf.saxon.lib.NamespaceConstant;
import net.sf.saxon.om.AxisInfo;
import net.sf.saxon.om.NamespaceBinding;
import net.sf.saxon.om.NodeInfo;
import net.sf.saxon.pattern.AnyNodeTest;
import net.sf.saxon.pattern.NodeKindTest;
import net.sf.saxon.pattern.NodeTest;
import net.sf.saxon.tree.iter.*;
import net.sf.saxon.tree.util.FastStringBuffer;
import net.sf.saxon.tree.util.Navigator;
import net.sf.saxon.tree.wrapper.AbstractNodeWrapper;
import net.sf.saxon.tree.wrapper.SiblingCountingNode;
import net.sf.saxon.type.Type;
import net.sf.saxon.type.UType;
import org.jdom.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* A node in the XML parse tree representing an XML element, character content, or attribute.
* This is the implementation of the NodeInfo interface used as a wrapper for JDOM nodes.
*
* @author Michael H. Kay
*/
public class JDOMNodeWrapper extends AbstractNodeWrapper implements SiblingCountingNode {
protected Object node; // the JDOM node to which this XPath node is mapped; or a List of
// adjacent text nodes
protected short nodeKind;
/*@Nullable*/ private JDOMNodeWrapper parent; // null means unknown
protected int index; // -1 means unknown
/**
* This constructor is protected: nodes should be created using the wrap
* factory method on the DocumentWrapper class
*
* @param node The JDOM node to be wrapped
* @param parent The NodeWrapper that wraps the parent of this node
* @param index Position of this node among its siblings
*/
protected JDOMNodeWrapper(Object node, JDOMNodeWrapper parent, int index) {
this.node = node;
this.parent = parent;
this.index = index;
}
/**
* Factory method to wrap a JDOM node with a wrapper that implements the Saxon
* NodeInfo interface.
*
* @param node The JDOM node
* @param docWrapper The wrapper for the Document containing this node
* @return The new wrapper for the supplied node
*/
protected static JDOMNodeWrapper makeWrapper(Object node, JDOMDocumentWrapper docWrapper) {
return makeWrapper(node, docWrapper, null, -1);
}
/**
* Factory method to wrap a JDOM node with a wrapper that implements the Saxon
* NodeInfo interface.
*
* @param node The JDOM node
* @param docWrapper The wrapper for the Document containing this node
* @param parent The wrapper for the parent of the JDOM node
* @param index The position of this node relative to its siblings
* @return The new wrapper for the supplied node
*/
protected static JDOMNodeWrapper makeWrapper(Object node, JDOMDocumentWrapper docWrapper,
JDOMNodeWrapper parent, int index) {
JDOMNodeWrapper wrapper;
if (node instanceof Document) {
wrapper = (JDOMNodeWrapper)docWrapper.getRootNode();
if (wrapper == null) {
wrapper = new JDOMNodeWrapper(node, parent, index);
wrapper.nodeKind = Type.DOCUMENT;
}
} else if (node instanceof Element) {
wrapper = new JDOMNodeWrapper(node, parent, index);
wrapper.nodeKind = Type.ELEMENT;
} else if (node instanceof Attribute) {
wrapper = new JDOMNodeWrapper(node, parent, index);
wrapper.nodeKind = Type.ATTRIBUTE;
} else if (node instanceof String || node instanceof Text) {
wrapper = new JDOMNodeWrapper(node, parent, index);
wrapper.nodeKind = Type.TEXT;
} else if (node instanceof Comment) {
wrapper = new JDOMNodeWrapper(node, parent, index);
wrapper.nodeKind = Type.COMMENT;
} else if (node instanceof ProcessingInstruction) {
wrapper = new JDOMNodeWrapper(node, parent, index);
wrapper.nodeKind = Type.PROCESSING_INSTRUCTION;
} else if (node instanceof Namespace) {
throw new IllegalArgumentException("Cannot wrap JDOM namespace objects");
} else {
throw new IllegalArgumentException("Bad node type in JDOM! " + node.getClass() + " instance " + node.toString());
}
wrapper.treeInfo = docWrapper;
return wrapper;
}
public JDOMDocumentWrapper getTreeInfo() {
return (JDOMDocumentWrapper)treeInfo;
}
/**
* Get the underlying JDOM node, to implement the VirtualNode interface
*/
public Object getUnderlyingNode() {
if (node instanceof List) {
return ((List) node).get(0);
} else {
return node;
}
}
/**
* Return the type of node.
*
* @return one of the values Node.ELEMENT, Node.TEXT, Node.ATTRIBUTE, etc.
*/
public int getNodeKind() {
return nodeKind;
}
/**
* Determine the relative position of this node and another node, in document order.
* The other node will always be in the same document.
*
* @param other The other node, whose position is to be compared with this node
* @return -1 if this node precedes the other node, +1 if it follows the other
* node, or 0 if they are the same node. (In this case, isSameNode() will always
* return true, and the two nodes will produce the same result for generateId())
*/
public int compareOrder(NodeInfo other) {
if (other instanceof SiblingCountingNode) {
return Navigator.compareOrder(this, (SiblingCountingNode) other);
} else {
// it must be a namespace node
return -other.compareOrder(this);
}
}
/**
* Get the value of the item as a CharSequence. This is in some cases more efficient than
* the version of the method that returns a String.
*/
public CharSequence getStringValueCS() {
if (node instanceof List) {
// This wrapper is mapped to a list of adjacent text nodes
List nodes = (List) node;
FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C64);
for (Object textNode : nodes) {
fsb.append(getStringValue(textNode));
}
return fsb;
} else {
return getStringValue(node);
}
}
/**
* Supporting method to get the string value of a node
*
* @param node the JDOM node
* @return the XPath string value of the node
*/
private static String getStringValue(Object node) {
if (node instanceof Document) {
List children1 = ((Document) node).getContent();
FastStringBuffer sb1 = new FastStringBuffer(FastStringBuffer.C256);
expandStringValue(children1, sb1);
return sb1.toString();
} else if (node instanceof Element) {
return ((Element) node).getValue();
} else if (node instanceof Attribute) {
return ((Attribute) node).getValue();
} else if (node instanceof Text) {
return ((Text) node).getText();
} else if (node instanceof String) {
return (String) node;
} else if (node instanceof Comment) {
return ((Comment) node).getText();
} else if (node instanceof ProcessingInstruction) {
return ((ProcessingInstruction) node).getData();
} else if (node instanceof Namespace) {
return ((Namespace) node).getURI();
} else {
return "";
}
}
/**
* Get the string values of all the nodes in a list, concatenating the values into
* a supplied string buffer
*
* @param list the list containing the nodes
* @param sb the StringBuffer to contain the result
*/
private static void expandStringValue(List list, FastStringBuffer sb) {
for (Object obj : list) {
if (obj instanceof Element) {
sb.append(((Element) obj).getValue());
} else if (obj instanceof Text) {
sb.append(((Text) obj).getText());
} else if (obj instanceof EntityRef) {
throw new IllegalStateException("Unexpanded entity in JDOM tree");
} else if (obj instanceof DocType) {
// do nothing: can happen in JDOM beta 10
} else {
throw new AssertionError("Unknown JDOM node type");
}
}
}
/**
* Get the local part of the name of this node. This is the name after the ":" if any.
*
* @return the local part of the name. For an unnamed node, returns "".
*/
public String getLocalPart() {
switch (nodeKind) {
case Type.ELEMENT:
return ((Element) node).getName();
case Type.ATTRIBUTE:
return ((Attribute) node).getName();
case Type.TEXT:
case Type.COMMENT:
case Type.DOCUMENT:
return "";
case Type.PROCESSING_INSTRUCTION:
return ((ProcessingInstruction) node).getTarget();
case Type.NAMESPACE:
return ((Namespace) node).getPrefix();
default:
return null;
}
}
/**
* Get the prefix part of the name of this node. This is the name before the ":" if any.
* (Note, this method isn't required as part of the NodeInfo interface.)
*
* @return the prefix part of the name. For an unnamed node, return an empty string.
*/
public String getPrefix() {
switch (nodeKind) {
case Type.ELEMENT:
return ((Element) node).getNamespacePrefix();
case Type.ATTRIBUTE:
return ((Attribute) node).getNamespacePrefix();
default:
return "";
}
}
/**
* Get the URI part of the name of this node. This is the URI corresponding to the
* prefix, or the URI of the default namespace if appropriate.
*
* @return The URI of the namespace of this node. For an unnamed node,
* or for a node with an empty prefix, return an empty
* string.
*/
public String getURI() {
switch (nodeKind) {
case Type.ELEMENT:
return ((Element) node).getNamespaceURI();
case Type.ATTRIBUTE:
return ((Attribute) node).getNamespaceURI();
default:
return "";
}
}
/**
* Get the display name of this node. For elements and attributes this is [prefix:]localname.
* For unnamed nodes, it is an empty string.
*
* @return The display name of this node.
* For a node with no name, return an empty string.
*/
public String getDisplayName() {
switch (nodeKind) {
case Type.ELEMENT:
return ((Element) node).getQualifiedName();
case Type.ATTRIBUTE:
return ((Attribute) node).getQualifiedName();
case Type.PROCESSING_INSTRUCTION:
case Type.NAMESPACE:
return getLocalPart();
default:
return "";
}
}
/**
* Get the NodeInfo object representing the parent of this node
*/
public NodeInfo getParent() {
if (parent == null) {
if (node instanceof Element) {
if (((Element) node).isRootElement()) {
parent = makeWrapper(((Element) node).getDocument(), getTreeInfo());
} else {
parent = makeWrapper(((Element) node).getParent(), getTreeInfo());
}
} else if (node instanceof Text) {
parent = makeWrapper(((Text) node).getParent(), getTreeInfo());
} else if (node instanceof Comment) {
parent = makeWrapper(((Comment) node).getParent(), getTreeInfo());
} else if (node instanceof ProcessingInstruction) {
parent = makeWrapper(((ProcessingInstruction) node).getParent(), getTreeInfo());
} else if (node instanceof Attribute) {
parent = makeWrapper(((Attribute) node).getParent(), getTreeInfo());
} else if (node instanceof Document) {
parent = null;
} else if (node instanceof Namespace) {
throw new UnsupportedOperationException("Cannot find parent of JDOM namespace node");
} else {
throw new IllegalStateException("Unknown JDOM node type " + node.getClass());
}
}
return parent;
}
/**
* Get the index position of this node among its siblings (starting from 0)
* In the case of a text node that maps to several adjacent siblings in the JDOM,
* the numbering actually refers to the position of the underlying JDOM nodes;
* thus the sibling position for the text node is that of the first JDOM node
* to which it relates, and the numbering of subsequent XPath nodes is not necessarily
* consecutive.
*/
public int getSiblingPosition() {
if (index == -1) {
int ix = 0;
getParent();
AxisIterator iter;
switch (nodeKind) {
case Type.ELEMENT:
case Type.TEXT:
case Type.COMMENT:
case Type.PROCESSING_INSTRUCTION:
iter = parent.iterateAxis(AxisInfo.CHILD);
break;
case Type.ATTRIBUTE:
iter = parent.iterateAxis(AxisInfo.ATTRIBUTE);
break;
case Type.NAMESPACE:
iter = parent.iterateAxis(AxisInfo.NAMESPACE);
break;
default:
index = 0;
return index;
}
while (true) {
NodeInfo n = (NodeInfo) iter.next();
if (n == null) {
break;
}
if (n.isSameNodeInfo(this)) {
index = ix;
return index;
}
if (((JDOMNodeWrapper) n).node instanceof List) {
ix += ((List) (((JDOMNodeWrapper) n).node)).size();
} else {
ix++;
}
}
throw new IllegalStateException("JDOM node not linked to parent node");
}
return index;
}
@Override
protected AxisIterator iterateAttributes(NodeTest nodeTest) {
AxisIterator base = new AttributeEnumeration(this);
if (nodeTest == AnyNodeTest.getInstance()) {
return base;
} else {
return new Navigator.AxisFilter(base, nodeTest);
}
}
@Override
protected AxisIterator iterateChildren(NodeTest nodeTest) {
if (hasChildNodes()) {
AxisIterator base = new ChildEnumeration(this, true, true);
if (nodeTest == AnyNodeTest.getInstance()) {
return base;
} else {
return new Navigator.AxisFilter(base, nodeTest);
}
} else {
return EmptyIterator.OfNodes.THE_INSTANCE;
}
}
@Override
protected AxisIterator iterateSiblings(NodeTest nodeTest, boolean forwards) {
if (nodeTest == AnyNodeTest.getInstance()) {
return new ChildEnumeration(this, false, forwards);
} else {
return new Navigator.AxisFilter(
new ChildEnumeration(this, false, forwards),
nodeTest);
}
}
@Override
protected AxisIterator iterateDescendants(NodeTest nodeTest, boolean includeSelf) {
Iterator descendants;
if (nodeTest.getUType() == UType.ELEMENT) {
// only select element nodes
descendants = ((Parent) node).getDescendants(new org.jdom.filter.ElementFilter());
} else {
descendants = ((Parent) node).getDescendants();
}
NodeWrappingFunction wrappingFunct = new NodeWrappingFunction() {
public NodeInfo wrap(Content node) {
return makeWrapper(node, getTreeInfo());
}
};
AxisIterator wrappedDescendants = new DescendantWrappingIterator(descendants, wrappingFunct);
if (includeSelf && nodeTest.matchesNode(this)) {
wrappedDescendants = new PrependIterator(this, wrappedDescendants);
}
if (nodeTest instanceof AnyNodeTest || (nodeTest instanceof NodeKindTest && ((NodeKindTest) nodeTest).getNodeKind() == Type.ELEMENT)) {
return wrappedDescendants;
} else {
return new Navigator.AxisFilter(wrappedDescendants, nodeTest);
}
}
private static class DescendantWrappingIterator extends NodeWrappingAxisIterator