Example usage for javax.xml.soap SOAPEnvelope addHeader

List of usage examples for javax.xml.soap SOAPEnvelope addHeader

Introduction

In this page you can find the example usage for javax.xml.soap SOAPEnvelope addHeader.

Prototype

public SOAPHeader addHeader() throws SOAPException;

Source Link

Document

Creates a SOAPHeader object and sets it as the SOAPHeader object for this SOAPEnvelope object.

Usage

From source file:be.fedict.eid.idp.protocol.ws_federation.sts.WSSecuritySoapHandler.java

private void handleOutboundMessage(SOAPMessageContext context) throws SOAPException {
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();
    SOAPHeader soapHeader = soapMessage.getSOAPHeader();
    if (null == soapHeader) {
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
        soapHeader = soapEnvelope.addHeader();
    }// ww  w .  j a v a 2 s.  c o  m

    WSSecHeader wsSecHeader = new WSSecHeader();
    Element securityElement;
    try {
        securityElement = wsSecHeader.insertSecurityHeader(soapPart);
    } catch (WSSecurityException e) {
        throw new SOAPException("WS-Security error: " + e.getMessage(), e);
    }
    soapHeader.removeChild(securityElement);
    soapHeader.appendChild(securityElement);

    WSSecTimestamp wsSecTimeStamp = new WSSecTimestamp();
    wsSecTimeStamp.build(soapPart, wsSecHeader);
}

From source file:be.e_contract.dssp.client.WSSecuritySOAPHandler.java

private void handleOutboundMessage(SOAPMessageContext context) throws WSSecurityException, SOAPException {
    if (null == this.session && null == this.username) {
        return;/*from w w w  .  j a v a2  s . c o m*/
    }
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    SOAPHeader soapHeader;
    try {
        soapHeader = soapMessage.getSOAPHeader();
    } catch (SOAPException e) {
        // WebSphere 8.5.5.1 work-around.
        soapHeader = null;
    }
    if (null == soapHeader) {
        /*
         * Work-around for Axis2.
         */
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
        soapHeader = soapEnvelope.addHeader();
    }

    WSSecHeader wsSecHeader = new WSSecHeader();
    Element securityElement = wsSecHeader.insertSecurityHeader(soapPart);

    if (null != this.session) {
        securityElement.appendChild(
                securityElement.getOwnerDocument().importNode(this.session.getSecurityTokenElement(), true));
    }

    WSSecTimestamp wsSecTimeStamp = new WSSecTimestamp();
    wsSecTimeStamp.setTimeToLive(60);
    wsSecTimeStamp.build(soapPart, wsSecHeader);

    if (null != this.username) {
        WSSecUsernameToken usernameToken = new WSSecUsernameToken();
        usernameToken.setUserInfo(this.username, this.password);
        usernameToken.setPasswordType(WSConstants.PASSWORD_TEXT);
        usernameToken.prepare(soapPart);
        usernameToken.prependToHeader(wsSecHeader);
    }

    if (null != this.session) {
        // work-around for WebSphere
        WSSConfig wssConfig = new WSSConfig();
        wssConfig.setWsiBSPCompliant(false);

        WSSecSignature wsSecSignature = new WSSecSignature(wssConfig);
        wsSecSignature.setSignatureAlgorithm(WSConstants.HMAC_SHA1);
        wsSecSignature.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
        wsSecSignature.setCustomTokenId(this.session.getSecurityTokenElement().getAttributeNS(
                "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Id"));
        wsSecSignature.setSecretKey(this.session.getKey());
        wsSecSignature.prepare(soapPart, null, wsSecHeader);
        Vector<WSEncryptionPart> signParts = new Vector<WSEncryptionPart>();
        SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(soapPart.getDocumentElement());
        signParts.add(new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(),
                soapConstants.getEnvelopeURI(), "Content"));
        signParts.add(new WSEncryptionPart(wsSecTimeStamp.getId()));
        List<Reference> referenceList = wsSecSignature.addReferencesToSign(signParts, wsSecHeader);
        wsSecSignature.computeSignature(referenceList, false, null);
    }

    /*
     * Really needs to be at the end for Axis2 to work. Axiom bug?
     */
    appendSecurityHeader(soapHeader, securityElement);
}

From source file:com.konakart.bl.modules.ordertotal.thomson.HeaderSecrityHandler.java

public boolean handleMessage(SOAPMessageContext smc) {
    Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    if (outboundProperty.booleanValue()) {
        SOAPMessage message = smc.getMessage();

        if (log.isInfoEnabled()) {
            log.info("Adding Credentials : " + getUName() + "/" + getPWord());
        }/*from  ww w  . ja  va 2 s  . c  o  m*/

        try {
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
            envelope.setPrefix("soapenv");
            envelope.getBody().setPrefix("soapenv");

            SOAPHeader header = envelope.addHeader();
            SOAPElement security = header.addChildElement("Security", "wsse",
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

            SOAPElement usernameToken = security.addChildElement("UsernameToken", "wsse");
            usernameToken.addAttribute(new QName("wsu:Id"), "UsernameToken-1");
            usernameToken.setAttribute("wsu:Id", "UsernameToken-1");

            usernameToken.addAttribute(new QName("xmlns:wsu"),
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");

            SOAPElement username = usernameToken.addChildElement("Username", "wsse");
            username.addTextNode(getUName());

            SOAPElement password = usernameToken.addChildElement("Password", "wsse");
            password.setAttribute("Type",
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
            password.addTextNode(getPWord());

            SOAPElement encodingType = usernameToken.addChildElement("Nonce", "wsse");
            encodingType.setAttribute("EncodingType",
                    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary");
            encodingType.addTextNode("Encoding");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return outboundProperty;
}

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

private void handleOutboundMessage(SOAPMessageContext context) throws WSSecurityException,
        ConversationException, SOAPException, IOException, XMLSignatureException, XMLSecurityException {
    LOG.debug("adding WS-Security header");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    SOAPHeader soapHeader = soapMessage.getSOAPHeader();
    if (null == soapHeader) {
        /*/*from  w  w w .  j  a  v  a  2 s. co  m*/
         * Work-around for Axis2.
         */
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
        soapHeader = soapEnvelope.addHeader();
    }

    WSSecHeader wsSecHeader = new WSSecHeader();
    Element securityElement = wsSecHeader.insertSecurityHeader(soapPart);

    addToken(context, securityElement);

    addUsernamePassword(context, soapPart, wsSecHeader);

    WSSecTimestamp wsSecTimeStamp = new WSSecTimestamp();
    wsSecTimeStamp.build(soapPart, wsSecHeader);

    addProofOfPossessionSignature(context, soapMessage, soapPart, wsSecHeader, wsSecTimeStamp);

    addCertificateSignature(context, soapPart, wsSecHeader, wsSecTimeStamp);

    /*
     * Really needs to be at the end for Axis2 to work. Axiom bug?
     */
    appendSecurityHeader(soapHeader, securityElement);
}

From source file:com.profesorfalken.payzen.webservices.sdk.handler.soap.HeaderHandler.java

/**
 * Takes the outgoing SOAP message and modifies it adding the header 
 * information//from w  ww  .ja  v  a  2  s .  c  o  m
 * 
 * @param smc SOAP message context
 * @return 
 */
@Override
public boolean handleMessage(SOAPMessageContext smc) {

    Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    if (Boolean.TRUE.equals(outboundProperty)) {

        SOAPMessage message = smc.getMessage();

        try {
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();

            //Creates header into SOAP envelope
            SOAPHeader header = envelope.getHeader();
            if (header == null) {
                header = envelope.addHeader();
            }

            // Add shopId
            addHeaderField(header, "shopId", this.shopId);

            // Timestamp
            TimeZone tz = TimeZone.getTimeZone("UTC");
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            df.setTimeZone(tz);
            String nowAsISO = df.format(new Date());
            addHeaderField(header, "timestamp", nowAsISO);

            // Mode
            addHeaderField(header, "mode", this.mode);

            // Add requestId
            String requestId = UUID.randomUUID().toString();
            addHeaderField(header, "requestId", requestId);

            // Authentication token
            String tokenString = requestId + nowAsISO;
            addHeaderField(header, "authToken", sign(tokenString, shopKey));

        } catch (SOAPException e) {
            logger.error("Error sending header", e);
        }
    }

    return outboundProperty;

}

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();
    }/*w w w .j  a va2s  .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:eu.payzen.webservices.sdk.handler.soap.HeaderHandler.java

/**
 * Takes the outgoing SOAP message and modifies it adding the header 
 * information//ww w  .j  ava  2 s .  c  om
 * 
 * @param smc SOAP message context
 * @return boolean indicating outbound property
 */
public boolean handleMessage(SOAPMessageContext smc) {

    Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    if (Boolean.TRUE.equals(outboundProperty)) {

        SOAPMessage message = smc.getMessage();

        try {
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();

            //Creates header into SOAP envelope
            SOAPHeader header = envelope.getHeader();
            if (header == null) {
                header = envelope.addHeader();
            }

            // Add shopId
            addHeaderField(header, "shopId", this.shopId);

            // Add User name
            if (wsUser != null) {
                addHeaderField(header, "wsUser", this.wsUser);
            }

            // Add return url
            if (returnUrl != null) {
                addHeaderField(header, "returnUrl", this.returnUrl);
            }

            // Add ecsPaymentId
            if (ecsPaymentId != null) {
                addHeaderField(header, "ecsPaymentId", this.ecsPaymentId);
            }

            // Add remoteId
            if (remoteId != null) {
                addHeaderField(header, "remoteId", this.remoteId);
            }

            //DynamicHeaders
            if (dynamicHeaders != null) {
                for (String key : dynamicHeaders.keySet()) {
                    String value = dynamicHeaders.get(key);
                    if (value != null) {
                        addHeaderField(header, key, value);
                    }
                }
            }

            // Timestamp
            TimeZone tz = TimeZone.getTimeZone("UTC");
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
            df.setTimeZone(tz);
            String nowAsISO = df.format(new Date());
            addHeaderField(header, "timestamp", nowAsISO);

            // Mode
            addHeaderField(header, "mode", this.mode);

            // Add requestId
            String requestId = UUID.randomUUID().toString();
            addHeaderField(header, "requestId", requestId);

            // Authentication token
            String tokenString = requestId + nowAsISO;
            addHeaderField(header, "authToken", sign(tokenString, shopKey));

        } catch (SOAPException e) {
            logger.error("Error sending header", e);
        }
    }

    return outboundProperty;

}

From source file:com.cisco.dvbu.ps.common.adapters.connect.SoapHttpConnector.java

private Document send(SoapHttpConnectorCallback cb, String requestXml) throws AdapterException {
    log.debug("Entered send: " + cb.getName());

    // set up the factories and create a SOAP factory
    SOAPConnection soapConnection;
    Document doc = null;//w  w  w. j a  v  a 2  s  .c o  m
    URL endpoint = null;
    try {
        soapConnection = SOAPConnectionFactory.newInstance().createConnection();
        MessageFactory messageFactory = MessageFactory.newInstance();

        // Create a message from the message factory.
        SOAPMessage soapMessage = messageFactory.createMessage();

        // Set the SOAP Action here
        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", cb.getAction());

        // set credentials
        //         String authorization = new sun.misc.BASE64Encoder().encode((shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes());
        String authorization = new String(org.apache.commons.codec.binary.Base64.encodeBase64(
                (shConfig.getUser() + "@" + shConfig.getDomain() + ":" + shConfig.getPassword()).getBytes()));
        headers.addHeader("Authorization", "Basic " + authorization);
        log.debug("Authentication: " + authorization);

        // create a SOAP part have populate the envelope
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.setEncodingStyle(SOAPConstants.URI_NS_SOAP_ENCODING);

        SOAPHeader head = envelope.getHeader();
        if (head == null)
            head = envelope.addHeader();

        // create a SOAP body
        SOAPBody body = envelope.getBody();

        log.debug("Request XSL Style Sheet:\n"
                + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(cb.getRequestBodyXsl())));

        // convert request string to document and then transform
        body.addDocument(XmlUtils.xslTransform(XmlUtils.stringToDocument(requestXml), cb.getRequestBodyXsl()));

        // build the request structure
        soapMessage.saveChanges();
        log.debug("Soap request successfully built: ");
        log.debug("  Body:\n"
                + XMLUtils.getPrettyXml(XMLUtils.getDocumentFromString(XmlUtils.nodeToString(body))));

        if (shConfig.useProxy()) {
            System.setProperty("http.proxySet", "true");
            System.setProperty("http.proxyHost", shConfig.getProxyHost());
            System.setProperty("http.proxyPort", "" + shConfig.getProxyPort());
            if (shConfig.useProxyCredentials()) {
                System.setProperty("http.proxyUser", shConfig.getProxyUser());
                System.setProperty("http.proxyPassword", shConfig.getProxyPassword());
            }
        }

        endpoint = new URL(shConfig.getEndpoint(cb.getEndpoint()));

        // now make that call over the SOAP connection
        SOAPMessage reply = null;
        AdapterException ae = null;

        for (int i = 1; (i <= shConfig.getRetryAttempts() && reply == null); i++) {
            log.debug("Attempt " + i + ": sending request to endpoint: " + endpoint);
            try {
                reply = soapConnection.call(soapMessage, endpoint);
                log.debug("Attempt " + i + ": received response: " + reply);
            } catch (Exception e) {
                ae = new AdapterException(502, String.format(AdapterConstants.ADAPTER_EM_CONNECTION, endpoint),
                        e);
                Thread.sleep(100);
            }
        }

        // close down the connection
        soapConnection.close();

        if (reply == null)
            throw ae;

        SOAPFault fault = reply.getSOAPBody().getFault();
        if (fault == null) {
            doc = reply.getSOAPBody().extractContentAsDocument();
        } else {
            // Extracts the entire Soap Fault message coming back from CIS
            String faultString = XmlUtils.nodeToString(fault);
            throw new AdapterException(503, faultString, null);
        }
    } catch (AdapterException e) {
        throw e;
    } catch (Exception e) {
        throw new AdapterException(504,
                String.format(AdapterConstants.ADAPTER_EM_CONNECTION, shConfig.getEndpoint(cb.getEndpoint())),
                e);
    } finally {
        if (shConfig.useProxy()) {
            System.setProperty("http.proxySet", "false");
        }
    }
    log.debug("Exiting send: " + cb.getName());

    return doc;
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

private Document createSOAPFaultDocument(String faultString) throws SOAPException {
    MessageFactory factory = MessageFactory.newInstance();
    SOAPMessage message = factory.createMessage();
    SOAPPart sp = message.getSOAPPart();
    SOAPEnvelope se = sp.getEnvelope();
    se.setPrefix(SOAP_PREFIX);/*from   ww w  . j  a  v  a 2 s .c o  m*/
    se.getHeader().detachNode();
    se.addHeader();
    se.getBody().detachNode();
    SOAPBody body = se.addBody();
    SOAPFault fault = body.addFault();
    Name faultCode = se.createName("Client", null, SOAPConstants.URI_NS_SOAP_ENVELOPE);
    fault.setFaultCode(faultCode);
    fault.setFaultString(faultString);
    return se.getOwnerDocument();
}

From source file:com.qubit.solution.fenixedu.bennu.webservices.services.client.WebServiceClientHandler.java

public boolean handleMessage(SOAPMessageContext smc) {

    boolean isOutbound = (Boolean) smc.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);

    if (isOutbound) {
        try {/*from ww  w . ja  v  a2  s .c  o  m*/

            final byte[] sessionKey = generateAESKey();
            final String encriptedPassword = cypher(sessionKey, password);
            final String encriptedTimestamp = cypher(sessionKey, getTimestamp());
            final String nonce = cypherSessionKey(getPublicKey(), sessionKey);

            SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();
            SOAPFactory soapFactory = SOAPFactory.newInstance();

            // WSSecurity <Security> header
            SOAPElement wsSecHeaderElm = soapFactory.createElement("Security", AUTH_PREFIX, AUTH_NS);
            SOAPElement userNameTokenElm = soapFactory.createElement("UsernameToken", AUTH_PREFIX, AUTH_NS);
            // Username
            SOAPElement userNameElm = soapFactory.createElement("Username", AUTH_PREFIX, AUTH_NS);
            userNameElm.addTextNode(username);
            // Password
            SOAPElement passwdElm = soapFactory.createElement("Password", AUTH_PREFIX, AUTH_NS);
            passwdElm.addTextNode(encriptedPassword);
            // Nonce
            SOAPElement nonceElm = soapFactory.createElement("Nonce", AUTH_PREFIX, AUTH_NS);
            nonceElm.addTextNode(nonce);
            // Created
            SOAPElement createdElm = soapFactory.createElement("Created", AUTH_PREFIX, AUTH_NS);
            createdElm.addTextNode(encriptedTimestamp);

            userNameTokenElm.addChildElement(userNameElm);
            userNameTokenElm.addChildElement(passwdElm);
            userNameTokenElm.addChildElement(nonceElm);
            userNameTokenElm.addChildElement(createdElm);

            // add child elements to the root element
            wsSecHeaderElm.addChildElement(userNameTokenElm);

            SOAPHeader sh = envelope.getHeader();
            if (sh == null) {
                // create SOAPHeader instance for SOAP envelope
                sh = envelope.addHeader();
            }

            // add SOAP element for header to SOAP header object
            sh.addChildElement(wsSecHeaderElm);

        } catch (Exception e) {
            throw new RuntimeException("Problems in the securityHandler", e);
        }
    }
    return true;
}