Example usage for org.w3c.dom Node equals

List of usage examples for org.w3c.dom Node equals

Introduction

In this page you can find the example usage for org.w3c.dom Node equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Indicates whether some other object is "equal to" this one.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new ByteArrayInputStream(
                    ("<foo><foo1>Foo Test 1</foo1><foo2><another1><test1>Foo Test 2</test1></another1></foo2><foo3>Foo Test 3</foo3><foo4>Foo Test 4</foo4></foo>")
                            .getBytes()));
    String xpath = "/" + getXPath(document, "test1");
    Node node1 = (Node) XPathFactory.newInstance().newXPath().compile(xpath).evaluate(document,
            XPathConstants.NODE);
    Node node2 = (Node) XPathFactory.newInstance().newXPath().compile("//test1").evaluate(document,
            XPathConstants.NODE);
    System.out.println(node1.equals(node2));
}

From source file:Main.java

/**
 * @param el an Element/*from ww  w  .  jav a  2  s .c  o m*/
 * @return the ordinal position 1..N of this element amongst its sibling
 * elements (of any name), as a String; 
 * or '0' if the element has no parent
 */
public static String ordinalPosition(Element el) {
    String position = "0";
    Node parent = el.getParentNode();
    if (parent instanceof Element) {
        int pos = 0;
        NodeList nl = ((Element) parent).getChildNodes();
        for (int i = 0; i < nl.getLength(); i++) {
            Node n = nl.item(i);
            if (n instanceof Element)
                pos++;
            if (n.equals(el))
                position = new Integer(pos).toString();
        }
    }
    return position;
}

From source file:Main.java

/**
 * Reverse Engineers an XPath Expression of a given Node in the DOM.
 * //from   w  w w.  j  av a  2s . co m
 * @param node
 *            the given node.
 * @return string xpath expression (e.g., "/html[1]/body[1]/div[3]").
 */
public static String getXPathExpression(Node node) {
    Object xpathCache = node.getUserData(FULL_XPATH_CACHE);
    if (xpathCache != null) {
        return xpathCache.toString();
    }
    Node parent = node.getParentNode();

    if ((parent == null) || parent.getNodeName().contains("#document")) {
        String xPath = "/" + node.getNodeName() + "[1]";
        node.setUserData(FULL_XPATH_CACHE, xPath, null);
        return xPath;
    }

    StringBuffer buffer = new StringBuffer();

    if (parent != node) {
        buffer.append(getXPathExpression(parent));
        buffer.append("/");
    }

    buffer.append(node.getNodeName());

    List<Node> mySiblings = getSiblings(parent, node);

    for (int i = 0; i < mySiblings.size(); i++) {
        Node el = mySiblings.get(i);

        if (el.equals(node)) {
            buffer.append('[').append(Integer.toString(i + 1)).append(']');
            // Found so break;
            break;
        }
    }
    String xPath = buffer.toString();
    node.setUserData(FULL_XPATH_CACHE, xPath, null);
    return xPath;
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

public static Node getNextSiblingElement(Node node) {
    if (node == null || node.getParentNode() == null) {
        return null;
    }//from w  w  w .  j av a2  s.c  om
    Node parent = node.getParentNode();
    NodeList nodes = parent.getChildNodes();
    if (nodes == null) {
        return null;
    }
    boolean found = false;
    for (int i = 0; i < nodes.getLength(); i++) {
        Node child = nodes.item(i);
        if (child.equals(node)) {
            found = true;
            continue;
        }
        if (found && child.getNodeType() == Node.ELEMENT_NODE) {
            return child;
        }
    }

    return null;
}

From source file:de.hpi.petrinet.PetriNet.java

/**
 * Checks whether the net is a workflow net. Such a net has
 * exactly one initial and one final place and every place and 
 * transition is one a path from i to o.
 * /*from  w w  w  .j a v a2  s .  c om*/
 * @return true, if the net is a workflow net
 */
public boolean isWorkflowNet() {
    boolean isWF = (this.getInitialPlaces().size() == 1) && (this.getFinalPlaces().size() == 1);
    // maybe we already know that the net is not a workflow net
    if (!isWF)
        return isWF;

    Node in = this.getInitialPlace();
    Node out = this.getFinalPlace();
    for (Node n : this.getNodes()) {
        if (n.equals(in) || n.equals(out))
            continue;
        isWF &= this.getTransitiveClosure().isPath(in, n);
        isWF &= this.getTransitiveClosure().isPath(n, out);
    }
    return isWF;
}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

/**
 * Compute the xpath of a node relative to an anchor.
 * /*w  w  w  . j  a va 2  s. c  om*/
 * @param node
 *            node to find the xpath from.
 * @param anchor
 *            the relative point to fid from.
 * @return the computed xpath.
 */
public static String calcXpath(Node node, Node anchor) {
    String xpath = "";
    Node current = null;

    if (node == null || node.equals(anchor))
        return "";

    // add attribute to xpath
    if (node instanceof Attr) {
        Attr attr = (Attr) node;
        node = attr.getOwnerElement();
        xpath = '@' + attr.getName() + '/';
    }

    while ((current = node.getParentNode()) != anchor) {
        Engine.logEngine.trace("Calc Xpath : current node : " + current.getNodeName());
        NodeList childs = current.getChildNodes();
        int index = 0;
        for (int i = 0; i < childs.getLength(); i++) {
            if (childs.item(i).getNodeType() != Node.ELEMENT_NODE
                    && !childs.item(i).getNodeName().equalsIgnoreCase("#text"))
                continue;

            Engine.logEngine.trace("Calc Xpath : ==== > Child node : " + childs.item(i).getNodeName());

            // Bump the index if we have the same tag names..
            if (childs.item(i).getNodeName().equalsIgnoreCase(node.getNodeName())) {
                // tag names are equal ==> bump the index.
                index++;
                // is our node the one that is listed ?
                if (childs.item(i).equals(node))
                    // We found our node in the parent node list
                    break;
            }
        }
        // count the number of elements having the same tag
        int nbElements = 0;
        for (int i = 0; i < childs.getLength(); i++) {
            if (childs.item(i).getNodeName().equalsIgnoreCase(node.getNodeName())) {
                nbElements++;
            }
        }

        String name = node.getNodeName();
        if (name.equalsIgnoreCase("#text"))
            name = "text()";
        name = xpathEscapeColon(name);

        if (nbElements > 1) {
            xpath = name + "[" + index + "]/" + xpath;
        } else {
            // only one element had the same tag ==> do not compute the [xx]
            // syntax..
            xpath = name + "/" + xpath;
        }
        node = current;
    }
    if (xpath.length() > 0)
        // remove the trailing '/'
        xpath = xpath.substring(0, xpath.length() - 1);

    return xpath;
}

From source file:com.castis.sysComp.PoisConverterSysComp.java

public void parseClientUIFile(File file) throws Exception {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(file);
    doc.getDocumentElement().normalize();

    try {// w w  w . j  a  va2 s  .  com
        NodeList pList = doc.getElementsByTagName("clientUIInventory");

        Node pNode = pList.item(0);
        List<sceneDTO> sceneDTOList = new ArrayList<sceneDTO>();
        String platformType = "";
        if (pNode.getNodeType() == Node.ELEMENT_NODE) {
            Element eElement = (Element) pNode;
            if (eElement.getElementsByTagName("adPlatformType").getLength() > 0)
                platformType = eElement.getElementsByTagName("adPlatformType").item(0).getTextContent();
            else {
                if (platformType == null || platformType.equals(""))
                    throw new DataParsingException("data parsing error(adPlatformType)");
            }
            NodeList sceneList = eElement.getElementsByTagName("scene");

            for (int i = 0; i < sceneList.getLength(); i++) {
                Node sNode = sceneList.item(i);
                if (sNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element sElement = (Element) sNode;
                    String id = sElement.getAttribute("id");
                    if (id == null || id.equals(""))
                        throw new DataParsingException("data parsing error(scene id)");

                    String name = sElement.getAttribute("name");
                    if (name == null || name.equals(""))
                        throw new DataParsingException("data parsing error(scene name)");

                    String templateFileName = null;
                    if (sElement.getElementsByTagName("templateFileName").getLength() > 0)
                        templateFileName = sElement.getElementsByTagName("templateFileName").item(0)
                                .getTextContent();

                    if (templateFileName == null || templateFileName.equals("")) {
                        throw new DataParsingException("data parsing error(templateFileName)");
                    }
                    Node rNode = null;
                    if (sElement.getElementsByTagName("relatedMenuList").getLength() > 0)
                        rNode = sElement.getElementsByTagName("relatedMenuList").item(0);

                    if (rNode == null || rNode.equals("")) {
                        throw new DataParsingException("data parsing error(relatedMenuList)");
                    }

                    NodeList relatedMenuList = ((Element) rNode).getElementsByTagName("relatedMenu");

                    if (relatedMenuList.getLength() == 0) {
                        throw new DataParsingException("data parsing error(relatedMenuList)");
                    }

                    for (int j = 0; j < relatedMenuList.getLength(); j++) {
                        Node relatedNode = relatedMenuList.item(j);
                        if (relatedNode.getNodeType() == Node.ELEMENT_NODE) {
                            Element rElement = (Element) relatedNode;
                            String menuId = rElement.getAttribute("id");
                            String menuName = rElement.getAttribute("name");

                            if (menuId == null || menuId.equals(""))
                                throw new DataParsingException("data parsing error(related menu id)");
                            if (menuName == null || menuName.equals(""))
                                throw new DataParsingException("data parsing error(related menu name)");

                            Node adNode = null;
                            if (sElement.getElementsByTagName("adSpaceList").getLength() > 0)
                                adNode = sElement.getElementsByTagName("adSpaceList").item(0);

                            if (adNode == null || adNode.equals("")) {
                                throw new DataParsingException("data parsing error(adSpaceList)");
                            }

                            NodeList spaceList = ((Element) adNode).getElementsByTagName("adSpace");
                            if (spaceList.getLength() == 0) {
                                throw new DataParsingException("data parsing error(adSpace)");
                            }
                            for (int k = 0; k < spaceList.getLength(); k++) {
                                Node spaceNode = spaceList.item(k);
                                if (spaceNode.getNodeType() == Node.ELEMENT_NODE) {
                                    Element spaceElement = (Element) spaceNode;
                                    String spaceId = spaceElement.getAttribute("id");
                                    String spaceName = spaceElement.getAttribute("name");

                                    if (spaceId == null || spaceId.equals(""))
                                        throw new DataParsingException("data parsing error(space id)");
                                    if (spaceName == null || spaceName.equals(""))
                                        throw new DataParsingException("data parsing error(space name)");

                                    String resolution = null;
                                    String onFocus = null;
                                    String clickable = null;
                                    if (spaceElement.getElementsByTagName("size").getLength() > 0)
                                        resolution = spaceElement.getElementsByTagName("size").item(0)
                                                .getTextContent();

                                    if (spaceElement.getElementsByTagName("sizeOnFocus").getLength() > 0)
                                        onFocus = spaceElement.getElementsByTagName("sizeOnFocus").item(0)
                                                .getTextContent();
                                    String sizeLimit = "";
                                    NodeList tempList = spaceElement.getElementsByTagName("fileSizeLimit");
                                    if (tempList != null && tempList.getLength() > 0) {
                                        sizeLimit = spaceElement.getElementsByTagName("fileSizeLimit").item(0)
                                                .getTextContent();
                                    }

                                    if (spaceElement.getElementsByTagName("clickable").getLength() > 0)
                                        clickable = spaceElement.getElementsByTagName("clickable").item(0)
                                                .getTextContent();

                                    if (resolution == null || resolution.equals(""))
                                        throw new DataParsingException("data parsing error(size)");

                                    if (clickable == null || clickable.equals(""))
                                        throw new DataParsingException("data parsing error(clickable)");

                                    if (clickable.equalsIgnoreCase("Y")
                                            && (onFocus == null || onFocus.equals("")))
                                        throw new DataParsingException("data parsing error(sizeOnFocus)");

                                    sceneDTO sceneDTO = new sceneDTO();
                                    sceneDTO.setId(id);
                                    sceneDTO.setName(name);
                                    sceneDTO.setTemplateFileName(templateFileName);
                                    sceneDTO.setMenuId(menuId);
                                    sceneDTO.setMenuName(menuName);
                                    sceneDTO.setSpaceId(spaceId);
                                    sceneDTO.setSpaceName(spaceName);
                                    sceneDTO.setResolution(resolution);
                                    sceneDTO.setResolutionOnFocus(onFocus);
                                    sceneDTO.setSizeLimit(sizeLimit);
                                    if (sizeLimit == null || sizeLimit == "") {
                                        sceneDTO.setSizeLimit("-1");
                                    }
                                    sceneDTO.setClickable(clickable);

                                    sceneDTOList.add(sceneDTO);

                                    if (checkDuplicateMenu(sceneDTOList, sceneDTO) == false) {
                                        throw new DataParsingException("data parsing error(duplicate menu)");
                                    }
                                }
                            }

                        }

                    }
                }

            }
        }

        writeClientUIFile(sceneDTOList, platformType, file);
    } catch (Exception e) {
        String errorMsg = e.getMessage();
        log.error(errorMsg, e);
        throw new DataParsingException(errorMsg, e); //throw(e);
    }
}

From source file:eu.europa.esig.dss.xades.validation.XAdESSignature.java

/**
 * Checks if the given {@code Element} has as parent the current signature. This is the security check.
 *
 * @param element/*w  ww. ja va  2 s .com*/
 *            the element to be checked (can be null)
 * @return true if the given element has as parent the current signature element, false otherwise
 */
private boolean hasSignatureAsParent(final Element element) {

    if (element == null) {
        return false;
    }
    Node node = element;
    String nodeName = node.getNodeName();
    if (XPathQueryHolder.XMLE_X509CERTIFICATE.equals(nodeName)) {

        node = node.getParentNode();
        if (node == null) {
            return false;
        }
        nodeName = node.getNodeName();

    }
    if (XPathQueryHolder.XMLE_X509DATA.equals(nodeName)) {

        node = node.getParentNode();
        if (node == null) {
            return false;
        }
        nodeName = node.getNodeName();
    }
    if (XPathQueryHolder.XMLE_KEYINFO.equals(nodeName)) {

        node = node.getParentNode();
        if (node == null) {
            return false;
        }
    }
    if (!node.equals(signatureElement)) {
        return false;
    }
    return true;
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Assert XML content is equal.<br/>
 * <p/>/*from ww w.  j a v  a 2 s  . c o  m*/
 * This methods compares the attributes (if any exist) and either recursively compares the child elements (if any
 * exists) or the text content.<br/>
 * Therefore, mixed content is NOT supported by this method.
 * 
 * @param messageIn
 *            The message printed if assertion fails.
 * @param expected
 *            The expected XML content.
 * @param toBeAsserted
 *            The XML content to be compared with the expected content.
 * @throws Exception
 *             If anything fails.
 */
public static void assertXmlEquals(final String messageIn, final Node expected, final Node toBeAsserted)
        throws Exception {
    // Assert both nodes are null or both nodes are not null
    if (expected == null) {
        assertNull(messageIn + "Unexpected node. ", toBeAsserted);
        return;
    }
    assertNotNull(messageIn + " Expected node. ", toBeAsserted);
    if (expected.equals(toBeAsserted)) {
        return;
    }
    String nodeName = getLocalName(expected);
    String message = messageIn;
    if (!message.contains("-- Asserting ")) {
        message = message + "-- Asserting " + nodeName + ". ";
    } else {
        message = message + "/" + nodeName;
    }
    // assert both nodes are nodes of the same node type
    // if thedocument container xslt directive than is the nodeName
    // "#document" is here compared
    assertEquals(message + " Type of nodes are different", expected.getNodeType(), toBeAsserted.getNodeType());
    if (expected.getNodeType() == Node.TEXT_NODE) {
        assertEquals(message + " Text nodes are different. ", expected.getTextContent().trim(),
                toBeAsserted.getTextContent().trim());
    }
    // assert attributes
    NamedNodeMap expectedAttributes = expected.getAttributes();
    NamedNodeMap toBeAssertedAttributes = toBeAsserted.getAttributes();
    if (expectedAttributes == null) {
        assertNull(message + " Unexpected attributes. [" + nodeName + "]", toBeAssertedAttributes);
    } else {
        assertNotNull(message + " Expected attributes. ", toBeAssertedAttributes);
        final int expectedNumberAttributes = expectedAttributes.getLength();
        for (int i = 0; i < expectedNumberAttributes; i++) {
            Node expectedAttribute = expectedAttributes.item(i);
            String expectedAttributeNamespace = expectedAttribute.getNamespaceURI();
            Node toBeAssertedAttribute = null;
            if (expectedAttributeNamespace != null) {
                final String localName = expectedAttribute.getLocalName();
                toBeAssertedAttribute = toBeAssertedAttributes.getNamedItemNS(expectedAttributeNamespace,
                        localName);
                assertNotNull(message + " Expected attribute " + expectedAttribute.getNodeName(),
                        toBeAssertedAttribute);
            } else {
                // not namespace aware parsed. Attributes may have different
                // prefixes which are now part of their node name.
                // To compare expected and to be asserted attribute, it is
                // first it is tried to find the appropriate to be asserted
                // attribute by the node name. If this fails, xpath
                // selection is used after extracting the expected
                // attribute name
                final String expectedAttributeNodeName = expectedAttribute.getNodeName();
                toBeAssertedAttribute = toBeAssertedAttributes.getNamedItem(expectedAttributeNodeName);
                if (toBeAssertedAttribute == null) {
                    final String attributeName = getLocalName(expectedAttribute);
                    final String attributeXpath = "@" + attributeName;
                    toBeAssertedAttribute = selectSingleNode(toBeAsserted, attributeXpath);
                }
                assertNotNull(message + " Expected attribute " + expectedAttributeNodeName,
                        toBeAssertedAttribute);
            }
            assertEquals(message + " Attribute value mismatch [" + expectedAttribute.getNodeName() + "] ",
                    expectedAttribute.getTextContent(), toBeAssertedAttribute.getTextContent());
        }
    }
    // As mixed content (text + child elements) is not supported,
    // either the child elements or the text content have to be asserted.
    // Therefore, it is first tried to assert the children.
    // After that it is checked if children have been found. If this is not
    // the case, the text content is compared.
    NodeList expectedChildren = expected.getChildNodes();
    NodeList toBeAssertedChildren = toBeAsserted.getChildNodes();
    int expectedNumberElementNodes = 0;
    int toBeAssertedNumberElementNodes = 0;
    List<Node> previouslyAssertedChildren = new ArrayList<Node>();
    for (int i = 0; i < expectedChildren.getLength(); i++) {
        Node expectedChild = expectedChildren.item(i);
        if (expectedChild.getNodeType() == Node.ELEMENT_NODE) {
            expectedNumberElementNodes++;
            String expectedChildName = getLocalName(expectedChild);
            String expectedUri = expectedChild.getNamespaceURI();
            boolean expectedElementAsserted = false;
            for (int j = 0; j < toBeAssertedChildren.getLength(); j++) {
                final Node toBeAssertedChild = toBeAssertedChildren.item(j);
                // prevent previously asserted children from being
                // asserted again
                if (previouslyAssertedChildren.contains(toBeAssertedChild)) {
                    continue;
                }
                if (toBeAssertedChild.getNodeType() == Node.ELEMENT_NODE
                        && expectedChildName.equals(getLocalName(toBeAssertedChild))
                        && (expectedUri == null || expectedUri.equals(toBeAssertedChild.getNamespaceURI()))) {
                    expectedElementAsserted = true;
                    toBeAssertedNumberElementNodes++;
                    assertXmlEquals(message, expectedChild, toBeAssertedChild);
                    // add asserted child to list of asserted children to
                    // prevent it from being asserted again.
                    previouslyAssertedChildren.add(toBeAssertedChild);
                    break;
                }
            }
            if (!expectedElementAsserted) {
                fail(new StringBuffer(message).append(" Did not found expected corresponding element [")
                        .append(nodeName).append(", ").append(expectedChildName).append(", ").append(i)
                        .append("]").toString());
            }
        }
    }
    // check if any element node in toBeAssertedChildren exists
    // that has not been asserted. In this case, this element node
    // is unexpected!
    for (int i = 0; i < toBeAssertedChildren.getLength(); i++) {
        Node toBeAssertedChild = toBeAssertedChildren.item(i);
        // prevent previously asserted children from being
        // asserted again
        if (previouslyAssertedChildren.contains(toBeAssertedChild)) {
            continue;
        }
        if (toBeAssertedChild.getNodeType() == Node.ELEMENT_NODE) {
            fail(new StringBuffer(message).append("Found unexpected element node [").append(nodeName)
                    .append(", ").append(getLocalName(toBeAssertedChild)).append(", ").append(i).append("]")
                    .toString());
        }
    }
    // if no children have been found, text content must be compared
    if (expectedNumberElementNodes == 0 && toBeAssertedNumberElementNodes == 0) {
        String expectedContent = expected.getTextContent();
        String toBeAssertedContent = toBeAsserted.getTextContent();
        assertEquals(message, expectedContent, toBeAssertedContent);
    }
}

From source file:org.apache.any23.extractor.microdata.MicrodataParser.java

/**
 * Returns all the <b>itemprop</b>s for the given <b>itemscope</b> node.
 *
 * @param scopeNode node representing the <b>itemscope</b>
 * @param skipRoot if <code>true</code> the given root <code>node</code>
 *        will be not read as a property, even if it contains the <b>itemprop</b> attribute.
 * @return the list of <b>itemprop</b>s detected within the given <b>itemscope</b>.
 * @throws MicrodataParserException if an error occurs while retrieving an property value.
 *//*from w  ww.ja  v  a 2  s .  c  om*/
public List<ItemProp> getItemProps(final Node scopeNode, boolean skipRoot) throws MicrodataParserException {
    final Set<Node> accepted = new LinkedHashSet<>();

    if (!skipRoot) {
        NamedNodeMap attributes = scopeNode.getAttributes();
        if (attributes.getNamedItem(ITEMPROP_ATTRIBUTE) != null) {
            accepted.add(scopeNode);
        }
    }

    // TreeWalker to walk DOM tree starting with the scopeNode. Nodes maybe visited multiple times.
    TreeWalker treeWalker = ((DocumentTraversal) scopeNode.getOwnerDocument()).createTreeWalker(scopeNode,
            NodeFilter.SHOW_ELEMENT, new NodeFilter() {
                @Override
                public short acceptNode(Node node) {
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        NamedNodeMap attributes = node.getAttributes();
                        if (attributes.getNamedItem(ITEMPROP_ATTRIBUTE) != null && !scopeNode.equals(node)) {
                            accepted.add(node);
                        }

                        if (attributes.getNamedItem(ITEMSCOPE_ATTRIBUTE) != null) {
                            // Don't visit descendants of nodes that define a new scope
                            return FILTER_REJECT;
                        }
                    }
                    return FILTER_ACCEPT;
                }
            }, false);

    // To populate accepted we only need to walk the tree.
    while (treeWalker.nextNode() != null)
        ;

    final List<ItemProp> result = new ArrayList<>();
    for (Node itemPropNode : accepted) {
        final String itemProp = DomUtils.readAttribute(itemPropNode, ITEMPROP_ATTRIBUTE, null);

        if (StringUtils.isBlank(itemProp)) {
            manageError(new MicrodataParserException("invalid property name '" + itemProp + "'", itemPropNode));
            continue;
        }

        final String[] propertyNames = itemProp.trim().split("\\s+");
        ItemPropValue itemPropValue;
        for (String propertyName : propertyNames) {
            try {
                itemPropValue = getPropertyValue(itemPropNode);
            } catch (MicrodataParserException mpe) {
                manageError(mpe);
                continue;
            }
            result.add(new ItemProp(DomUtils.getXPathForNode(itemPropNode), propertyName, itemPropValue));
        }
    }
    return result;
}