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.e_contract.mycarenet.xkms2.KeyBindingAuthenticationSignatureSOAPHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (false == outboundProperty) {
        return true;
    }//from   w ww  .  jav a 2  s.  c  o  m
    LOG.debug("adding key binding authentication signature");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    String requestElementName;
    if (null != this.prototypeKeyBindingId) {
        requestElementName = "RegisterRequest";
        this.referenceUri = "#" + this.prototypeKeyBindingId;
    } else if (null != this.revokeKeyBindingId) {
        requestElementName = "RevokeRequest";
        this.referenceUri = "#" + this.revokeKeyBindingId;
    } else {
        LOG.error("missing key binding id");
        return false;
    }
    NodeList requestNodeList = soapPart.getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE,
            requestElementName);
    Element requestElement = (Element) requestNodeList.item(0);
    if (null == requestElement) {
        LOG.error("request element not present");
        return false;
    }
    Document xkmsDocument;
    try {
        xkmsDocument = copyDocument(requestElement);
    } catch (ParserConfigurationException e) {
        LOG.error("error copying XKMS request: " + e.getMessage(), e);
        return false;
    }

    NodeList keyBindingAuthenticationNodeList = xkmsDocument
            .getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "KeyBindingAuthentication");
    Element keyBindingAuthenticationElement = (Element) keyBindingAuthenticationNodeList.item(0);
    try {
        prepareDocument(xkmsDocument);
        addSignature(keyBindingAuthenticationElement);
    } catch (Exception e) {
        LOG.error("error adding authn signature: " + e.getMessage(), e);
        return false;
    }

    Node signatureNode = soapPart.importNode(keyBindingAuthenticationElement.getFirstChild(), true);

    keyBindingAuthenticationNodeList = soapPart.getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE,
            "KeyBindingAuthentication");
    keyBindingAuthenticationElement = (Element) keyBindingAuthenticationNodeList.item(0);
    keyBindingAuthenticationElement.appendChild(signatureNode);
    return true;
}

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   ww w. ja  va  2s .c  o 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:be.e_contract.mycarenet.xkms.ProofOfPossessionSignatureSOAPHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    if (null == this.sessionKey) {
        return true;
    }/*from www . j  a v  a2  s .  c  o  m*/
    if (null == this.prototypeKeyBindingId) {
        return true;
    }

    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (false == outboundProperty) {
        return true;
    }
    LOG.debug("adding proof of possession signature");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    NodeList registerRequestNodeList = soapPart.getElementsByTagNameNS(XKMS_NAMESPACE, "Register");
    Element registerRequestElement = (Element) registerRequestNodeList.item(0);
    Document xkmsDocument;
    try {
        xkmsDocument = copyDocument(registerRequestElement);
    } catch (ParserConfigurationException e) {
        LOG.error("error copying XKMS request: " + e.getMessage(), e);
        return false;
    }

    NodeList proofOfPossessionNodeList = xkmsDocument.getElementsByTagNameNS(XKMS_NAMESPACE,
            "ProofOfPossession");
    Element proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    try {
        prepareDocument(xkmsDocument);
        addSignature(proofOfPossessionElement);
    } catch (Exception e) {
        LOG.error("error adding proof signature: " + e.getMessage(), e);
        return false;
    }
    Node signatureNode = soapPart.importNode(proofOfPossessionElement.getFirstChild(), true);

    proofOfPossessionNodeList = soapPart.getElementsByTagNameNS(XKMS_NAMESPACE, "ProofOfPossession");
    proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    proofOfPossessionElement.appendChild(signatureNode);
    return true;
}

From source file:be.e_contract.mycarenet.xkms2.ProofOfPossessionSignatureSOAPHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    if (null == this.sessionKey) {
        return true;
    }//  w ww  .  j a  v a  2s.  c  o  m
    if (null == this.prototypeKeyBindingId) {
        return true;
    }

    Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (false == outboundProperty) {
        return true;
    }
    LOG.debug("adding proof of possession signature");
    SOAPMessage soapMessage = context.getMessage();
    SOAPPart soapPart = soapMessage.getSOAPPart();

    NodeList registerRequestNodeList = soapPart.getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE,
            "RegisterRequest");
    Element registerRequestElement = (Element) registerRequestNodeList.item(0);
    Document xkmsDocument;
    try {
        xkmsDocument = copyDocument(registerRequestElement);
    } catch (ParserConfigurationException e) {
        LOG.error("error copying XKMS request: " + e.getMessage(), e);
        return false;
    }

    NodeList proofOfPossessionNodeList = xkmsDocument
            .getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "ProofOfPossession");
    Element proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    try {
        prepareDocument(xkmsDocument);
        addSignature(proofOfPossessionElement);
    } catch (Exception e) {
        LOG.error("error adding proof signature: " + e.getMessage(), e);
        return false;
    }
    Node signatureNode = soapPart.importNode(proofOfPossessionElement.getFirstChild(), true);

    proofOfPossessionNodeList = soapPart.getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE,
            "ProofOfPossession");
    proofOfPossessionElement = (Element) proofOfPossessionNodeList.item(0);
    proofOfPossessionElement.appendChild(signatureNode);
    return true;
}

From source file:com.hiperium.integration.access.control.SoapSessionHandler.java

@SuppressWarnings("unchecked")
@Override//from ww  w .java  2 s  .co m
public boolean handleMessage(SOAPMessageContext context) {
    LOGGER.debug("handleMessage - BEGIN");
    // Only message arriving from the client. Not processing responses.
    Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (!outbound) {
        Map<String, List<String>> map = (Map<String, List<String>>) context
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        List<String> sessionHeader = this.getHTTPHeader(map, CommonsUtil.SESSIONID);
        if (sessionHeader == null) {
            SOAPMessage msg = context.getMessage();
            this.generateFault(msg, Resources.getResourceBundle(EnumI18N.SECURITY, Locale.getDefault())
                    .getString("ilegalAccessResource"));
        }
        // Get the sessionId from the entire HTTP Message
        StringBuffer sessionIdBuffer = new StringBuffer();
        for (String session : sessionHeader) {
            sessionIdBuffer.append(session);
        }
        // Validate that the session ID is valid 
        if (StringUtils.isNotBlank(sessionIdBuffer.toString()) && !this.securityBusinessDelegate
                .getSessionManagerBO().findIfHomeLoggedIn(sessionIdBuffer.toString())) {
            SOAPMessage msg = context.getMessage();
            this.generateFault(msg, Resources.getResourceBundle(EnumI18N.SECURITY, Locale.getDefault())
                    .getString("ilegalAccessResource"));
        }
    }
    LOGGER.debug("handleMessage - END");
    return true; //continue other handler chain
}

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  w w  w  . j a v  a  2s. c  om*/

            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;
}

From source file:com.qubit.solution.fenixedu.bennu.webservices.services.server.BennuWebServiceHandler.java

@Override
public boolean handleMessage(SOAPMessageContext context) {
    Boolean isRequest = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    //for response message only, true for outbound messages, false for inbound
    if (!isRequest) {
        try {//ww w.ja v a  2 s. c o  m

            WebServiceServerConfiguration configuration = getWebServiceServerConfiguration(
                    ((com.sun.xml.ws.api.server.WSEndpoint) context.get("com.sun.xml.ws.api.server.WSEndpoint"))
                            .getImplementationClass().getName());

            SOAPMessage soapMsg = context.getMessage();
            SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope();
            SOAPHeader soapHeader = soapEnv.getHeader();

            if (!configuration.isActive()) {
                generateSOAPErrorMessage(soapMsg, "Sorry webservice is disabled at application level!");
            }

            if (configuration.isAuthenticatioNeeded()) {

                if (configuration.isUsingWSSecurity()) {
                    if (soapHeader == null) {
                        generateSOAPErrorMessage(soapMsg,
                                "No header in message, unabled to validate security credentials");
                    }

                    String username = null;
                    String password = null;
                    String nonce = null;
                    String created = null;

                    Iterator<SOAPElement> childElements = soapHeader.getChildElements(QNAME_WSSE_SECURITY);
                    if (childElements.hasNext()) {
                        SOAPElement securityElement = childElements.next();
                        Iterator<SOAPElement> usernameTokens = securityElement
                                .getChildElements(QNAME_WSSE_USERNAME_TOKEN);
                        if (usernameTokens.hasNext()) {
                            SOAPElement usernameToken = usernameTokens.next();
                            username = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_USERNAME)
                                    .next()).getValue();
                            password = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_PASSWORD)
                                    .next()).getValue();
                            nonce = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_NONCE).next())
                                    .getValue();
                            created = ((SOAPElement) usernameToken.getChildElements(QNAME_WSSE_CREATED).next())
                                    .getValue();
                        }
                    }
                    if (username == null || password == null || nonce == null || created == null) {
                        generateSOAPErrorMessage(soapMsg,
                                "Missing information, unabled to validate security credentials");
                    }

                    SecurityHeader securityHeader = new SecurityHeader(configuration, username, password, nonce,
                            created);
                    if (!securityHeader.isValid()) {
                        generateSOAPErrorMessage(soapMsg, "Invalid credentials");
                    } else {
                        context.put(BennuWebService.SECURITY_HEADER, securityHeader);
                        context.setScope(BennuWebService.SECURITY_HEADER, Scope.APPLICATION);
                    }
                } else {
                    com.sun.xml.ws.transport.Headers httpHeader = (Headers) context
                            .get(MessageContext.HTTP_REQUEST_HEADERS);
                    String username = null;
                    String password = null;
                    List<String> list = httpHeader.get("authorization");
                    if (list != null) {
                        for (String value : list) {
                            if (value.startsWith("Basic")) {
                                String[] split = value.split(" ");
                                try {
                                    String decoded = new String(Base64.decodeBase64(split[1]), "UTF-8");
                                    String[] split2 = decoded.split(":");
                                    if (split2.length == 2) {
                                        username = split2[0];
                                        password = split2[1];
                                    }
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }

                    if (username == null || password == null) {
                        generateSOAPErrorMessage(soapMsg,
                                "Missing information, unabled to validate security credentials");
                    }

                    if (!configuration.validate(username, password)) {
                        generateSOAPErrorMessage(soapMsg, "Invalid credentials");
                    }
                }
            }

        } catch (SOAPException e) {
            System.err.println(e);
        }
    }

    //continue other handler chain
    return true;
}

From source file:com.hiperium.integration.access.control.SoapSignatureHandler.java

@SuppressWarnings("unchecked")
@Override// w  w  w.  jav  a 2  s  . com
public boolean handleMessage(SOAPMessageContext context) {
    LOGGER.debug("handleMessage - BEGIN");
    // Only message arriving from the client. Not processing responses.
    Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (!outbound) {
        // Get the sessionId from the entire HTTP Message
        StringBuffer sessionIdBuffer = new StringBuffer();
        Map<String, List<String>> map = (Map<String, List<String>>) context
                .get(MessageContext.HTTP_REQUEST_HEADERS);
        for (String session : this.getHTTPHeader(map, CommonsUtil.SESSIONID)) {
            sessionIdBuffer.append(session);
        }
        // Try to get SOAP header values from the SOAP message
        try {
            SOAPMessage msg = context.getMessage();
            if (LOGGER.isDebugEnabled()) {
                System.out.println("REQUEST:");
                msg.writeTo(System.out);
                System.out.println();
            }
            Node node = msg.getSOAPHeader().getFirstChild();

            // Header values
            NodeList nodeList = node.getChildNodes(); // Name, TimeStamp, Signature.
            if (nodeList.getLength() < 3) {
                this.generateFault(msg, "Too few header nodes!");
            }

            // Extract the required attributes.
            Long homeId = Long.valueOf(nodeList.item(0).getFirstChild().getNodeValue());
            String signature = nodeList.item(1).getFirstChild().getNodeValue();
            String timestamp = nodeList.item(2).getFirstChild().getNodeValue();
            if (StringUtils.isBlank(timestamp) || StringUtils.isBlank(signature)) {
                this.generateFault(msg, "Missing header key/value pairs!");
            }

            // Validates that the user Token exists in the DB for valid registered external Application.
            String token = this.securityBusinessDelegate.getHomeGatewayBO().findTokenInSession(homeId,
                    sessionIdBuffer.toString());
            if (StringUtils.isBlank(token)) {
                this.generateFault(msg, homeId.toString().concat(" not registered!"));
            }

            // Generate comparison signature and compare against what's sent.
            byte[] secretBytes = Signature.getBytes(token);
            String localSignature = Signature.createSignature(homeId, timestamp, secretBytes);
            if (!this.verify(signature, localSignature)) {
                this.generateFault(msg, "HMAC signatures do not match.");
            }
        } catch (Exception e) {
            throw new RuntimeException("SOAPException thrown.", e);
        }
    }
    LOGGER.debug("handleMessage - END");
    return true; //continue other handler chain
}

From source file:org.apache.juddi.xlt.util.LoggingHandler.java

private String getOperationName(SOAPMessageContext context) {
    // service is optional :-(
    QName service = (QName) context.get(MessageContext.WSDL_SERVICE);
    if (service == null) {
        service = new QName("<unknown>");
    }/*from  w  w  w. j  a v a 2  s . c o m*/

    // operation is optional :-(
    QName operation = (QName) context.get(MessageContext.WSDL_OPERATION);
    if (operation == null) {
        // operation = new QName("<unknown>");

        try {
            operation = new QName(context.getMessage().getSOAPBody().getFirstChild().getLocalName());
        } catch (SOAPException ex) {
            throw new RuntimeException("", ex);
        }
    }

    return service.getLocalPart() + "." + operation.getLocalPart();
}

From source file:org.apache.juddi.xlt.util.LoggingHandler.java

private void logMessage(SOAPMessageContext context) {
    boolean isOutbound = isOutboundMessage(context);

    // optionally append the HTTP request/response headers
    String headersKey = isOutbound ? MessageContext.HTTP_REQUEST_HEADERS : MessageContext.HTTP_RESPONSE_HEADERS;
    StringBuilder httpHeaders = new StringBuilder();
    Map<Object, Object> headers = (Map<Object, Object>) context.get(headersKey);
    if (headers != null && headers.size() > 0) {
        for (Entry<Object, Object> entry : headers.entrySet()) {
            httpHeaders.append("- " + entry.getKey() + " = " + entry.getValue() + "\n");
        }//ww w  .  j a v a 2  s.co  m
    }

    // append the SOAP message
    String soapMessage = DomUtils.prettyPrintNode(context.getMessage().getSOAPPart());

    // append the message context properties
    StringBuilder messageContextProperties = new StringBuilder();
    TreeMap<String, Object> sortedContextProperties = new TreeMap<String, Object>(context);
    for (Entry<String, Object> entry : sortedContextProperties.entrySet()) {
        messageContextProperties.append("- " + entry.getKey() + " = " + entry.getValue() + "\n");
    }

    // finally log all
    String format = isOutbound ? OUTBOUND_MESSAGE_FORMAT : INBOUND_MESSAGE_FORMAT;
    LOG.debug(String.format(format, httpHeaders, soapMessage, messageContextProperties));
}