Example usage for org.w3c.dom Element setAttributeNS

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

Introduction

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

Prototype

public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;

Source Link

Document

Adds a new attribute.

Usage

From source file:org.apache.ws.scout.registry.RegistryImpl.java

/**
 * /*ww  w.  j av a2s  .c o m*/
 */
public JAXBElement<?> execute(JAXBElement<?> uddiRequest, URI endPointURI) throws RegistryException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document doc;
    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        this.marshaller.marshal(uddiRequest, baos);
        doc = docBuilder.parse(new ByteArrayInputStream(baos.toByteArray()));
    } catch (SAXException saxe) {
        throw (new RegistryException(saxe));
    } catch (ParserConfigurationException pce) {
        throw (new RegistryException(pce));
    } catch (IOException ioe) {
        throw (new RegistryException(ioe));
    } catch (JAXBException ioe) {
        throw (new RegistryException(ioe));
    }
    Element request = doc.getDocumentElement();

    request.setAttribute("xmlns", this.getUddiNamespace());
    if (!"3.0".equals(this.getUddiVersion())) {
        request.setAttribute("generic", this.getUddiVersion());
    }
    //request.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns", this.getUddiNamespace());
    // A SOAP request is made and a SOAP response
    // is returned.

    Element response;
    try {
        response = transport.send(request, endPointURI);
    } catch (TransportException te) {
        throw new RegistryException(te);
    }
    /* if (response.hasAttributes()) {
        NamedNodeMap am = response.getAttributes();
        ArrayList<String> al = new ArrayList<String>();
        for (int i = 0; i < am.getLength(); i++) {
     Node n = am.item(i);
     String attribute = n.getNodeName();
     if (attribute!= null && attribute.startsWith("xmlns")) {
        al.add(attribute);
     }
        }
        for (String attr : al) {
     response.removeAttribute(attr);
        }
     }*/

    if (response.getNamespaceURI() == null) {
        response.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", this.getUddiNamespace());
    }

    // If we are getting responses from a UDDI v3, remove the xmlns

    // First, let's make sure that a response
    // (any response) is found in the SOAP Body.

    String responseName = response.getLocalName();
    if (responseName == null) {
        throw new RegistryException("Unsupported response " + "from registry. A value was not present.");
    }

    if (responseName.toLowerCase().equals("fault")) {
        NodeList nodeList = null;

        // Child Elements
        String fCode = null;
        nodeList = response.getElementsByTagName("faultcode");
        if (nodeList.getLength() > 0)
            fCode = nodeList.item(0).getNodeValue();

        String fString = null;
        nodeList = response.getElementsByTagName("faultstring");
        if (nodeList.getLength() > 0)
            fString = nodeList.item(0).getNodeValue();

        String fActor = null;
        nodeList = response.getElementsByTagName("faultactor");
        if (nodeList.getLength() > 0)
            fActor = nodeList.item(0).getNodeValue();

        DispositionReport dispRpt = null;

        nodeList = response.getElementsByTagName("detail");
        if (nodeList.getLength() > 0) {
            nodeList = ((Element) nodeList.item(0)).getElementsByTagName("dispositionReport");
            if (nodeList.getLength() > 0) {
                JAXBElement<DispositionReport> dispRptObj = null;
                try {
                    dispRptObj = (JAXBElement<DispositionReport>) unmarshaller
                            .unmarshal((Element) nodeList.item(0));
                } catch (JAXBException xmle) {
                    throw (new RegistryException(xmle));
                }
                dispRpt = dispRptObj.getValue();
            }
        }

        RegistryException e = new RegistryException(fCode, fString, fActor, dispRpt);

        // Create RegistryException instance and return
        throw e;
    }

    // Let's now try to determine which UDDI response
    // we received and unmarshal it appropriately or
    // throw a RegistryException if it's unknown.
    // Well, we have now determined that something was
    // returned and it is "a something" that we know
    // about so let's unmarshal it into a RegistryObject
    // Next, let's make sure we didn't recieve a SOAP
    // Fault. If it is a SOAP Fault then throw it
    // immediately.

    JAXBElement<?> uddiResponse = null;
    try {
        String xml = XMLUtils.convertNodeToXMLString(response);
        log.debug("Response is: " + xml);

        StringReader reader = new StringReader(xml);
        uddiResponse = (JAXBElement<?>) unmarshaller.unmarshal(new StreamSource(reader));
        //It is probably faster not to go to a String, but JAXB has issues with this
        //uddiResponse = (JAXBElement<?>) unmarshaller.unmarshal(response);

    } catch (JAXBException xmle) {
        throw (new RegistryException(xmle));
    }

    return uddiResponse;
}

From source file:org.apache.ws.scout.registry.RegistryV3Impl.java

/**
 * /*from  w ww  .  j a va2  s . c  o m*/
 */
public JAXBElement<?> execute(JAXBElement<?> uddiRequest, URI endPointURI) throws RegistryV3Exception {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    Document doc;
    try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setNamespaceAware(true);
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        this.marshaller.marshal(uddiRequest, baos);
        doc = docBuilder.parse(new ByteArrayInputStream(baos.toByteArray()));
    } catch (SAXException saxe) {
        throw (new RegistryV3Exception(saxe));
    } catch (ParserConfigurationException pce) {
        throw (new RegistryV3Exception(pce));
    } catch (IOException ioe) {
        throw (new RegistryV3Exception(ioe));
    } catch (JAXBException ioe) {
        throw (new RegistryV3Exception(ioe));
    }
    Element request = doc.getDocumentElement();

    request.setAttribute("xmlns", this.getUddiNamespace());
    if (!"3.0".equals(this.getUddiVersion())) {
        request.setAttribute("generic", this.getUddiVersion());
    }
    //request.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns", this.getUddiNamespace());
    // A SOAP request is made and a SOAP response
    // is returned.
    if (log.isDebugEnabled()) {
        String xmlIn = XMLUtils.convertNodeToXMLString(request);
        log.debug("Request send to UDDI Registry: " + xmlIn);
    }

    Element response;
    try {
        response = transport.send(request, endPointURI);
    } catch (TransportException te) {
        throw new RegistryV3Exception(te);
    }
    /* if (response.hasAttributes()) {
       NamedNodeMap am = response.getAttributes();
       ArrayList<String> al = new ArrayList<String>();
       for (int i = 0; i < am.getLength(); i++) {
     Node n = am.item(i);
     String attribute = n.getNodeName();
     if (attribute!= null && attribute.startsWith("xmlns")) {
        al.add(attribute);
     }
       }
       for (String attr : al) {
     response.removeAttribute(attr);
       }
    }*/
    JAXBElement<?> uddiResponse = null;
    if (response != null) {
        if (response.getNamespaceURI() == null) {
            response.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", this.getUddiNamespace());
        }

        // If we are getting responses from a UDDI v3, remove the xmlns

        // First, let's make sure that a response
        // (any response) is found in the SOAP Body.

        String responseName = response.getLocalName();
        if (responseName == null) {
            throw new RegistryV3Exception("Unsupported response " + "from registry. A value was not present.");
        }

        // Let's now try to determine which UDDI response
        // we received and unmarshal it appropriately or
        // throw a RegistryV3Exception if it's unknown.
        // Well, we have now determined that something was
        // returned and it is "a something" that we know
        // about so let's unmarshal it into a RegistryObject
        // Next, let's make sure we didn't recieve a SOAP
        // Fault. If it is a SOAP Fault then throw it
        // immediately.

        try {
            String xml = XMLUtils.convertNodeToXMLString(response);
            log.debug("Response is: " + xml);

            StringReader reader = new StringReader(xml);
            uddiResponse = (JAXBElement<?>) unmarshaller.unmarshal(new StreamSource(reader));
            //It is probably faster not to go to a String, but JAXB has issues with this
            //uddiResponse = (JAXBElement<?>) unmarshaller.unmarshal(response);

        } catch (JAXBException xmle) {
            throw (new RegistryV3Exception(xmle));
        }

        if (responseName.toLowerCase().equals("fault")) {
            NodeList nodeList = null;

            // Child Elements
            String fCode = null;
            nodeList = response.getElementsByTagName("faultcode");
            if (nodeList.getLength() > 0)
                fCode = nodeList.item(0).getNodeValue();

            String fString = null;
            nodeList = response.getElementsByTagName("faultstring");
            if (nodeList.getLength() > 0)
                fString = nodeList.item(0).getNodeValue();

            String fActor = null;
            nodeList = response.getElementsByTagName("faultactor");
            if (nodeList.getLength() > 0)
                fActor = nodeList.item(0).getNodeValue();

            DispositionReport dispRpt = null;

            nodeList = response.getElementsByTagName("detail");
            if (nodeList.getLength() > 0) {
                nodeList = ((Element) nodeList.item(0)).getElementsByTagName("dispositionReport");
                if (nodeList.getLength() > 0) {
                    JAXBElement<DispositionReport> dispRptObj = null;
                    try {
                        dispRptObj = (JAXBElement<DispositionReport>) unmarshaller
                                .unmarshal((Element) nodeList.item(0));
                    } catch (JAXBException xmle) {
                        throw (new RegistryV3Exception(xmle));
                    }
                    dispRpt = dispRptObj.getValue();
                }
            }

            RegistryV3Exception e = new RegistryV3Exception(fCode, fString, fActor, dispRpt);

            // Create RegistryV3Exception instance and return
            throw e;
        }
    }

    return uddiResponse;
}

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

@org.junit.Test
public void testBadAttribute() throws Exception {
    WSSecEncrypt builder = new WSSecEncrypt();
    builder.setUserInfo("wss40");
    builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
    builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    /*//  w  ww . j av a  2 s  .  co m
     * Prepare the Encrypt object with the token, setup data structure
     */
    builder.prepare(doc, crypto);

    /*
     * Set up the parts structure to encrypt the body
     */
    SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc.getDocumentElement());
    java.util.List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
    WSEncryptionPart encP = new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(),
            soapConstants.getEnvelopeURI(), "Content");
    parts.add(encP);

    /*
     * Encrypt the parts (Body), create EncryptedData elements that reference
     * the EncryptedKey, and get a ReferenceList that can be put into the
     * Security header. Be sure that the ReferenceList is after the
     * EncryptedKey element in the Security header (strict layout)
     */
    Element refs = builder.encryptForRef(null, parts);
    builder.addExternalRefElement(refs, secHeader);

    /*
     * now add (prepend) the EncryptedKey element, then a
     * BinarySecurityToken if one was setup during prepare
     */
    Element encryptedKeyElement = builder.getEncryptedKeyElement();
    encryptedKeyElement.setAttributeNS(null, "Type", "SomeType");
    WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), encryptedKeyElement);

    builder.prependBSTElementToHeader(secHeader);

    Document encryptedDoc = doc;

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

    // Turn off BSP compliance
    WSSecurityEngine newEngine = new WSSecurityEngine();
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    wssConfig.setWsiBSPCompliant(false);
    newEngine.setWssConfig(wssConfig);
    newEngine.processSecurityHeader(encryptedDoc, null, keystoreCallbackHandler, crypto);

    // Now turn on BSP compliance
    wssConfig.setWsiBSPCompliant(true);
    newEngine.setWssConfig(wssConfig);
    try {
        newEngine.processSecurityHeader(encryptedDoc, null, keystoreCallbackHandler, crypto);
        fail("Failure expected on a bad attribute type");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getMessage().contains("bad attribute"));
    }
}

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

public static Element duplicateEncryptedDataInExternalWrapperElement(Element saaj, boolean moveReferenceList) {
    if (moveReferenceList) {
        moveReferenceList(saaj);//from   w  ww . j  a  v a  2 s.com
    }
    Element body = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"),
            true);
    Element encData = getFirstChildElement(body,
            new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData"), true);
    Element newEncData = createNewEncryptedData(encData);
    Element sh = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Header"),
            true);
    Element wsseHeader = getFirstChildElement(sh,
            new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "Security"),
            true);

    Node newWsseHeader = wsseHeader.cloneNode(false);
    Node cur = wsseHeader.getFirstChild();
    String newId = newEncData.getAttributeNS(null, "Id");
    while (cur != null) {
        cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId);
    }
    sh.removeChild(wsseHeader);
    sh.appendChild(newWsseHeader);

    if (!moveReferenceList) {
        updateEncryptedKeyRefList(newWsseHeader, newId);
    }

    Element wrapper = encData.getOwnerDocument().createElementNS(null, "a");
    wrapper.setAttributeNS("http://schemas.xmlsoap.org/soap/envelope/", "mustUnderstand", "0");
    wrapper.setAttributeNS("http://schemas.xmlsoap.org/soap/envelope/", "actor", "foo");
    wrapper.appendChild(newEncData);
    sh.appendChild(wrapper);
    print(saaj.getOwnerDocument());
    return newEncData;
}

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

public static Element addEncryptedDataWithEmbeddedEncryptedKeyInWsseHeader(Element saaj) {
    moveReferenceList(saaj);/*from ww  w .  j  ava 2  s  . co  m*/
    Element body = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"),
            true);
    Element encData = getFirstChildElement(body,
            new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData"), true);

    Element newEncData = (Element) encData.cloneNode(true);
    String newId = newEncData.getAttributeNS(null, "Id") + "b";
    newEncData.setAttributeNS(null, "Id", newId);

    Element encKey = getFirstChildElement(saaj, new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedKey"),
            true);
    Element newEncKey = (Element) encKey.cloneNode(true);
    String newEcId = newEncKey.getAttributeNS(null, "Id") + "b";
    newEncKey.setAttributeNS(null, "Id", newEcId);

    Element keyInfo = getFirstChildElement(newEncData,
            new QName("http://www.w3.org/2000/09/xmldsig#", "KeyInfo"), true);
    Element str = getFirstChildElement(newEncData,
            new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "SecurityTokenReference"),
            true);
    keyInfo.replaceChild(newEncKey, str);

    Element wsseHeader = getFirstChildElement(saaj,
            new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "Security"),
            true);

    Node newWsseHeader = wsseHeader.cloneNode(false);
    Node cur = wsseHeader.getFirstChild();

    while (cur != null) {
        cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId);
    }
    newWsseHeader.appendChild(newEncData);

    Node parent = wsseHeader.getParentNode();
    parent.removeChild(wsseHeader);
    parent.appendChild(newWsseHeader);
    print(saaj.getOwnerDocument());
    return newEncData;

}

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

private static void updateEncryptedKeyRefList(Node wsseHeader, String newId) {
    Element encryptedKey = getFirstChildElement(wsseHeader,
            new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedKey"), true);
    Element ref = getFirstChildElement(encryptedKey,
            new QName("http://www.w3.org/2001/04/xmlenc#", "DataReference"), true);
    Element newRef = (Element) ref.cloneNode(true);
    newRef.setAttributeNS(null, "URI", "#" + newId);
    ref.getParentNode().appendChild(newRef);
}

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

private static Element createNewEncryptedData(Element encData) {
    Element newEncData = (Element) encData.cloneNode(true);
    String id = newEncData.getAttributeNS(null, "Id");
    String newId = id + "b";
    newEncData.setAttributeNS(null, "Id", newId);
    return newEncData;
}

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

private static Node copyHeadersAndUpdateRefList(Node cur, Node dest, String newId) {
    Node temp = cur.cloneNode(true);
    dest.appendChild(temp);//from w  w  w . j av a  2 s .c  o m
    if (newId != null && temp.getNodeType() == Node.ELEMENT_NODE) {
        Element t = (Element) temp;
        if (t.getLocalName().equals("ReferenceList")) {
            Element ref = getFirstChildElement(t,
                    new QName("http://www.w3.org/2001/04/xmlenc#", "DataReference"), true);
            Element newRef = (Element) ref.cloneNode(true);
            newRef.setAttributeNS(null, "URI", "#" + newId);
            t.appendChild(newRef);
        }
    }
    return cur.getNextSibling();
}

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

/**
 * This is a test for processing an Timestamp where it contains a Created element with
 * a ValueType. This should be rejected as per the BSP spec.
 *//*  w  ww  .  ja v  a  2  s  . c  om*/
@org.junit.Test
public void testCreatedValueType() throws Exception {

    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    Element timestampElement = doc.createElementNS(WSConstants.WSU_NS,
            WSConstants.WSU_PREFIX + ":" + WSConstants.TIMESTAMP_TOKEN_LN);

    DateFormat zulu = new XmlSchemaDateFormat();
    Element elementCreated = doc.createElementNS(WSConstants.WSU_NS,
            WSConstants.WSU_PREFIX + ":" + WSConstants.CREATED_LN);
    Date createdDate = new Date();
    long currentTime = createdDate.getTime() + 300000;
    createdDate.setTime(currentTime);
    elementCreated.appendChild(doc.createTextNode(zulu.format(createdDate)));
    elementCreated.setAttributeNS(null, "ValueType", WSConstants.WSS_SAML_KI_VALUE_TYPE);
    timestampElement.appendChild(elementCreated);

    secHeader.getSecurityHeader().appendChild(timestampElement);

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
        LOG.debug(outputString);
    }
    //
    // Do some processing
    //
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    wssConfig.setWsiBSPCompliant(true);
    wssConfig.setValidator(WSSecurityEngine.TIMESTAMP, new NoOpValidator());
    try {
        verify(doc, wssConfig);
        fail("The timestamp validation should have failed");
    } catch (WSSecurityException ex) {
        //
    }

    // Now it should pass...
    wssConfig.setWsiBSPCompliant(false);
    verify(doc, wssConfig);
}

From source file:org.apache.ws.security.message.token.SecurityTokenReference.java

private void createKeyIdentifier(Document doc, String uri, Node node, boolean base64) {
    Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier");
    keyId.setAttributeNS(null, "ValueType", uri);
    if (base64) {
        keyId.setAttributeNS(null, "EncodingType", BinarySecurity.BASE64_ENCODING);
    }//  w w  w  .ja  v a  2s  .  c  o m

    keyId.appendChild(node);
    Element elem = getFirstElement();
    if (elem != null) {
        this.element.replaceChild(keyId, elem);
    } else {
        this.element.appendChild(keyId);
    }
}