Search in sources :

Example 1 with SOAPHeaderElement

use of javax.xml.soap.SOAPHeaderElement in project nhin-d by DirectProject.

the class DirectSOAPHandler method handleMessage.

/**
     * This method handles the incoming and outgoing SOAP-Message. It's an
     * excellent point to manipulate the SOAP.
     * 
     * @param SOAPMessageContext
     *            The SOAPMessageContext object.
     * @return true for successful handling, false otherwise.
     */
@Override
public boolean handleMessage(SOAPMessageContext context) {
    LOGGER.info("Entering DirectSOAPHandler.handleMessage(SOAPMessageContext)");
    // Inquire incoming or outgoing message.
    boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    try {
        if (outbound) {
            LOGGER.info("Handling an outbound message");
            boolean isACK = !context.containsKey(ENDPOINT_ADDRESS);
            SafeThreadData threadData = SafeThreadData.GetThreadInstance(Thread.currentThread().getId());
            SOAPMessage msg = ((SOAPMessageContext) context).getMessage();
            dumpSOAPMessage(msg);
            SOAPPart sp = msg.getSOAPPart();
            // edit Envelope
            SOAPEnvelope env = sp.getEnvelope();
            SOAPHeader sh = env.addHeader();
            @SuppressWarnings("unused") SOAPBody sb = env.getBody();
            try {
                if (threadData.getAction() != null) {
                    QName qname = new QName("http://www.w3.org/2005/08/addressing", "Action");
                    SOAPHeaderElement saction = sh.addHeaderElement(qname);
                    boolean must = true;
                    saction.setMustUnderstand(must);
                    saction.setValue(threadData.getAction());
                }
                if (threadData.getRelatesTo() != null) {
                    QName qname = new QName("http://www.w3.org/2005/08/addressing", "RelatesTo");
                    SOAPHeaderElement relates = sh.addHeaderElement(qname);
                    relates.setValue(threadData.getRelatesTo());
                }
                if (threadData.getFrom() != null) {
                    QName qname = new QName("http://www.w3.org/2005/08/addressing", "From");
                    QName child = new QName("http://www.w3.org/2005/08/addressing", "Address");
                    SOAPHeaderElement efrom = sh.addHeaderElement(qname);
                    SOAPElement address = efrom.addChildElement(child);
                    address.setValue(threadData.getFrom());
                }
                if (threadData.getMessageId() != null) {
                    QName qname = new QName("http://www.w3.org/2005/08/addressing", "MessageID");
                    SOAPHeaderElement message = sh.addHeaderElement(qname);
                    message.setValue(threadData.getMessageId());
                }
                if (threadData.getTo() != null) {
                    QName qname = new QName("http://www.w3.org/2005/08/addressing", "To");
                    SOAPHeaderElement sto = sh.addHeaderElement(qname);
                    sto.setValue(threadData.getTo());
                }
                SOAPHeaderElement directHeader = sh.addHeaderElement(new QName("urn:direct:addressing", "addressBlock"));
                directHeader.setPrefix("direct");
                directHeader.setRole("urn:direct:addressing:destination");
                directHeader.setRelay(true);
                if (StringUtils.isNotBlank(threadData.getDirectFrom())) {
                    SOAPElement directFromElement = directHeader.addChildElement(new QName("from"));
                    directFromElement.setPrefix("direct");
                    URI uri = new URI(threadData.getDirectFrom());
                    directFromElement.setValue((new URI("mailto", uri.getSchemeSpecificPart(), null)).toString());
                }
                if (StringUtils.isNotBlank(threadData.getDirectTo())) {
                    /**
                         * consider multiple recipients
                         */
                    String[] directTos = threadData.getDirectTo().split(";");
                    for (String directToAddr : directTos) {
                        SOAPElement directToElement = directHeader.addChildElement(new QName("to"));
                        directToElement.setPrefix("direct");
                        URI uri = new URI(directToAddr);
                        directToElement.setValue((new URI("mailto", uri.getSchemeSpecificPart(), null)).toString());
                    }
                }
                SOAPElement directMetadataLevelElement = directHeader.addChildElement(new QName("metadata-level"));
                directMetadataLevelElement.setPrefix("direct");
                directMetadataLevelElement.setValue(MetadataLevelEnum.MINIMAL.getLevel());
            } catch (Throwable tb) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Failed to write SOAP Header", tb);
                } else {
                    LOGGER.error("Failed to write SOAP Header: " + tb.getMessage());
                }
            }
            if (isACK) {
                SafeThreadData.clean(Thread.currentThread().getId());
            }
        } else {
            LOGGER.info("Handling an inbound message");
            SOAPMessage msg = ((SOAPMessageContext) context).getMessage();
            boolean isResponse = isResponse(msg);
            if (!isResponse) {
                // Issue 249 - before handling the inbound case, we should clear 
                // out the old thread data if we don't this the To: (SMTP recipients) will 
                // append from the previous thread data 
                SafeThreadData.clean(Thread.currentThread().getId());
            }
            SafeThreadData threadData = SafeThreadData.GetThreadInstance(Thread.currentThread().getId());
            ServletRequest sr = (ServletRequest) context.get(MessageContext.SERVLET_REQUEST);
            if (sr != null) {
                threadData.setRemoteHost(sr.getRemoteHost());
                threadData.setThisHost(sr.getServerName());
                threadData.setPid(getPID());
            }
            SOAPPart sp = msg.getSOAPPart();
            // edit Envelope
            SOAPEnvelope env = sp.getEnvelope();
            SOAPHeader sh = env.getHeader();
            @SuppressWarnings("unchecked") Iterator<Node> it = sh.extractAllHeaderElements();
            while (it.hasNext()) {
                try {
                    Node header = it.next();
                    if (StringUtils.contains(header.toString(), "MessageID")) {
                        threadData.setMessageId(header.getTextContent());
                    } else if (StringUtils.contains(header.toString(), "Action")) {
                        threadData.setAction(header.getTextContent());
                    } else if (StringUtils.contains(header.toString(), "RelatesTo")) {
                        threadData.setRelatesTo(header.getTextContent());
                    } else if (StringUtils.contains(header.toString(), "ReplyTo")) {
                        NodeList reps = header.getChildNodes();
                        for (int i = 0; i < reps.getLength(); i++) {
                            Node address = reps.item(i);
                            if (StringUtils.contains(address.getNodeName(), "Address")) {
                                threadData.setEndpoint(address.getTextContent());
                            }
                        }
                    } else if (StringUtils.contains(header.toString(), "From")) {
                        NodeList reps = header.getChildNodes();
                        for (int i = 0; i < reps.getLength(); i++) {
                            Node address = reps.item(i);
                            if (StringUtils.contains(address.getNodeName(), "Address")) {
                                threadData.setFrom(address.getTextContent());
                            }
                        }
                    } else if (// must be after ReplyTo
                    StringUtils.contains(header.toString(), "To")) {
                        threadData.setTo(header.getTextContent());
                    } else if (StringUtils.contains(header.toString(), "addressBlock")) {
                        NodeList childNodes = header.getChildNodes();
                        for (int i = 0; i < childNodes.getLength(); i++) {
                            Node node = childNodes.item(i);
                            if (StringUtils.contains(node.getNodeName(), "from")) {
                                threadData.setDirectFrom(node.getTextContent());
                            } else if (StringUtils.contains(node.getNodeName(), "to")) {
                                // XDR-MULTIPLE-RECIPIENT-ISSUE - this is the part where old thread data 
                                // gets into the To: and will cause unwanted recipients 
                                // (see above for the clear)
                                String recipient = node.getTextContent();
                                if (threadData.getDirectTo() == null) {
                                    threadData.setDirectTo(recipient);
                                } else {
                                    /**
                                         * if multiple recipients, save addresses in one parameters separate by (;)
                                         */
                                    threadData.setDirectTo(threadData.getDirectTo() + ";" + recipient);
                                }
                            } else if (StringUtils.contains(node.getNodeName(), "metadata-level")) {
                                threadData.setDirectMetadataLevel(node.getTextContent());
                            }
                        }
                    }
                } catch (Throwable tb) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Failed to read input parameter.", tb);
                    } else {
                        LOGGER.error("Failed to read input parameter.");
                    }
                }
            }
            threadData.save();
        }
    } catch (Exception e) {
        LOGGER.warn("Error handling SOAP message.", e);
        return false;
    }
    return true;
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) ServletRequest(javax.servlet.ServletRequest) QName(javax.xml.namespace.QName) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) SOAPMessage(javax.xml.soap.SOAPMessage) URI(java.net.URI) SOAPException(javax.xml.soap.SOAPException) SOAPBody(javax.xml.soap.SOAPBody) SOAPMessageContext(javax.xml.ws.handler.soap.SOAPMessageContext) SOAPPart(javax.xml.soap.SOAPPart) SOAPElement(javax.xml.soap.SOAPElement) SOAPHeader(javax.xml.soap.SOAPHeader)

Example 2 with SOAPHeaderElement

use of javax.xml.soap.SOAPHeaderElement in project cxf by apache.

the class SecurityHeaderCacheInterceptor method handleMessage.

public void handleMessage(SoapMessage mc) throws Fault {
    SOAPMessage saaj = mc.getContent(SOAPMessage.class);
    if (cachedSecurityHeader == null) {
        try {
            Iterator<?> cachedHeadersIterator = SAAJUtils.getHeader(saaj).getChildElements(SEC_HEADER);
            if (cachedHeadersIterator.hasNext()) {
                cachedSecurityHeader = (SOAPHeaderElement) cachedHeadersIterator.next();
            }
        } catch (SOAPException e) {
        // Ignore
        }
    } else {
        try {
            saaj.getSOAPHeader().removeContents();
            SOAPHeaderElement secHeaderElement = SAAJUtils.getHeader(saaj).addHeaderElement(SEC_HEADER);
            Iterator<?> cachedHeadersIterator = cachedSecurityHeader.getChildElements();
            while (cachedHeadersIterator.hasNext()) {
                secHeaderElement.addChildElement((SOAPElement) cachedHeadersIterator.next());
            }
        } catch (SOAPException e) {
            e.printStackTrace();
        }
    }
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) SOAPException(javax.xml.soap.SOAPException) SOAPMessage(javax.xml.soap.SOAPMessage)

Example 3 with SOAPHeaderElement

use of javax.xml.soap.SOAPHeaderElement in project ddf by codice.

the class IdpEndpoint method determineAuthMethod.

private AuthObj determineAuthMethod(String bodyStr, AuthnRequest authnRequest) {
    XMLStreamReader xmlStreamReader = null;
    try {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(bodyStr));
    } catch (XMLStreamException e) {
        LOGGER.debug("Unable to parse SOAP message from client.", e);
    }
    SoapMessage soapMessage = new SoapMessage(Soap11.getInstance());
    SAAJInInterceptor.SAAJPreInInterceptor preInInterceptor = new SAAJInInterceptor.SAAJPreInInterceptor();
    soapMessage.setContent(XMLStreamReader.class, xmlStreamReader);
    preInInterceptor.handleMessage(soapMessage);
    SAAJInInterceptor inInterceptor = new SAAJInInterceptor();
    inInterceptor.handleMessage(soapMessage);
    SOAPPart soapMessageContent = (SOAPPart) soapMessage.getContent(Node.class);
    AuthObj authObj = new AuthObj();
    try {
        Iterator soapHeaderElements = soapMessageContent.getEnvelope().getHeader().examineAllHeaderElements();
        while (soapHeaderElements.hasNext()) {
            SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) soapHeaderElements.next();
            if (soapHeaderElement.getLocalName().equals("Security")) {
                Iterator childElements = soapHeaderElement.getChildElements();
                while (childElements.hasNext()) {
                    Object nextElement = childElements.next();
                    if (nextElement instanceof SOAPElement) {
                        SOAPElement element = (SOAPElement) nextElement;
                        if (element.getLocalName().equals("UsernameToken")) {
                            Iterator usernameTokenElements = element.getChildElements();
                            Object next;
                            while (usernameTokenElements.hasNext()) {
                                if ((next = usernameTokenElements.next()) instanceof Element) {
                                    Element nextEl = (Element) next;
                                    if (nextEl.getLocalName().equals("Username")) {
                                        authObj.username = nextEl.getTextContent();
                                    } else if (nextEl.getLocalName().equals("Password")) {
                                        authObj.password = nextEl.getTextContent();
                                    }
                                }
                            }
                            if (authObj.username != null && authObj.password != null) {
                                authObj.method = USER_PASS;
                                break;
                            }
                        } else if (element.getLocalName().equals("Assertion") && element.getNamespaceURI().equals("urn:oasis:names:tc:SAML:2.0:assertion")) {
                            authObj.assertion = new SecurityToken(element.getAttribute("ID"), element, null, null);
                            authObj.method = SAML;
                            break;
                        }
                    }
                }
            }
        }
    } catch (SOAPException e) {
        LOGGER.debug("Unable to parse SOAP message.", e);
    }
    RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
    boolean requestingPki = false;
    boolean requestingUp = false;
    if (requestedAuthnContext != null) {
        List<AuthnContextClassRef> authnContextClassRefs = requestedAuthnContext.getAuthnContextClassRefs();
        for (AuthnContextClassRef authnContextClassRef : authnContextClassRefs) {
            String authnContextClassRefStr = authnContextClassRef.getAuthnContextClassRef();
            if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_X509.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SMARTCARD_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SOFTWARE_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SPKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_TLS_CLIENT.equals(authnContextClassRefStr)) {
                requestingPki = true;
            } else if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD_PROTECTED_TRANSPORT.equals(authnContextClassRefStr)) {
                requestingUp = true;
            }
        }
    } else {
        //The requested auth context isn't required so we don't know what they want... just set both to true
        requestingPki = true;
        requestingUp = true;
    }
    if (requestingUp && authObj.method != null && authObj.method.equals(USER_PASS)) {
        LOGGER.trace("Found UsernameToken and correct AuthnContextClassRef");
        return authObj;
    } else if (requestingPki && authObj.method == null) {
        LOGGER.trace("Found no token, but client requested PKI AuthnContextClassRef");
        authObj.method = PKI;
        return authObj;
    } else if (authObj.method == null) {
        LOGGER.debug("No authentication tokens found for the current request and the client did not request PKI authentication");
    }
    return authObj;
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) XMLStreamReader(javax.xml.stream.XMLStreamReader) Node(org.w3c.dom.Node) SOAPElement(javax.xml.soap.SOAPElement) SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) Element(org.w3c.dom.Element) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) SAAJInInterceptor(org.apache.cxf.binding.soap.saaj.SAAJInInterceptor) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) XMLStreamException(javax.xml.stream.XMLStreamException) SOAPException(javax.xml.soap.SOAPException) StringReader(java.io.StringReader) SOAPPart(javax.xml.soap.SOAPPart) Iterator(java.util.Iterator) SOAPElement(javax.xml.soap.SOAPElement) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SignableXMLObject(org.opensaml.xmlsec.signature.SignableXMLObject) XMLObject(org.opensaml.core.xml.XMLObject)

Example 4 with SOAPHeaderElement

use of javax.xml.soap.SOAPHeaderElement in project ddf by codice.

the class SoapRequestDecoder method decodeRelayState.

public String decodeRelayState(String samlRequest) {
    String relayState = null;
    try {
        SOAPPart soapMessage = SamlProtocol.parseSoapMessage(samlRequest);
        SOAPEnvelope envelope = soapMessage.getEnvelope();
        SOAPHeader header = envelope.getHeader();
        Iterator iterator = header.examineAllHeaderElements();
        while (iterator.hasNext()) {
            SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) iterator.next();
            if ("RelayState".equals(soapHeaderElement.getLocalName())) {
                relayState = soapHeaderElement.getValue();
                break;
            }
        }
    } catch (XMLStreamException e) {
        throw new IllegalArgumentException("Unable to convert parse SOAP request.");
    } catch (SOAPException e) {
        throw new IllegalArgumentException("Unable to get SOAP envelope.");
    }
    return relayState;
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) XMLStreamException(javax.xml.stream.XMLStreamException) SOAPException(javax.xml.soap.SOAPException) SOAPPart(javax.xml.soap.SOAPPart) Iterator(java.util.Iterator) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) SOAPHeader(javax.xml.soap.SOAPHeader)

Example 5 with SOAPHeaderElement

use of javax.xml.soap.SOAPHeaderElement in project nhin-d by DirectProject.

the class RepositorySOAPHandler method handleMessage.

/**
     * This method handles the incoming and outgoing SOAP-Message. It's an
     * excellent point to manipulate the SOAP.
     * 
     * @param SOAPMessageContext
     *            The SOAPMessageContext object.
     * 
     * @return true if successful handling, false otherwise.
     */
@Override
public boolean handleMessage(SOAPMessageContext context) {
    //Inquire incoming or outgoing message.
    boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    try {
        if (outbound) {
            getHeaderData();
            SOAPMessage msg = ((SOAPMessageContext) context).getMessage();
            // dumpSOAPMessage(msg);
            SOAPPart sp = msg.getSOAPPart();
            // edit Envelope
            SOAPEnvelope env = sp.getEnvelope();
            SOAPHeader sh = env.addHeader();
            @SuppressWarnings("unused") SOAPBody sb = env.getBody();
            if (action != null) {
                QName qname = new QName("http://www.w3.org/2005/08/addressing", "Action");
                SOAPHeaderElement saction = sh.addHeaderElement(qname);
                boolean must = true;
                saction.setMustUnderstand(must);
                saction.setValue(action);
            }
            if (relatesTo != null) {
                QName qname = new QName("http://www.w3.org/2005/08/addressing", "RelatesTo");
                SOAPHeaderElement relates = sh.addHeaderElement(qname);
                relates.setValue(relatesTo);
            }
            if (from != null) {
                QName qname = new QName("http://www.w3.org/2005/08/addressing", "From");
                QName child = new QName("http://www.w3.org/2005/08/addressing", "Address");
                SOAPHeaderElement efrom = sh.addHeaderElement(qname);
                SOAPElement address = efrom.addChildElement(child);
                address.setValue(from);
            }
            if (messageId != null) {
                QName qname = new QName("http://www.w3.org/2005/08/addressing", "MessageID");
                SOAPHeaderElement message = sh.addHeaderElement(qname);
                message.setValue(messageId);
            }
            if (to != null) {
                QName qname = new QName("http://www.w3.org/2005/08/addressing", "To");
                SOAPHeaderElement sto = sh.addHeaderElement(qname);
                sto.setValue(to);
            }
        } else {
        //should not be any inbound
        }
    } catch (Exception e) {
        LOGGER.error("Error handling SOAP message", e);
        return false;
    }
    return true;
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) QName(javax.xml.namespace.QName) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) SOAPMessage(javax.xml.soap.SOAPMessage) SOAPException(javax.xml.soap.SOAPException) IOException(java.io.IOException) SOAPBody(javax.xml.soap.SOAPBody) SOAPMessageContext(javax.xml.ws.handler.soap.SOAPMessageContext) SOAPPart(javax.xml.soap.SOAPPart) SOAPElement(javax.xml.soap.SOAPElement) SOAPHeader(javax.xml.soap.SOAPHeader)

Aggregations

SOAPHeaderElement (javax.xml.soap.SOAPHeaderElement)32 SOAPMessage (javax.xml.soap.SOAPMessage)21 SOAPHeader (javax.xml.soap.SOAPHeader)19 SOAPException (javax.xml.soap.SOAPException)16 SOAPEnvelope (javax.xml.soap.SOAPEnvelope)13 Name (javax.xml.soap.Name)10 SOAPElement (javax.xml.soap.SOAPElement)10 SOAPBody (javax.xml.soap.SOAPBody)8 SOAPBodyElement (javax.xml.soap.SOAPBodyElement)7 WebServiceException (javax.xml.ws.WebServiceException)7 SOAPFactory (javax.xml.soap.SOAPFactory)6 SOAPPart (javax.xml.soap.SOAPPart)6 ProtocolException (javax.xml.ws.ProtocolException)6 CoordinationContextType (org.oasis_open.docs.ws_tx.wscoor._2006._06.CoordinationContextType)6 Iterator (java.util.Iterator)5 JAXBException (javax.xml.bind.JAXBException)5 JAXBContext (javax.xml.bind.JAXBContext)4 QName (javax.xml.namespace.QName)4 SOAPMessageContext (javax.xml.ws.handler.soap.SOAPMessageContext)4 IOException (java.io.IOException)3