Example usage for org.w3c.dom Element getElementsByTagNameNS

List of usage examples for org.w3c.dom Element getElementsByTagNameNS

Introduction

In this page you can find the example usage for org.w3c.dom Element getElementsByTagNameNS.

Prototype

public NodeList getElementsByTagNameNS(String namespaceURI, String localName) throws DOMException;

Source Link

Document

Returns a NodeList of all the descendant Elements with a given local name and namespace URI in document order.

Usage

From source file:org.apache.webdav.lib.methods.PollMethod.java

public void parseResponse(InputStream input, HttpState state, HttpConnection conn)
        throws IOException, HttpException {
    int status = getStatusLine().getStatusCode();

    if (status == HttpStatus.SC_MULTI_STATUS) {
        parseXMLResponse(input);/*from ww w.j  av  a 2s.  com*/
        NodeList list = getResponseDocument().getDocumentElement().getElementsByTagNameNS("DAV:", "response");

        for (int i = 0; i < list.getLength(); i++) {
            Element e = (Element) list.item(i);

            NodeList s = e.getElementsByTagNameNS("DAV:", "status");
            if (s.getLength() > 0) {
                Element response = ((Element) (s.item(0)).getParentNode());
                String statusText = DOMUtils.getTextValue(s.item(0));
                if (statusText.indexOf(" 200 ") != -1) {
                    // polled subscriptions for which *AN* event is fired
                    NodeList p = response.getElementsByTagNameNS(EXCHANGE_NS, "subscriptionID");
                    if (p.getLength() > 0) {
                        NodeList li = ((Element) p.item(0)).getElementsByTagName("li");
                        for (int l = 0; l < li.getLength(); ++l) {
                            String id = DOMUtils.getTextValue(li.item(i));
                            this.subscriptionsWithEvents.add(Integer.getInteger(id));
                        }
                    }
                } else if (statusText.indexOf(" 204 ") != -1) {
                    // polled subscriptions for which *NO* event is fired
                    NodeList p = response.getElementsByTagNameNS(EXCHANGE_NS, "subscriptionID");
                    if (p.getLength() > 0) {
                        NodeList li = ((Element) p.item(0)).getElementsByTagName("li");
                        for (int l = 0; l < li.getLength(); ++l) {
                            String id = DOMUtils.getTextValue(li.item(i));
                            this.subscriptionsWithoutEvents.add(Integer.getInteger(id));
                        }
                    }
                }
            }
        }
    }
}

From source file:org.apache.webdav.lib.properties.AclProperty.java

/**
 * Parse an ace./*from   w ww.  j  a v a  2s  .  c om*/
 */
protected Ace parseAce(Element element) {

    String principal = null;
    Element child = DOMUtils.getFirstElement(element, "DAV:", "principal");
    if (child == null) {
        System.err.println("Error: mandatory element <principal> is missing !");
        System.err.println("element: " + element);
        return null;
    }

    Element href = DOMUtils.getFirstElement(child, "DAV:", "href");
    if (href != null) {
        principal = DOMUtils.getTextValue(href);
        try {
            principal = URIUtil.decode(principal);
        } catch (URIException e) {
            System.err.println("Warning: decoding href element failed!");
            System.err.println("reason: " + e.getReason());
        }
    }

    String[] types = { "all", "authenticated", "unauthenticated", "property", "self" };
    for (int i = 0; i < types.length && principal == null; i++) {
        Element type = DOMUtils.getFirstElement(child, "DAV:", types[i]);
        if (type != null) {
            principal = types[i];
        }
    }

    if (principal == null) {
        System.err.println("Error: unknown type of principal");
        System.err.println("element: " + element);
        return null;
    }

    Ace ace = new Ace(principal);

    child = DOMUtils.getFirstElement(element, "DAV:", "grant");
    if (child == null) {
        child = DOMUtils.getFirstElement(element, "DAV:", "deny");
        ace.setNegative(true);
    }
    if (child != null) {
        NodeList privilegeElements = child.getElementsByTagNameNS("DAV:", "privilege");
        for (int i = 0; i < privilegeElements.getLength(); i++) {
            Element privilegeElement = (Element) privilegeElements.item(i);
            NodeList privileges = privilegeElement.getElementsByTagName("*");
            for (int j = 0; j < privileges.getLength(); j++) {
                Element privilege = (Element) privileges.item(j);
                ace.addPrivilege(parsePrivilege(privilege));
            }
        }
    }

    child = DOMUtils.getFirstElement(element, "DAV:", "inherited");
    if (child != null) {
        href = DOMUtils.getFirstElement(child, "DAV:", "href");
        String shref = null;
        if (href != null) {
            shref = DOMUtils.getTextValue(href);
            if (!shref.equals(response.getHref())) {
                ace.setInherited(true);
                ace.setInheritedFrom(shref);
            }
        } else {
            System.err.println("Error: mandatory element <href> is missing !");
            return null;
        }
    }

    child = DOMUtils.getFirstElement(element, "DAV:", "protected");
    if (child != null) {
        ace.setProtected(true);
    }

    child = DOMUtils.getFirstElement(element, "http://jakarta.apache.org/slide/", "non-inheritable");
    if (child != null) {
        ace.setInheritable(false);
    }

    return ace;

}

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

/**
 * Test that signs a SOAP body element "value". The SOAP request is then modified
 * so that the signed "value" element is put in the header, and the value of the
 * original element is changed. This test will fail as the request will contain
 * multiple elements with the same wsu:Id.
 */// ww w .j a v a  2  s .  co m
@org.junit.Test
public void testMovedElement() throws Exception {
    WSSecSignature builder = new WSSecSignature();
    builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
    LOG.info("Before Signing....");
    Document doc = SOAPUtil.toSOAPPart(SOAPMSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
    WSEncryptionPart encP = new WSEncryptionPart("value", "http://blah.com", "");
    parts.add(encP);
    builder.setParts(parts);

    Document signedDoc = builder.build(doc, crypto, secHeader);

    //
    // Replace the signed element with a modified element, and move the original
    // signed element into the SOAP header
    //
    org.w3c.dom.Element secHeaderElement = secHeader.getSecurityHeader();
    org.w3c.dom.Element envelopeElement = signedDoc.getDocumentElement();
    org.w3c.dom.Node valueNode = envelopeElement.getElementsByTagNameNS("http://blah.com", "value").item(0);
    org.w3c.dom.Node clonedValueNode = valueNode.cloneNode(true);
    secHeaderElement.appendChild(clonedValueNode);
    valueNode.getFirstChild().setNodeValue("250");

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

    try {
        verify(signedDoc);
        fail("Failure expected on multiple elements with the same wsu:Id");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == 6);
        assertTrue(ex.getMessage().startsWith("The signature or decryption was invalid"));
    }
}

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

/**
 * Test that signs a SOAP body element "value". The SOAP request is then modified
 * so that the signed "value" element is put in the header, and the value of the
 * original element is changed. The wsu:Id value of the original element is also
 * changed. Signature verification will pass, so we need to check the wsu:Id's.
 *///from  w  ww .  j  a va 2  s  .  c om
@org.junit.Test
public void testMovedElementChangedId() throws Exception {
    WSSecSignature builder = new WSSecSignature();
    builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
    LOG.info("Before Signing....");
    Document doc = SOAPUtil.toSOAPPart(SOAPMSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
    WSEncryptionPart encP = new WSEncryptionPart("value", "http://blah.com", "");
    parts.add(encP);
    builder.setParts(parts);

    Document signedDoc = builder.build(doc, crypto, secHeader);

    //
    // Replace the signed element with a modified element, and move the original
    // signed element into the SOAP header
    //
    org.w3c.dom.Element secHeaderElement = secHeader.getSecurityHeader();
    org.w3c.dom.Element envelopeElement = signedDoc.getDocumentElement();
    org.w3c.dom.Node valueNode = envelopeElement.getElementsByTagNameNS("http://blah.com", "value").item(0);
    org.w3c.dom.Node clonedValueNode = valueNode.cloneNode(true);
    secHeaderElement.appendChild(clonedValueNode);
    valueNode.getFirstChild().setNodeValue("250");
    String savedId = ((org.w3c.dom.Element) valueNode).getAttributeNS(WSConstants.WSU_NS, "Id");
    ((org.w3c.dom.Element) valueNode).setAttributeNS(WSConstants.WSU_NS, "wsu:Id", "id-250");

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

    //
    // Now we check that the wsu:Id of the element we want signed corresponds to the
    // wsu:Id that was actually signed...again, this should pass
    //
    List<WSSecurityEngineResult> results = verify(signedDoc);

    WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN);
    WSSecurityUtil.checkSignsAllElements(actionResult, new String[] { savedId });

    //
    // Finally we need to check that the wsu:Id of the element we want signed in the
    // SOAP request is the same as the wsu:Id that was actually signed
    //
    envelopeElement = signedDoc.getDocumentElement();
    org.w3c.dom.Node bodyNode = envelopeElement.getElementsByTagNameNS(WSConstants.URI_SOAP11_ENV, "Body")
            .item(0);
    valueNode = ((org.w3c.dom.Element) bodyNode).getElementsByTagNameNS("http://blah.com", "value").item(0);
    String actualId = ((org.w3c.dom.Element) valueNode).getAttributeNS(WSConstants.WSU_NS, "Id");
    try {
        WSSecurityUtil.checkSignsAllElements(actionResult, new String[] { actualId });
        fail("Failure expected on bad wsu:Id");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == 6);
        assertTrue(ex.getMessage().startsWith("The signature or decryption was invalid"));
    }
}

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

/**
 * Test that signs and verifies a Timestamp. The request is then modified so that the
 * Timestamp has a default (WSU) namespace inserted. The signature validation should still
 * pass due to c14n (see WSS-181).//w  w w .  j a v  a2s  .  c o m
 * 
 * @throws java.lang.Exception Thrown when there is any problem in signing or verification
 */
@org.junit.Test
public void testValidModifiedSignature() throws Exception {
    WSSecSignature builder = new WSSecSignature();
    builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
    LOG.info("Before Signing....");
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    WSSecTimestamp timestamp = new WSSecTimestamp();
    timestamp.setTimeToLive(300);
    Document createdDoc = timestamp.build(doc, secHeader);

    List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
    WSEncryptionPart encP = new WSEncryptionPart("Timestamp", WSConstants.WSU_NS, "");
    parts.add(encP);
    builder.setParts(parts);

    Document signedDoc = builder.build(createdDoc, crypto, secHeader);
    org.w3c.dom.Element secHeaderElement = secHeader.getSecurityHeader();
    org.w3c.dom.Node timestampNode = secHeaderElement.getElementsByTagNameNS(WSConstants.WSU_NS, "Timestamp")
            .item(0);
    ((org.w3c.dom.Element) timestampNode).setAttributeNS(WSConstants.XMLNS_NS, "xmlns", WSConstants.WSU_NS);

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

    verify(signedDoc);
}

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

/**
 * A test for WSS-66 - the nonce string is null
 * http://issues.apache.org/jira/browse/WSS-66
 * "Possible security hole when PasswordDigest is used by client."
 *///  w  ww.  j a v  a  2s  . c om
@org.junit.Test
public void testNullNonce() throws Exception {
    WSSecUsernameToken builder = new WSSecUsernameToken();
    builder.setPasswordType(WSConstants.PASSWORD_DIGEST);
    builder.setUserInfo("wernerd", "BAD_PASSWORD");

    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 set the content to null
    //
    org.w3c.dom.Element elem = builder.getUsernameTokenElement();
    org.w3c.dom.NodeList list = elem.getElementsByTagNameNS(WSConstants.WSSE_NS, "Nonce");
    org.w3c.dom.Node nonceNode = list.item(0);
    org.w3c.dom.Node childNode = nonceNode.getFirstChild();
    childNode.setNodeValue("");

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

    try {
        //
        // Verification should fail as the password is bad
        //
        verify(utDoc);
        fail("Expected failure due to a bad password");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == WSSecurityException.FAILED_AUTHENTICATION);
        // expected
    }
}

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

/**
 * A test for WSS-66 - the created string is null
 * http://issues.apache.org/jira/browse/WSS-66
 * "Possible security hole when PasswordDigest is used by client."
 *//* w  w  w.ja  va 2s  .  com*/
@org.junit.Test
public void testNullCreated() throws Exception {
    WSSecUsernameToken builder = new WSSecUsernameToken();
    builder.setPasswordType(WSConstants.PASSWORD_DIGEST);
    builder.setUserInfo("wernerd", "BAD_PASSWORD");

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

    //
    // Manually find the Created node and set the content to null
    //
    org.w3c.dom.Element elem = builder.getUsernameTokenElement();
    org.w3c.dom.NodeList list = elem.getElementsByTagNameNS(WSConstants.WSU_NS, "Created");
    org.w3c.dom.Node nonceNode = list.item(0);
    org.w3c.dom.Node childNode = nonceNode.getFirstChild();
    childNode.setNodeValue("");

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

    try {
        //
        // Verification should fail as the password is bad
        //
        verify(utDoc);
        fail("Expected failure due to a bad password");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == WSSecurityException.FAILED_AUTHENTICATION);
        // expected
    }
}

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

/**
 * A test for sending multiple nonces in the UsernameToken
 *///from ww  w  . ja  va2 s.  c  om
@org.junit.Test
public void testMultipleNonce() 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, "Nonce");
    org.w3c.dom.Node nonceNode = list.item(0);
    org.w3c.dom.Node nonceCopy = nonceNode.cloneNode(true);
    nonceNode.getParentNode().insertBefore(nonceCopy, nonceNode);

    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.UsernameTokenTest.java

/**
 * A test for sending multiple Created elements in the UsernameToken
 *///from   ww w  .j  a  va  2 s.  c  o  m
@org.junit.Test
public void testMultipleCreated() 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 Created node and duplicate it
    //
    org.w3c.dom.Element elem = builder.getUsernameTokenElement();
    org.w3c.dom.NodeList list = elem.getElementsByTagNameNS(WSConstants.WSU_NS, "Created");
    org.w3c.dom.Node createdNode = list.item(0);
    org.w3c.dom.Node createdCopy = createdNode.cloneNode(true);
    createdNode.getParentNode().insertBefore(createdCopy, createdNode);

    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.UsernameTokenTest.java

/**
 * A test for sending multiple passwords in the UsernameToken
 *///from   w w w.  j ava2  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);
}