Example usage for javax.xml.ws.handler.soap SOAPMessageContext getMessage

List of usage examples for javax.xml.ws.handler.soap SOAPMessageContext getMessage

Introduction

In this page you can find the example usage for javax.xml.ws.handler.soap SOAPMessageContext getMessage.

Prototype

public SOAPMessage getMessage();

Source Link

Document

Gets the SOAPMessage from this message context.

Usage

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. ja v  a  2 s  . c o m*/
    }

    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:be.fedict.eid.idp.sp.protocol.ws_federation.sts.LoggingSoapHandler.java

public boolean handleMessage(SOAPMessageContext context) {
    if (false == LOG.isDebugEnabled()) {
        return true;
    }//from   w ww  .jav a 2  s .  c  om
    LOG.debug("handle message");
    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    LOG.debug("outbound message: " + outboundProperty);
    SOAPMessage soapMessage = context.getMessage();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {
        soapMessage.writeTo(output);
    } catch (Exception e) {
        LOG.error("SOAP error: " + e.getMessage());
    }
    LOG.debug("SOAP message: " + output.toString());
    return true;
}

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;// www . j av a  2  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:be.fedict.hsm.ws.impl.WSSecuritySOAPHandler.java

private void handleInboundMessage(SOAPMessageContext context) throws WSSecurityException, SOAPException {
    LOG.debug("checking WS-Security header");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    Crypto crypto = new WSSecurityCrypto();
    WSSConfig wssConfig = new WSSConfig();
    wssConfig.setWsiBSPCompliant(true);/*  w w  w . j a v a 2 s.  co m*/
    secEngine.setWssConfig(wssConfig);
    List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(soapPart, null, null, crypto);
    if (null == results) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security results");
    }

    WSSecurityEngineResult timeStampActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.TS);
    if (null == timeStampActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security timestamp result");
    }

    Timestamp receivedTimestamp = (Timestamp) timeStampActionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);
    if (null == receivedTimestamp) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security timestamp");
    }

    LOG.debug("WS-Security timestamp created: " + receivedTimestamp.getCreated());
    LOG.debug("WS-Security timestamp expires: " + receivedTimestamp.getExpires());
    String timeStampIdRef = "#" + receivedTimestamp.getID();

    WSSecurityEngineResult bstActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
    if (null == bstActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no WS-Security BinarySecurityToken");
    }
    BinarySecurity binarySecurityToken = (BinarySecurity) bstActionResult
            .get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);

    WSSecurityEngineResult signActionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN);
    if (null == signActionResult) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("no valid XML signature");
    }
    String signatureMethod = (String) signActionResult.get(WSSecurityEngineResult.TAG_SIGNATURE_METHOD);
    LOG.debug("signature method: " + signatureMethod);
    if (false == "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256".equals(signatureMethod)) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError();
        throw new SecurityException("signature algo should be RSA-SHA256");
    }
    X509Certificate certificate = (X509Certificate) signActionResult
            .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
    LOG.debug("certificate subject: " + certificate.getSubjectX500Principal());
    List<WSDataRef> wsDataRefs = (List<WSDataRef>) signActionResult
            .get(WSSecurityEngineResult.TAG_DATA_REF_URIS);

    SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
    SOAPBody soapBody = soapEnvelope.getBody();
    String bodyIdRef = "#" + soapBody.getAttributeNS(WSU_NAMESPACE, "Id");
    String bstIdRef = "#" + binarySecurityToken.getID();

    boolean timestampDigested = false;
    boolean bodyDigested = false;
    boolean tokenDigested = false;
    for (WSDataRef wsDataRef : wsDataRefs) {
        String wsuId = wsDataRef.getWsuId();
        LOG.debug("signed wsu:Id: " + wsuId);
        LOG.debug("digest algorithm: " + wsDataRef.getDigestAlgorithm());
        if (false == "http://www.w3.org/2001/04/xmlenc#sha256".equals(wsDataRef.getDigestAlgorithm())) {
            this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
            throw new SecurityException("digest algorithm should be SHA256");
        }
        if (timeStampIdRef.equals(wsuId)) {
            timestampDigested = true;
        } else if (bodyIdRef.equals(wsuId)) {
            bodyDigested = true;
        } else if (bstIdRef.equals(wsuId)) {
            tokenDigested = true;
        }
    }
    if (false == timestampDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("timestamp not digested");
    }
    if (false == bodyDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("SOAP Body not digested");
    }
    if (false == tokenDigested) {
        this.securityAuditGeneratorBean.webServiceAuthenticationError(certificate);
        throw new SecurityException("BinarySecurityToken not digested");
    }

    context.put(X509_ATTRIBUTE, certificate);
}

From source file:com.wavemaker.runtime.ws.jaxws.SOAPLoggingHandler.java

private void log(SOAPMessageContext context) {
    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    String messageText;//ww  w  .  j  av a2  s.c  o  m
    if (outboundProperty.booleanValue()) {
        messageText = "Outbound SOAP message:\n";
    } else {
        messageText = "Inbound SOAP message:\n";
    }

    SOAPMessage message = context.getMessage();
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        message.writeTo(baos);
        log.debug(messageText + baos.toString());
        baos.close();
    } catch (Exception e) {
        log.error(e);
    }
}

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

private void handleInboundMessage(SOAPMessageContext context) throws WSSecurityException {
    LOG.debug("checking WS-Security header");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(soapPart, null, null, null);
    if (null == results) {
        throw new SecurityException("no WS-Security results");
    }//from   w  w  w. jav  a  2 s  .co  m

    WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.TS);
    if (null == actionResult) {
        throw new SecurityException("no WS-Security timestamp result");
    }

    Timestamp receivedTimestamp = (Timestamp) actionResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);
    if (null == receivedTimestamp) {
        throw new SecurityException("no WS-Security timestamp");
    }

    LOG.debug("WS-Security timestamp created: " + receivedTimestamp.getCreated());
    LOG.debug("WS-Security timestamp expires: " + receivedTimestamp.getExpires());
}

From source file:be.fedict.trust.xkms2.WSSecurityServerHandler.java

/**
 * {@inheritDoc}/*ww  w .ja  v a  2s.  co  m*/
 */
public boolean handleMessage(SOAPMessageContext soapMessageContext) {

    LOG.debug("handle message");

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

    SOAPMessage soapMessage = soapMessageContext.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    if (true == outboundProperty.booleanValue()) {
        handleOutboundDocument(soapPart, soapMessageContext);
    } else {
        handleInboundDocument(soapPart, soapMessageContext);
    }

    return true;
}

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

/**
 * Takes the outgoing SOAP message and modifies it adding the header 
 * information/*w w  w . j  a v  a 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.konakart.bl.modules.ordertotal.thomson.HeaderLoggingHandler.java

/**
 * Outputs the soap msg to the logger/*from   ww w. java  2s .com*/
 * 
 * @param context
 */
public void logSoapMsg(SOAPMessageContext context) {
    if (!log.isDebugEnabled()) {
        return;
    }

    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    String msgType = null;
    if (outboundProperty.booleanValue()) {
        msgType = "Request:";
    } else {
        msgType = "Response:";
    }

    SOAPMessage message = context.getMessage();
    try {
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer tf = tff.newTransformer();

        // Set formatting

        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        Source sc = message.getSOAPPart().getContent();

        ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(streamOut);
        tf.transform(sc, result);

        if (log.isDebugEnabled()) {
            log.debug(msgType + "\n" + streamOut.toString()
                    + "\n------------------------------------------------------------------------");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:hornet.framework.webservice.SOAPLoggingHandler.java

/**
 * log le message SOAP/*from   w w w . j ava 2  s . c  o  m*/
 *
 * @param smc
 *            SOAPMessageContext
 */
private void logSOAP(final SOAPMessageContext smc) {

    final Boolean outboundProperty = (Boolean) smc.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (outboundProperty.booleanValue()) {
        LOGGER.debug("\nMessage SOAP envoye:");
    } else {
        LOGGER.debug("\nMessage SOAP recu:");
    }
    final SOAPMessage message = smc.getMessage();
    try {
        // Create transformer
        final TransformerFactory tff = TransformerFactory.newInstance();
        final Transformer tranf = tff.newTransformer();

        // Get reply content
        final Source src = message.getSOAPPart().getContent();

        // Set output transformation
        final ByteArrayOutputStream streamOut = new ByteArrayOutputStream();
        final StreamResult result = new StreamResult(streamOut);
        tranf.transform(src, result);

        LOGGER.debug(streamOut.toString(CharEncoding.UTF_8));
    } catch (final TransformerConfigurationException e) {
        LOGGER.error(ERROR_MSG, e);
    } catch (final SOAPException e) {
        LOGGER.error(ERROR_MSG, e);
    } catch (final TransformerException e) {
        LOGGER.error(ERROR_MSG, e);
    } catch (final UnsupportedEncodingException e) {
        LOGGER.error(ERROR_MSG, e);
    }

}