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:org.apache.ws.security.message.UsernameTokenTest.java

/**
 * A test for sending multiple passwords in the UsernameToken
 *///ww w . j a v  a 2 s.  c  o  m
@org.junit.Test
public void testMultiplePassword() throws Exception {
    WSSecUsernameToken builder = new WSSecUsernameToken();
    builder.setPasswordType(WSConstants.PASSWORD_DIGEST);
    builder.setUserInfo("wernerd", "verySecret");

    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document utDoc = builder.build(doc, secHeader);

    //
    // Manually find the Nonce node and duplicate it
    //
    org.w3c.dom.Element elem = builder.getUsernameTokenElement();
    org.w3c.dom.NodeList list = elem.getElementsByTagNameNS(WSConstants.WSSE_NS, "Password");
    org.w3c.dom.Node passwordNode = list.item(0);
    org.w3c.dom.Node passwordCopy = passwordNode.cloneNode(true);
    passwordNode.getParentNode().insertBefore(passwordCopy, passwordNode);

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(utDoc);
        LOG.debug(outputString);
    }

    WSSecurityEngine newEngine = new WSSecurityEngine();
    try {
        newEngine.processSecurityHeader(doc, null, callbackHandler, null);
        fail("Expected failure as it is not BSP compliant");
    } catch (WSSecurityException ex) {
        // expected
    }
    WSSConfig config = WSSConfig.getNewInstance();
    config.setWsiBSPCompliant(false);
    newEngine.setWssConfig(config);
    newEngine.processSecurityHeader(doc, null, callbackHandler, null);
}

From source file:org.apache.ws.security.message.WSSecDKSign.java

protected Set getInclusivePrefixes(Element target, boolean excludeVisible) {
    Set result = new HashSet();
    Node parent = target;
    NamedNodeMap attributes;/*from  w  w w . ja v a 2s.  c o  m*/
    Node attribute;
    while (!(parent.getParentNode() instanceof Document)) {
        parent = parent.getParentNode();
        attributes = parent.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.add("#default");
                } else {
                    result.add(attribute.getLocalName());
                }
            }
        }
    }

    if (excludeVisible == true) {
        attributes = target.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.remove("#default");
                } else {
                    result.remove(attribute.getLocalName());
                }
            }
            if (attribute.getPrefix() != null) {
                result.remove(attribute.getPrefix());
            }
        }

        if (target.getPrefix() == null) {
            result.remove("#default");
        } else {
            result.remove(target.getPrefix());
        }
    }

    return result;
}

From source file:org.apache.ws.security.message.WSSecSignature.java

protected Set getInclusivePrefixes(Element target, boolean excludeVisible) {
    Set result = new HashSet();
    Node parent = target;
    while (!(parent.getParentNode() instanceof Document)) {
        parent = parent.getParentNode();
        NamedNodeMap attributes = parent.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.add("#default");
                } else {
                    result.add(attribute.getLocalName());
                }//from   w  w w.  java 2 s . c  o  m
            }
        }
    }

    if (excludeVisible == true) {
        NamedNodeMap attributes = target.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (attribute.getNamespaceURI() != null
                    && attribute.getNamespaceURI().equals(org.apache.ws.security.WSConstants.XMLNS_NS)) {
                if (attribute.getNodeName().equals("xmlns")) {
                    result.remove("#default");
                } else {
                    result.remove(attribute.getLocalName());
                }
            }
            if (attribute.getPrefix() != null) {
                result.remove(attribute.getPrefix());
            }
        }

        if (target.getPrefix() == null) {
            result.remove("#default");
        } else {
            result.remove(target.getPrefix());
        }
    }

    return result;
}

From source file:org.apache.ws.security.message.WSSecSignatureBase.java

/**
 * Get the List of inclusive prefixes from the DOM Element argument 
 *///w  w w  . jav a2s . c o  m
public List<String> getInclusivePrefixes(Element target, boolean excludeVisible) {
    List<String> result = new ArrayList<String>();
    Node parent = target;
    while (parent.getParentNode() != null && !(Node.DOCUMENT_NODE == parent.getParentNode().getNodeType())) {
        parent = parent.getParentNode();
        NamedNodeMap attributes = parent.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (WSConstants.XMLNS_NS.equals(attribute.getNamespaceURI())) {
                if ("xmlns".equals(attribute.getNodeName())) {
                    result.add("#default");
                } else {
                    result.add(attribute.getLocalName());
                }
            }
        }
    }

    if (excludeVisible) {
        NamedNodeMap attributes = target.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (WSConstants.XMLNS_NS.equals(attribute.getNamespaceURI())) {
                if ("xmlns".equals(attribute.getNodeName())) {
                    result.remove("#default");
                } else {
                    result.remove(attribute.getLocalName());
                }
            }
            if (attribute.getPrefix() != null) {
                result.remove(attribute.getPrefix());
            }
        }

        if (target.getPrefix() == null) {
            result.remove("#default");
        } else {
            result.remove(target.getPrefix());
        }
    }

    return result;
}

From source file:org.apache.ws.security.processor.ReferenceListProcessor.java

/**
 * Decrypt the EncryptedData argument using a SecretKey.
 * @param doc The (document) owner of EncryptedData
 * @param dataRefURI The URI of EncryptedData
 * @param encData The EncryptedData element
 * @param symmetricKey The SecretKey with which to decrypt EncryptedData
 * @param symEncAlgo The symmetric encryption algorithm to use
 * @throws WSSecurityException/*w ww.  java  2s  . c  om*/
 */
public static WSDataRef decryptEncryptedData(Document doc, String dataRefURI, Element encData,
        SecretKey symmetricKey, String symEncAlgo) throws WSSecurityException {
    XMLCipher xmlCipher = null;
    try {
        xmlCipher = XMLCipher.getInstance(symEncAlgo);
        xmlCipher.init(XMLCipher.DECRYPT_MODE, symmetricKey);
    } catch (XMLEncryptionException ex) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, ex);
    }

    WSDataRef dataRef = new WSDataRef(dataRefURI);
    dataRef.setWsuId(dataRefURI);
    dataRef.setAlgorithm(symEncAlgo);
    boolean content = X509Util.isContent(encData);
    dataRef.setContent(content);

    Node parent = encData.getParentNode();
    Node previousSibling = encData.getPreviousSibling();
    if (content) {
        encData = (Element) encData.getParentNode();
        parent = encData.getParentNode();
    }

    try {
        xmlCipher.doFinal(doc, encData, content);
    } catch (Exception ex) {
        throw new WSSecurityException(WSSecurityException.FAILED_CHECK, null, null, ex);
    }

    if (parent.getLocalName().equals(WSConstants.ENCRYPTED_HEADER)
            && parent.getNamespaceURI().equals(WSConstants.WSSE11_NS)) {

        Node decryptedHeader = parent.getFirstChild();
        Element decryptedHeaderClone = (Element) decryptedHeader.cloneNode(true);
        parent.getParentNode().appendChild(decryptedHeaderClone);
        parent.getParentNode().removeChild(parent);
        dataRef.setProtectedElement(decryptedHeaderClone);
        dataRef.setXpath(getXPath(decryptedHeaderClone));
    } else if (content) {
        dataRef.setProtectedElement(encData);
        dataRef.setXpath(getXPath(encData));
    } else {
        Node decryptedNode;
        if (previousSibling == null) {
            decryptedNode = parent.getFirstChild();
        } else {
            decryptedNode = previousSibling.getNextSibling();
        }
        if (decryptedNode != null && Node.ELEMENT_NODE == decryptedNode.getNodeType()) {
            dataRef.setProtectedElement((Element) decryptedNode);
        }
        dataRef.setXpath(getXPath(decryptedNode));
    }

    return dataRef;
}

From source file:org.apache.ws.security.processor.ReferenceListProcessor.java

/**
 * @param decryptedNode the decrypted node
 * @return a fully built xpath //from  w w w .ja  va  2s  .  c o  m
 *        (eg. &quot;/soapenv:Envelope/soapenv:Body/ns:decryptedElement&quot;)
 *        if the decryptedNode is an Element or an Attr node and is not detached
 *        from the document. <code>null</code> otherwise
 */
public static String getXPath(Node decryptedNode) {
    if (decryptedNode == null) {
        return null;
    }

    String result = "";
    if (Node.ELEMENT_NODE == decryptedNode.getNodeType()) {
        result = decryptedNode.getNodeName();
        result = prependFullPath(result, decryptedNode.getParentNode());
    } else if (Node.ATTRIBUTE_NODE == decryptedNode.getNodeType()) {
        result = "@" + decryptedNode.getNodeName();
        result = prependFullPath(result, ((Attr) decryptedNode).getOwnerElement());
    } else {
        return null;
    }

    return result;
}

From source file:org.apache.ws.security.processor.ReferenceListProcessor.java

/**
 * Recursively build an absolute xpath (starting with the root &quot;/&quot;)
 * //from   www .  j a  v  a2 s  .  c o  m
 * @param xpath the xpath expression built so far
 * @param node the current node whose name is to be prepended
 * @return a fully built xpath
 */
private static String prependFullPath(String xpath, Node node) {
    if (node == null) {
        // probably a detached node... not really useful
        return null;
    } else if (Node.ELEMENT_NODE == node.getNodeType()) {
        xpath = node.getNodeName() + "/" + xpath;
        return prependFullPath(xpath, node.getParentNode());
    } else if (Node.DOCUMENT_NODE == node.getNodeType()) {
        return "/" + xpath;
    } else {
        return prependFullPath(xpath, node.getParentNode());
    }
}

From source file:org.apache.ws.security.util.WSSecurityUtil.java

/**
 * Returns the first element that matches <code>name</code> and
 * <code>namespace</code>. <p/> This is a replacement for a XPath lookup
 * <code>//name</code> with the given namespace. It's somewhat faster than
 * XPath, and we do not deal with prefixes, just with the real namespace URI
 * /*from   w  ww .  j av a 2 s  .  c  o  m*/
 * @param startNode Where to start the search
 * @param name Local name of the element
 * @param namespace Namespace URI of the element
 * @return The found element or <code>null</code>
 */
public static Node findElement(Node startNode, String name, String namespace) {
    //
    // Replace the formerly recursive implementation with a depth-first-loop
    // lookup
    //
    if (startNode == null) {
        return null;
    }
    Node startParent = startNode.getParentNode();
    Node processedNode = null;

    while (startNode != null) {
        // start node processing at this point
        if (startNode.getNodeType() == Node.ELEMENT_NODE && startNode.getLocalName().equals(name)) {
            String ns = startNode.getNamespaceURI();
            if (ns != null && ns.equals(namespace)) {
                return startNode;
            }

            if ((namespace == null || namespace.length() == 0) && (ns == null || ns.length() == 0)) {
                return startNode;
            }
        }
        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }
        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return null;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return null;
}

From source file:org.apache.ws.security.util.WSSecurityUtil.java

/**
 * Returns the single SAMLAssertion element that contains an AssertionID/ID that
 * matches the supplied parameter.//w w  w . ja v  a  2s.c o m
 * 
 * @param startNode Where to start the search
 * @param value Value of the AssertionID/ID attribute
 * @return The found element if there was exactly one match, or
 *         <code>null</code> otherwise
 */
public static Element findSAMLAssertionElementById(Node startNode, String value) {
    Element foundElement = null;

    //
    // Replace the formerly recursive implementation with a depth-first-loop
    // lookup
    //
    if (startNode == null) {
        return null;
    }
    Node startParent = startNode.getParentNode();
    Node processedNode = null;

    while (startNode != null) {
        // start node processing at this point
        if (startNode.getNodeType() == Node.ELEMENT_NODE) {
            Element se = (Element) startNode;
            if ((se.hasAttribute("ID") && value.equals(se.getAttribute("ID")))
                    || (se.hasAttribute("AssertionID") && value.equals(se.getAttribute("AssertionID")))) {
                if (foundElement == null) {
                    foundElement = se; // Continue searching to find duplicates
                } else {
                    log.warn("Multiple elements with the same 'ID' attribute value!");
                    return null;
                }
            }
        }

        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }
        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return foundElement;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return foundElement;
}

From source file:org.apache.ws.security.util.WSSecurityUtil.java

/**
 * Returns the single element that contains an Id with value
 * <code>uri</code> and <code>namespace</code>. <p/> This is a
 * replacement for a XPath Id lookup with the given namespace. It's somewhat
 * faster than XPath, and we do not deal with prefixes, just with the real
 * namespace URI/*from   w  ww. j  a  v a2 s  .c  om*/
 * 
 * If there are multiple elements, we log a warning and return null as this
 * can be used to get around the signature checking.
 * 
 * @param startNode Where to start the search
 * @param value Value of the Id attribute
 * @param namespace Namespace URI of the Id
 * @return The found element if there was exactly one match, or
 *         <code>null</code> otherwise
 */
public static Element findElementById(Node startNode, String value, String namespace) {
    Element foundElement = null;

    //
    // Replace the formerly recursive implementation with a depth-first-loop
    // lookup
    //
    if (startNode == null) {
        return null;
    }
    Node startParent = startNode.getParentNode();
    Node processedNode = null;

    while (startNode != null) {
        // start node processing at this point
        if (startNode.getNodeType() == Node.ELEMENT_NODE) {
            Element se = (Element) startNode;
            if (se.hasAttributeNS(namespace, "Id") && value.equals(se.getAttributeNS(namespace, "Id"))) {
                if (foundElement == null) {
                    foundElement = se; // Continue searching to find duplicates
                } else {
                    log.warn("Multiple elements with the same 'Id' attribute value!");
                    return null;
                }
            }
        }

        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }
        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return foundElement;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return foundElement;
}