Example usage for org.w3c.dom Node getParentNode

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

Introduction

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

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:Main.java

private static void collectCDATASections(Node node, Set<String> cdataQNames) {
    if (node instanceof CDATASection) {
        Node parent = node.getParentNode();
        if (parent != null) {
            String uri = parent.getNamespaceURI();
            if (uri != null) {
                cdataQNames.add("{" + uri + "}" + parent.getNodeName()); //NOI18N
            } else {
                cdataQNames.add(parent.getNodeName());
            }//from   www.  ja  va  2  s  . c o m
        }
    }

    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        collectCDATASections(children.item(i), cdataQNames);
    }
}

From source file:Main.java

public static String getNamespaceURI(final org.w3c.dom.Node n, final String prefix) {
    final Node prefixDeclaration = n.getAttributes().getNamedItem("xmlns:" + prefix);
    if (prefixDeclaration != null) {
        // we have found the good NameSpace
        return prefixDeclaration.getNodeValue();
    }/*  ww  w .j a v a  2  s .  c  o m*/
    // we have found the good NameSpace
    // we look for the NameSpace in the parent Node
    return getNamespaceURI(n.getParentNode(), prefix);
}

From source file:Main.java

/**
 * calculates the path of the node up in the hierarchy, example of result is
 * project/build/plugins/plugin level parameter designates the number of
 * parents to climb eg. for level 2 the result would be plugins/plugin level
 * -1 means all the way to the top.//from ww  w .  j  av  a 2 s .  c  om
 */
public static String pathUp(Node node, int level) {
    StringBuffer buf = new StringBuffer();

    int current = level;

    while ((node != null) && (current > 0)) {
        if (node instanceof Element) {
            if (buf.length() > 0) {
                buf.insert(0, "/");
            }

            buf.insert(0, node.getNodeName());
            current = current - 1;
        }

        node = node.getParentNode();
    }

    return buf.toString();
}

From source file:Main.java

public static String getXPath(Node node) {
    if (null == node)
        return null;

    // declarations
    Node parent = null;//ww w  .j  a  va  2  s  .co  m
    Stack<Node> hierarchy = new Stack<Node>();
    StringBuilder buffer = new StringBuilder();

    // push element on stack
    hierarchy.push(node);

    parent = node.getParentNode();
    while (null != parent && parent.getNodeType() != Node.DOCUMENT_NODE) {
        // push on stack
        hierarchy.push(parent);

        // get parent of parent
        parent = parent.getParentNode();
    }

    // construct xpath
    Object obj = null;
    while (!hierarchy.isEmpty() && null != (obj = hierarchy.pop())) {
        Node n = (Node) obj;
        boolean handled = false;

        // only consider elements
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            Element e = (Element) n;

            // is this the root element?
            if (buffer.length() == 0) {
                // root element - simply append element name
                buffer.append(n.getNodeName());
            } else {
                // child element - append slash and element name
                buffer.append("/");
                buffer.append(n.getNodeName());

                if (n.hasAttributes()) {
                    // see if the element has a name or id attribute
                    if (e.hasAttribute("id")) {
                        // id attribute found - use that
                        buffer.append("[@id='" + e.getAttribute("id") + "']");
                        handled = true;
                    } else if (e.hasAttribute("name")) {
                        // name attribute found - use that
                        buffer.append("[@name='" + e.getAttribute("name") + "']");
                        handled = true;
                    }
                }

                if (!handled) {
                    // no known attribute we could use - get sibling index
                    int prev_siblings = 1;
                    Node prev_sibling = n.getPreviousSibling();
                    while (null != prev_sibling) {
                        if (prev_sibling.getNodeType() == n.getNodeType()) {
                            if (prev_sibling.getNodeName().equalsIgnoreCase(n.getNodeName())) {
                                prev_siblings++;
                            }
                        }
                        prev_sibling = prev_sibling.getPreviousSibling();
                    }
                    buffer.append("[" + prev_siblings + "]");
                }
            }
        }
    }

    // return buffer
    return buffer.toString();
}

From source file:org.dozer.eclipse.plugin.sourcepage.util.DozerPluginUtils.java

public static Node getMappingNode(Node someNode) {
    Node parentNode = someNode;
    while (!"mapping".equals((parentNode = parentNode.getParentNode()).getNodeName())) {
        //do nothing
    }// ww w .  jav  a2s  .co  m
    if ("mapping".equals(parentNode.getNodeName()))
        return parentNode;
    else
        return null;
}

From source file:Main.java

/**
 * Returns true if the descendantOrSelf is on the descendant-or-self axis
 * of the context node./*from   w  w w .  jav  a  2 s  .  c  o m*/
 *
 * @param ctx
 * @param descendantOrSelf
 * @return true if the node is descendant
 */
static public boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) {
    if (ctx == descendantOrSelf) {
        return true;
    }

    Node parent = descendantOrSelf;

    while (true) {
        if (parent == null) {
            return false;
        }

        if (parent == ctx) {
            return true;
        }

        if (parent.getNodeType() == Node.ATTRIBUTE_NODE) {
            parent = ((Attr) parent).getOwnerElement();
        } else {
            parent = parent.getParentNode();
        }
    }
}

From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java

/**
 * Used to verify an enveloped digital signature
 *
 * @param doc a Document object containing the xml with the signature
 * @param keyStorePath a String containing the path to the KeyStore
 * @param keyStorePW a String containing the KeyStore password
 * @param verifyAlias a String containing the alias of the public key used for verification
 * @return True if signature passes verification, False otherwise
 *//* ww w.j  a va 2  s .  co m*/
public static boolean verifySignature(Document doc, String keyStorePath, String keyStorePW,
        String verifyAlias) {
    boolean coreValidation = false;
    PublicKey publicKey = ClientUtil.getPublicKeyByAlias(keyStorePath, keyStorePW, verifyAlias);
    if (publicKey == null) {
        logger.error(
                "Public key was null when verifying signature. Ensure keystore configuration values are set properly.");
        return false;
    }
    try {
        NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (nl.getLength() == 0) {
            logger.error("No XML Digital Signature was found. The document was discarded.");
            return false;
        }
        Node signatureNode = nl.item(nl.getLength() - 1);
        DOMValidateContext valContext = new DOMValidateContext(publicKey, signatureNode);
        valContext.setURIDereferencer(new MyURIDereferencer(signatureNode.getParentNode()));
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        coreValidation = signature.validate(valContext);
        if (!coreValidation) {
            // for testing/debugging when validation fails...
            logger.error("Digital Signature Core Validation failed.");
            boolean signatureValidation = signature.getSignatureValue().validate(valContext);
            logger.debug("Digital Signature Validation: " + signatureValidation);
            @SuppressWarnings("rawtypes")
            Iterator i = signature.getSignedInfo().getReferences().iterator();
            for (int j = 0; i.hasNext(); j++) {
                Reference ref = (Reference) i.next();
                boolean referenceValidation = ref.validate(valContext);
                logger.debug("Digital Signature Reference Validation: " + referenceValidation);
                byte[] calculatedDigestValue = ref.getCalculatedDigestValue();
                byte[] digestValue = ref.getDigestValue();
                String cdvString = new String(Base64.encodeBase64(calculatedDigestValue));
                logger.debug("Digital Signature Calculated Digest Value: " + cdvString);
                String dvString = new String(Base64.encodeBase64(digestValue));
                logger.debug("Digital Signature Digest Value: " + dvString);
            }
        }
    } catch (MarshalException e) {
        logger.error("MarshalException when attempting to verify a digital signature.");
    } catch (XMLSignatureException e) {
        logger.error("XMLSignature Exception when attempting to verify a digital signature.");
    }
    return coreValidation;
}

From source file:Main.java

public static String getPrefixNS(String uri, Node e) {
    while (e != null && e.getNodeType() == Node.ELEMENT_NODE) {
        NamedNodeMap attrs = e.getAttributes();
        for (int n = 0; n < attrs.getLength(); n++) {
            Attr a = (Attr) attrs.item(n);
            String name = a.getName();
            if (name.startsWith("xmlns:") && a.getNodeValue().equals(uri)) {
                return name.substring("xmlns:".length());
            }/*from   www. jav  a  2s .  com*/
        }
        e = e.getParentNode();
    }
    return null;
}

From source file:Main.java

/**
 * Searches for a node within a DOM document with a given node path expression.
 * Elements are separated by '.' characters.
 * Example: Foo.Bar.Poo/*from w w  w .  j a  v a2  s . c  o m*/
 * @param doc DOM Document to search for a node.
 * @param pathExpression dot separated path expression
 * @return Node element found in the DOM document.
 */
public static Node findNodeByName(Document doc, String pathExpression) {
    final StringTokenizer tok = new StringTokenizer(pathExpression, ".");
    final int numToks = tok.countTokens();
    NodeList elements;
    if (numToks == 1) {
        elements = doc.getElementsByTagNameNS("*", pathExpression);
        return elements.item(0);
    }

    String element = pathExpression.substring(pathExpression.lastIndexOf('.') + 1);
    elements = doc.getElementsByTagNameNS("*", element);

    String attributeName = null;
    if (elements.getLength() == 0) {
        //No element found, but maybe we are searching for an attribute
        attributeName = element;

        //cut off attributeName and set element to next token and continue
        Node found = findNodeByName(doc,
                pathExpression.substring(0, pathExpression.length() - attributeName.length() - 1));

        if (found != null) {
            return found.getAttributes().getNamedItem(attributeName);
        } else {
            return null;
        }
    }

    StringBuffer pathName;
    Node parent;
    for (int j = 0; j < elements.getLength(); j++) {
        int cnt = numToks - 1;
        pathName = new StringBuffer(element);
        parent = elements.item(j).getParentNode();
        do {
            if (parent != null) {
                pathName.insert(0, '.');
                pathName.insert(0, parent.getLocalName());//getNodeName());

                parent = parent.getParentNode();
            }
        } while (parent != null && --cnt > 0);
        if (pathName.toString().equals(pathExpression)) {
            return elements.item(j);
        }
    }

    return null;
}

From source file:Main.java

public static String getPrefix(String uri, Node e) {
    while (e != null && (e.getNodeType() == Element.ELEMENT_NODE)) {
        NamedNodeMap attrs = e.getAttributes();
        for (int n = 0; n < attrs.getLength(); n++) {
            Attr a = (Attr) attrs.item(n);
            String name;/*from   w w w. j  a v a2 s  . c o m*/
            if ((name = a.getName()).startsWith("xmlns:") && a.getNodeValue().equals(uri)) {
                return name.substring(6);
            }
        }
        e = e.getParentNode();
    }
    return null;
}