Example usage for javax.xml.soap SOAPHeaderElement setMustUnderstand

List of usage examples for javax.xml.soap SOAPHeaderElement setMustUnderstand

Introduction

In this page you can find the example usage for javax.xml.soap SOAPHeaderElement setMustUnderstand.

Prototype

public void setMustUnderstand(boolean mustUnderstand);

Source Link

Document

Sets the mustUnderstand attribute for this SOAPHeaderElement object to be either true or false.

Usage

From source file:com.github.thesmartenergy.cnr.SmartChargingProvider.java

private SOAPMessage createSoapMessage(GetChargingPlans value) throws PEPException {
    try {/* ww  w  .  j ava 2 s .  c o m*/
        JAXBContext jaxbContext = JAXBContext.newInstance(GetChargingPlans.class);
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        jaxbContext.createMarshaller().marshal(value, document);

        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        soapMessage.getSOAPBody().addDocument(document);
        Name headername = soapMessage.getSOAPPart().getEnvelope().createName("Action", "",
                "http://schemas.microsoft.com/ws/2005/05/addressing/none/");
        SOAPHeaderElement soapAction = soapMessage.getSOAPHeader().addHeaderElement(headername);
        soapAction.setMustUnderstand(true);
        soapAction.setTextContent("http://tempuri.org/ISmartCharging/GetChargingPlans");
        return soapMessage;
    } catch (DOMException | JAXBException | ParserConfigurationException | SOAPException ex) {
        throw new PEPException(ex);
    }
}

From source file:be.agiv.security.handler.WSAddressingHandler.java

private void handleOutboundMessage(SOAPMessageContext context) throws SOAPException {
    LOG.debug("adding WS-Addressing headers");
    SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
    SOAPHeader header = envelope.getHeader();
    if (null == header) {
        header = envelope.addHeader();/*from www  .ja va 2  s  .c  om*/
    }

    String wsuPrefix = null;
    String wsAddrPrefix = null;
    Iterator namespacePrefixesIter = envelope.getNamespacePrefixes();
    while (namespacePrefixesIter.hasNext()) {
        String namespacePrefix = (String) namespacePrefixesIter.next();
        String namespace = envelope.getNamespaceURI(namespacePrefix);
        if (WSConstants.WS_ADDR_NAMESPACE.equals(namespace)) {
            wsAddrPrefix = namespacePrefix;
        } else if (WSConstants.WS_SECURITY_UTILITY_NAMESPACE.equals(namespace)) {
            wsuPrefix = namespacePrefix;
        }
    }
    if (null == wsAddrPrefix) {
        wsAddrPrefix = getUniquePrefix("a", envelope);
        envelope.addNamespaceDeclaration(wsAddrPrefix, WSConstants.WS_ADDR_NAMESPACE);
    }
    if (null == wsuPrefix) {
        /*
         * Using "wsu" is very important for the IP-STS X509 credential.
         * Apparently the STS refuses when the namespace prefix of the
         * wsu:Id on the WS-Addressing To element is different from the
         * wsu:Id prefix on the WS-Security timestamp.
         */
        wsuPrefix = "wsu";
        envelope.addNamespaceDeclaration(wsuPrefix, WSConstants.WS_SECURITY_UTILITY_NAMESPACE);
    }

    SOAPFactory factory = SOAPFactory.newInstance();

    SOAPHeaderElement actionHeaderElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "Action", wsAddrPrefix));
    actionHeaderElement.setMustUnderstand(true);
    actionHeaderElement.addTextNode(this.action);

    SOAPHeaderElement messageIdElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "MessageID", wsAddrPrefix));
    String messageId = "urn:uuid:" + UUID.randomUUID().toString();
    context.put(MESSAGE_ID_CONTEXT_ATTRIBUTE, messageId);
    messageIdElement.addTextNode(messageId);

    SOAPHeaderElement replyToElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "ReplyTo", wsAddrPrefix));
    SOAPElement addressElement = factory.createElement("Address", wsAddrPrefix, WSConstants.WS_ADDR_NAMESPACE);
    addressElement.addTextNode("http://www.w3.org/2005/08/addressing/anonymous");
    replyToElement.addChildElement(addressElement);

    SOAPHeaderElement toElement = header
            .addHeaderElement(new QName(WSConstants.WS_ADDR_NAMESPACE, "To", wsAddrPrefix));
    toElement.setMustUnderstand(true);

    toElement.addTextNode(this.to);

    String toIdentifier = "to-id-" + UUID.randomUUID().toString();
    toElement.addAttribute(new QName(WSConstants.WS_SECURITY_UTILITY_NAMESPACE, "Id", wsuPrefix), toIdentifier);
    try {
        toElement.setIdAttributeNS(WSConstants.WS_SECURITY_UTILITY_NAMESPACE, "Id", true);
    } catch (UnsupportedOperationException e) {
        // Axis2 has missing implementation of setIdAttributeNS
        LOG.error("error setting Id attribute: " + e.getMessage());
    }
    context.put(TO_ID_CONTEXT_ATTRIBUTE, toIdentifier);
}

From source file:org.apache.taverna.activities.wsdl.T2WSDLSOAPInvoker.java

@Override
protected void addSoapHeader(SOAPEnvelope envelope) throws SOAPException {
    if (wsrfEndpointReference != null) {

        // Extract elements
        // Add WSA-stuff
        // Add elements

        Document wsrfDoc;/*from  w w w .  j  a va  2 s. co m*/
        try {
            wsrfDoc = parseWsrfEndpointReference(wsrfEndpointReference);
        } catch (Exception e) {
            logger.warn("Could not parse endpoint reference, ignoring:\n" + wsrfEndpointReference, e);
            return;
        }

        Element wsrfRoot = wsrfDoc.getDocumentElement();

        Element endpointRefElem = null;
        if (!wsrfRoot.getNamespaceURI().equals(WSA200403NS)
                || !wsrfRoot.getLocalName().equals(ENDPOINT_REFERENCE)) {
            // Only look for child if the parent is not an EPR
            NodeList nodes = wsrfRoot.getChildNodes();
            for (int i = 0, n = nodes.getLength(); i < n; i++) {
                Node node = nodes.item(i);
                if (Node.ELEMENT_NODE == node.getNodeType() && node.getLocalName().equals(ENDPOINT_REFERENCE)
                        && node.getNamespaceURI().equals(WSA200403NS)) {
                    // Support wrapped endpoint reference for backward compatibility
                    // and convenience (T2-677)
                    endpointRefElem = (Element) node;
                    break;
                }
            }
        }

        if (endpointRefElem == null) {
            logger.warn("Unexpected element name for endpoint reference, but inserting anyway: "
                    + wsrfRoot.getTagName());
            endpointRefElem = wsrfRoot;
        }

        Element refPropsElem = null;
        NodeList nodes = endpointRefElem.getChildNodes();
        for (int i = 0, n = nodes.getLength(); i < n; i++) {
            Node node = nodes.item(i);
            if (Node.ELEMENT_NODE == node.getNodeType() && node.getLocalName().equals(REFERENCE_PROPERTIES)
                    && node.getNamespaceURI().equals(WSA200403NS)) {
                refPropsElem = (Element) node;
                break;
            }
        }
        if (refPropsElem == null) {
            logger.warn("Could not find " + REFERENCE_PROPERTIES);
            return;
        }

        SOAPHeader header = envelope.getHeader();
        if (header == null) {
            header = envelope.addHeader();
        }

        NodeList refProps = refPropsElem.getChildNodes();

        for (int i = 0, n = refProps.getLength(); i < n; i++) {
            Node node = refProps.item(i);

            if (Node.ELEMENT_NODE == node.getNodeType()) {
                SOAPElement soapElement = SOAPFactory.newInstance().createElement((Element) node);
                header.addChildElement(soapElement);

                Iterator<SOAPHeaderElement> headers = header.examineAllHeaderElements();
                while (headers.hasNext()) {
                    SOAPHeaderElement headerElement = headers.next();
                    if (headerElement.getElementQName().equals(soapElement.getElementQName())) {
                        headerElement.setMustUnderstand(false);
                        headerElement.setActor(null);
                    }
                }
            }
        }
    }
}

From source file:org.apache.ws.security.handler.WSS4JHandler.java

/**
 * handle responses/*from  w w w.  j  av  a 2 s.  c  om*/
 *
 * @param mc
 * @param reqData
 * @return true on successful processing
 * @throws WSSecurityException
 */
public boolean doReceiver(MessageContext mc, RequestData reqData, boolean isRequest)
        throws WSSecurityException {

    Vector actions = new Vector();
    String action = (String) getOption(WSHandlerConstants.RECEIVE + '.' + WSHandlerConstants.ACTION);
    if (action == null) {
        action = (String) getOption(WSHandlerConstants.ACTION);
        if (action == null) {
            action = (String) mc.getProperty(WSHandlerConstants.ACTION);
        }
    }
    if (action == null) {
        throw new JAXRPCException("WSS4JHandler: No action defined");
    }
    int doAction = WSSecurityUtil.decodeAction(action, actions);

    String actor = (String) getOption(WSHandlerConstants.ACTOR);

    SOAPMessage message = ((SOAPMessageContext) mc).getMessage();
    SOAPPart sPart = message.getSOAPPart();
    Document doc = null;
    try {
        doc = messageToDocument(message);
    } catch (Exception ex) {
        if (doDebug) {
            log.debug(ex.getMessage(), ex);
        }
        throw new JAXRPCException("WSS4JHandler: cannot convert into document", ex);
    }
    /*
    * Check if it's a fault. Don't process faults.
    *
    */
    SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(doc.getDocumentElement());
    if (WSSecurityUtil.findElement(doc.getDocumentElement(), "Fault", soapConstants.getEnvelopeURI()) != null) {
        return false;
    }

    /*
    * To check a UsernameToken or to decrypt an encrypted message we need
    * a password.
    */
    CallbackHandler cbHandler = null;
    if ((doAction & (WSConstants.ENCR | WSConstants.UT)) != 0) {
        cbHandler = getPasswordCB(reqData);
    }

    /*
    * Get and check the Signature specific parameters first because they
    * may be used for encryption too.
    */
    doReceiverAction(doAction, reqData);

    Vector wsResult = null;
    try {
        wsResult = secEngine.processSecurityHeader(doc, actor, cbHandler, reqData.getSigCrypto(),
                reqData.getDecCrypto());
    } catch (WSSecurityException ex) {
        if (doDebug) {
            log.debug(ex.getMessage(), ex);
        }
        throw new JAXRPCException("WSS4JHandler: security processing failed", ex);
    }
    if (wsResult == null) { // no security header found
        if (doAction == WSConstants.NO_SECURITY) {
            return true;
        } else {
            throw new JAXRPCException("WSS4JHandler: Request does not contain required Security header");
        }
    }
    if (reqData.getWssConfig().isEnableSignatureConfirmation() && !isRequest) {
        checkSignatureConfirmation(reqData, wsResult);
    }

    /*
    * If we had some security processing, get the original
    * SOAP part of Axis' message and replace it with new SOAP
    * part. This new part may contain decrypted elements.
    */

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    XMLUtils.outputDOM(doc, os, true);
    try {
        sPart.setContent(new StreamSource(new ByteArrayInputStream(os.toByteArray())));
    } catch (SOAPException se) {
        if (doDebug) {
            log.debug(se.getMessage(), se);
        }
        throw new JAXRPCException("Couldn't set content on SOAPPart" + se.getMessage(), se);
    }

    if (doDebug) {
        log.debug("Processed received SOAP request");
    }

    /*
    * After setting the new current message, probably modified because
    * of decryption, we need to locate the security header. That is,
    * we force Axis (with getSOAPEnvelope()) to parse the string, build
    * the new header. Then we examine, look up the security header
    * and set the header as processed.
    *
    * Please note: find all header elements that contain the same
    * actor that was given to processSecurityHeader(). Then
    * check if there is a security header with this actor.
    */

    SOAPHeader sHeader = null;
    try {
        sHeader = message.getSOAPPart().getEnvelope().getHeader();
    } catch (Exception ex) {
        if (doDebug) {
            log.debug(ex.getMessage(), ex);
        }
        throw new JAXRPCException("WSS4JHandler: cannot get SOAP header after security processing", ex);
    }

    Iterator headers = sHeader.examineHeaderElements(actor);

    SOAPHeaderElement headerElement = null;
    while (headers.hasNext()) {
        SOAPHeaderElement hE = (SOAPHeaderElement) headers.next();
        if (hE.getElementName().getLocalName().equals(WSConstants.WSSE_LN)
                && ((Node) hE).getNamespaceURI().equals(WSConstants.WSSE_NS)) {
            headerElement = hE;
            break;
        }
    }

    /* JAXRPC conversion changes */
    headerElement.setMustUnderstand(false); // is this sufficient?

    /*
    * Now we can check the certificate used to sign the message.
    * In the following implementation the certificate is only trusted
    * if either it itself or the certificate of the issuer is installed
    * in the keystore.
    *
    * Note: the method verifyTrust(X509Certificate) allows custom
    * implementations with other validation algorithms for subclasses.
    */

    // Extract the signature action result from the action vector

    WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.SIGN);

    if (actionResult != null) {
        X509Certificate returnCert = (X509Certificate) actionResult
                .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);

        if (returnCert != null && !verifyTrust(returnCert, reqData)) {
            throw new JAXRPCException("WSS4JHandler: The certificate used for the signature is not trusted");
        }
    }

    /*
    * Perform further checks on the timestamp that was transmitted in the header.
    * In the following implementation the timestamp is valid if it was
    * created after (now-ttl), where ttl is set on server side, not by the client.
    *
    * Note: the method verifyTimestamp(Timestamp) allows custom
    * implementations with other validation algorithms for subclasses.
    */

    // Extract the timestamp action result from the action vector
    actionResult = WSSecurityUtil.fetchActionResult(wsResult, WSConstants.TS);

    if (actionResult != null) {
        Timestamp timestamp = (Timestamp) actionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);

        if (timestamp != null && reqData.getWssConfig().isTimeStampStrict()
                && !verifyTimestamp(timestamp, decodeTimeToLive(reqData))) {
            throw new JAXRPCException("WSS4JHandler: The timestamp could not be validated");
        }
    }

    /*
    * now check the security actions: do they match, in right order?
    */
    if (!checkReceiverResults(wsResult, actions)) {
        throw new JAXRPCException("WSS4JHandler: security processing failed (actions mismatch)");
    }

    /*
    * All ok up to this point. Now construct and setup the
    * security result structure. The service may fetch this
    * and check it.
    */
    Vector results = null;
    if ((results = (Vector) mc.getProperty(WSHandlerConstants.RECV_RESULTS)) == null) {
        results = new Vector();
        mc.setProperty(WSHandlerConstants.RECV_RESULTS, results);
    }
    WSHandlerResult rResult = new WSHandlerResult(actor, wsResult);
    results.add(0, rResult);
    if (doDebug) {
        log.debug("WSS4JHandler: exit invoke()");
    }

    return true;
}

From source file:org.wso2.carbon.identity.sso.saml.util.SAMLSOAPUtils.java

/**
 *
 * @param samlRes SAML Response/*from  w  w  w.  j  a v a2  s. c  o m*/
 * @param acUrl Assertion Consumer URL
 * @return
 */
public static String createSOAPMessage(String samlRes, String acUrl)
        throws TransformerException, SOAPException {
    SOAPMessage soapMsg;
    MessageFactory factory = MessageFactory.newInstance();
    soapMsg = factory.createMessage();
    SOAPPart part = soapMsg.getSOAPPart();
    SOAPEnvelope envelope = part.getEnvelope();
    SOAPHeader header = envelope.getHeader();
    SOAPHeaderElement soapHeaderElement = header.addHeaderElement(
            envelope.createName(SAMLECPConstants.SOAPECPHeaderElements.SOAP_ECP_HEADER_LOCAL_NAME,
                    SAMLECPConstants.SOAPECPHeaderElements.SOAP_ECP_HEADER_PREFIX,
                    SAMLECPConstants.SOAPECPHeaderElements.SOAP_ECP_HEADER_URI));
    soapHeaderElement.setMustUnderstand(true);
    soapHeaderElement.setActor(SAMLECPConstants.SOAPHeaderElements.SOAP_HEADER_ELEMENT_ACTOR);
    soapHeaderElement.addAttribute(new QName(SAMLECPConstants.SOAPHeaderElements.SOAP_HEADER_ELEMENT_ACS_URL),
            acUrl);
    SOAPBody body = envelope.getBody();
    String rawxml = "<![CDATA[" + samlRes + "]]>";
    body.addTextNode(rawxml);
    return convertSOAPMsgToString(soapMsg).replace("<![CDATA[", "").replace("]]>", "");
}