Search in sources :

Example 1 with SOAPEnvelope

use of javax.xml.soap.SOAPEnvelope in project tomcat by apache.

the class SignCode method populateEnvelope.

private static SOAPBody populateEnvelope(SOAPMessage message, String namespace) throws SOAPException {
    SOAPPart soapPart = message.getSOAPPart();
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
    envelope.addNamespaceDeclaration(namespace, "http://api.ws.symantec.com/webtrust/codesigningservice");
    return envelope.getBody();
}
Also used : SOAPPart(javax.xml.soap.SOAPPart) SOAPEnvelope(javax.xml.soap.SOAPEnvelope)

Example 2 with SOAPEnvelope

use of javax.xml.soap.SOAPEnvelope in project OpenAM by OpenRock.

the class SOAPCommunicator method createSOAPFault.

/**
     * Forms a SOAP Fault and puts it in the SOAP Message Body.
     *
     * @param faultCode   Fault code.
     * @param faultString Fault string.
     * @param detail      Fault details.
     * @return SOAP Fault in the SOAP Message Body or null if unable to generate the message.
     */
public SOAPMessage createSOAPFault(final String faultCode, final String faultString, final String detail) {
    try {
        SOAPMessage message = messageFactory.createMessage();
        SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
        SOAPFault fault = envelope.getBody().addFault();
        fault.setFaultCode(envelope.createName(faultCode, null, SOAPConstants.URI_NS_SOAP_ENVELOPE));
        fault.setFaultString(SAML2Utils.bundle.getString(faultString));
        if (StringUtils.isNotEmpty(detail)) {
            Detail faultDetail = fault.addDetail();
            SOAPElement faultDetailEntry = (SOAPElement) faultDetail.addDetailEntry(envelope.createName("Problem"));
            faultDetailEntry.addAttribute(envelope.createName("details"), SAML2Utils.bundle.getString(detail));
        }
        return message;
    } catch (SOAPException e) {
        debug.error("createSOAPFault:", e);
        return null;
    }
}
Also used : SOAPException(javax.xml.soap.SOAPException) SOAPElement(javax.xml.soap.SOAPElement) SOAPFault(javax.xml.soap.SOAPFault) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) SOAPMessage(javax.xml.soap.SOAPMessage) Detail(javax.xml.soap.Detail)

Example 3 with SOAPEnvelope

use of javax.xml.soap.SOAPEnvelope in project OpenAM by OpenRock.

the class FSSOAPReceiver method onMessage.

/**
     * Process the request.
     * @param request http request object
     * @param response http response object
     * @param message received soap message
     */
public void onMessage(HttpServletRequest request, HttpServletResponse response, SOAPMessage message) {
    FSUtils.debug.message("FSSOAPReceiver.onMessage: Called");
    try {
        Element elt = soapService.parseSOAPMessage(message);
        if (elt == null) {
            FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing saml:Request. Invalid SOAPMessage");
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
            returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
            return;
        }
        String eltTagName = (elt.getTagName().trim());
        String ns = elt.getNamespaceURI().trim();
        String nodeName = elt.getLocalName().trim();
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSSOAPReceiver.onMessage: " + "tagName: " + eltTagName + " namespaceUri: " + ns + " localName: " + nodeName);
        }
        //check for saml:Request
        if (nodeName.equalsIgnoreCase("Request") && ns.equalsIgnoreCase(IFSConstants.PROTOCOL_NAMESPACE_URI)) {
            SOAPMessage retMessage = null;
            try {
                FSSAMLRequest samlRequest = new FSSAMLRequest(elt);
                IDFFMetaManager metaManager = FSUtils.getIDFFMetaManager();
                if (metaManager == null) {
                    FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "could not create meta instance");
                    response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                    return;
                }
                String metaAlias = FSServiceUtils.getMetaAlias(request);
                String realm = IDFFMetaUtils.getRealmByMetaAlias(metaAlias);
                String hostedEntityId = metaManager.getEntityIDByMetaAlias(metaAlias);
                IDPDescriptorType hostedDesc = metaManager.getIDPDescriptor(realm, hostedEntityId);
                BaseConfigType hostedConfig = metaManager.getIDPDescriptorConfig(realm, hostedEntityId);
                FSServiceManager sm = FSServiceManager.getInstance();
                FSSSOBrowserArtifactProfileHandler handler = (FSSSOBrowserArtifactProfileHandler) sm.getBrowserArtifactSSOAndFedHandler(request, response, samlRequest);
                handler.setSOAPMessage(message);
                handler.setSAMLRequestElement(elt);
                handler.setHostedEntityId(hostedEntityId);
                handler.setHostedDescriptor(hostedDesc);
                handler.setHostedDescriptorConfig(hostedConfig);
                handler.setMetaAlias(metaAlias);
                handler.setRealm(realm);
                FSResponse samlResponse = handler.processSAMLRequest(samlRequest);
                if (samlResponse != null) {
                    if (FSUtils.debug.messageEnabled()) {
                        FSUtils.debug.message("FSSOAPReceiver.onMessage: " + "SAML Response created: " + samlResponse.toXMLString());
                    }
                } else {
                    FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "SAML Response is null");
                    response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                    return;
                }
                // introduce id attribute for Assertion bind in 
                // SOAPEnvelope and sign
                retMessage = soapService.bind(((FSResponse) samlResponse).toXMLString(true, true));
                if (FSServiceUtils.isSigningOn()) {
                    List assList = samlResponse.getAssertion();
                    Iterator iter = assList.iterator();
                    while (iter.hasNext()) {
                        FSAssertion assertion = (FSAssertion) iter.next();
                        String id = assertion.getID();
                        Document doc = (Document) FSServiceUtils.createSOAPDOM(retMessage);
                        String certAlias = IDFFMetaUtils.getFirstAttributeValueFromConfig(hostedConfig, IFSConstants.SIGNING_CERT_ALIAS);
                        if (certAlias == null) {
                            if (FSUtils.debug.messageEnabled()) {
                                FSUtils.debug.message("SOAPReceiver.onMessage: couldn't " + "obtain this site's cert alias.");
                            }
                            throw new SAMLResponderException(FSUtils.bundle.getString("cannotFindCertAlias"));
                        }
                        XMLSignatureManager manager = XMLSignatureManager.getInstance();
                        int minorVersion = assertion.getMinorVersion();
                        if (minorVersion == IFSConstants.FF_11_ASSERTION_MINOR_VERSION) {
                            manager.signXML(doc, certAlias, SystemConfigurationUtil.getProperty(SAMLConstants.XMLSIG_ALGORITHM), IFSConstants.ID, id, false);
                        } else if (minorVersion == IFSConstants.FF_12_POST_ASSERTION_MINOR_VERSION || minorVersion == IFSConstants.FF_12_ART_ASSERTION_MINOR_VERSION) {
                            manager.signXML(doc, certAlias, SystemConfigurationUtil.getProperty(SAMLConstants.XMLSIG_ALGORITHM), IFSConstants.ASSERTION_ID, assertion.getAssertionID(), false);
                        } else {
                            FSUtils.debug.error("invalid minor version.");
                        }
                        retMessage = FSServiceUtils.convertDOMToSOAP(doc);
                    }
                }
                if (retMessage == null) {
                    FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing saml:Request");
                    response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                    return;
                }
            } catch (SAMLException se) {
                FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing saml:Request:", se);
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                return;
            } catch (IDFFMetaException me) {
                FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing saml:Request:", me);
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                return;
            }
            returnSOAPMessage(retMessage, response);
            return;
        }
        if (nodeName.equalsIgnoreCase("AuthnRequest") && (ns.equalsIgnoreCase(IFSConstants.libertyMessageNamespaceURI) || ns.equalsIgnoreCase(IFSConstants.FF_12_XML_NS))) {
            SOAPMessage retMessage = null;
            try {
                FSAuthnRequest authnRequest = new FSAuthnRequest(elt);
                handleLECPRequest(request, response, authnRequest);
                retMessage = null;
            } catch (FSException e) {
                FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing lecp AuthnRequest:", e);
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                return;
            }
            returnSOAPMessage(retMessage, response);
            return;
        } else if (nodeName.equalsIgnoreCase("RegisterNameIdentifierRequest") && (ns.equalsIgnoreCase(IFSConstants.libertyMessageNamespaceURI) || ns.equalsIgnoreCase(IFSConstants.FF_12_XML_NS))) {
            SOAPMessage retMessage = null;
            boolean isError = false;
            String providerAlias = null;
            ProviderDescriptorType hostedProviderDesc = null;
            BaseConfigType hostedConfig = null;
            String realm = null;
            String hostedEntityId = null;
            String hostedRole = null;
            try {
                if (FSUtils.debug.messageEnabled()) {
                    FSUtils.debug.message("FSSOAPReceiver.onMessage: " + "Handling NameRegistrationRequest");
                }
                IDFFMetaManager metaManager = FSUtils.getIDFFMetaManager();
                if (metaManager == null) {
                    FSUtils.debug.message("Unable to get meta manager");
                    isError = true;
                } else {
                    providerAlias = FSServiceUtils.getMetaAlias(request);
                    if (providerAlias == null || providerAlias.length() < 1) {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("Unable to retrieve alias" + "Hosted Provider. Cannot process request");
                        }
                        isError = true;
                    }
                    realm = IDFFMetaUtils.getRealmByMetaAlias(providerAlias);
                    try {
                        hostedRole = metaManager.getProviderRoleByMetaAlias(providerAlias);
                        hostedEntityId = metaManager.getEntityIDByMetaAlias(providerAlias);
                        if (hostedRole != null && hostedRole.equals(IFSConstants.IDP)) {
                            hostedProviderDesc = metaManager.getIDPDescriptor(realm, hostedEntityId);
                            hostedConfig = metaManager.getIDPDescriptorConfig(realm, hostedEntityId);
                        } else if (hostedRole != null && hostedRole.equals(IFSConstants.SP)) {
                            hostedProviderDesc = metaManager.getSPDescriptor(realm, hostedEntityId);
                            hostedConfig = metaManager.getSPDescriptorConfig(realm, hostedEntityId);
                        }
                        if (hostedProviderDesc == null) {
                            throw new IDFFMetaException((String) null);
                        }
                    } catch (IDFFMetaException eam) {
                        FSUtils.debug.error("Unable to find Hosted Provider. " + "Cannot process request");
                        isError = true;
                    }
                }
                if (isError || hostedProviderDesc == null) {
                    returnSOAPMessage(retMessage, response);
                    return;
                } else {
                    FSNameRegistrationResponse regisResponse = handleRegistrationRequest(elt, message, hostedProviderDesc, hostedConfig, hostedRole, realm, hostedEntityId, providerAlias, request, response);
                    if (regisResponse == null) {
                        FSUtils.debug.error("Error in creating NameRegistration Response");
                        response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                        retMessage = soapService.formSOAPError("Server", "cannotProcessRequest", null);
                    } else {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("FSSOAPReceiver.onMessage: " + "Completed creating response");
                        }
                        retMessage = soapService.bind(regisResponse.toXMLString(true, true));
                        FSUtils.debug.message("Completed bind message");
                        if (retMessage == null) {
                            FSUtils.debug.error("Error in processing NameRegistration " + "Response");
                            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                            retMessage = soapService.formSOAPError("Server", "cannotProcessRequest", null);
                        } else {
                            if (FSServiceUtils.isSigningOn()) {
                                try {
                                    int minorVersion = regisResponse.getMinorVersion();
                                    if (minorVersion == IFSConstants.FF_11_PROTOCOL_MINOR_VERSION) {
                                        retMessage = signResponse(retMessage, IFSConstants.ID, regisResponse.getID(), hostedConfig);
                                    } else if (minorVersion == IFSConstants.FF_12_PROTOCOL_MINOR_VERSION) {
                                        retMessage = signResponse(retMessage, IFSConstants.RESPONSE_ID, regisResponse.getResponseID(), hostedConfig);
                                    } else {
                                        if (FSUtils.debug.messageEnabled()) {
                                            FSUtils.debug.message("invalid minor version.");
                                        }
                                    }
                                } catch (SAMLException e) {
                                    FSUtils.debug.error("FSNameRegistrationHandler:" + "sign soap Response failed", e);
                                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                                    return;
                                } catch (FSMsgException e) {
                                    FSUtils.debug.error("FSNameRegistrationHandler::" + "signRegistrationResponse failed", e);
                                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                                    return;
                                }
                            }
                        }
                    }
                }
                if (FSUtils.debug.messageEnabled()) {
                    ByteArrayOutputStream bop = null;
                    String xmlString = null;
                    bop = new ByteArrayOutputStream();
                    retMessage.writeTo(bop);
                    xmlString = bop.toString(IFSConstants.DEFAULT_ENCODING);
                    if (FSUtils.debug.messageEnabled()) {
                        FSUtils.debug.message("return SOAP message:" + xmlString);
                    }
                }
                returnSOAPMessage(retMessage, response);
                return;
            } catch (Exception se) {
                FSUtils.debug.error("Error in processing Name Registration request" + se.getMessage());
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                retMessage = soapService.formSOAPError("Server", "cannotProcessRequest", null);
                returnSOAPMessage(retMessage, response);
            }
        } else if (nodeName.equalsIgnoreCase("NameIdentifierMappingRequest") && (ns.equalsIgnoreCase(IFSConstants.libertyMessageNamespaceURI) || ns.equalsIgnoreCase(IFSConstants.FF_12_XML_NS))) {
            FSUtils.debug.message("FSSOAPReceiver:handling Name Identifier Mapping Request");
            IDFFMetaManager metaManager = FSUtils.getIDFFMetaManager();
            String metaAlias = FSServiceUtils.getMetaAlias(request);
            String realm = IDFFMetaUtils.getRealmByMetaAlias(metaAlias);
            String hostedEntityId = metaManager.getEntityIDByMetaAlias(metaAlias);
            ProviderDescriptorType hostedDesc = metaManager.getIDPDescriptor(realm, hostedEntityId);
            BaseConfigType hostedConfig = metaManager.getIDPDescriptorConfig(realm, hostedEntityId);
            FSNameIdentifierMappingRequest mappingRequest = new FSNameIdentifierMappingRequest(elt);
            if (FSServiceUtils.isSigningOn()) {
                String remoteEntityId = mappingRequest.getProviderID();
                ProviderDescriptorType remoteDesc = getRemoteProviderDescriptor(// it has to be idp
                IFSConstants.IDP, remoteEntityId, realm);
                if (remoteDesc == null) {
                    return;
                }
                if (verifyRequestSignature(elt, message, KeyUtil.getVerificationCert(remoteDesc, remoteEntityId, true))) {
                    if (FSUtils.debug.messageEnabled()) {
                        FSUtils.debug.message("FSSOAPReceiver: Success in verifying " + "Name Identifier Mapping Request");
                    }
                } else {
                    FSUtils.debug.error("Failed verifying Name Identifier Mapping Request");
                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                    return;
                }
            }
            String targetNamespace = mappingRequest.getTargetNamespace();
            String inResponseTo = mappingRequest.getRequestID();
            Status status = new Status(new StatusCode("samlp:Success"));
            FSNameMappingHandler idpHandler = new FSNameMappingHandler(hostedEntityId, hostedDesc, hostedConfig, metaAlias);
            NameIdentifier nameIdentifier = idpHandler.getNameIdentifier(mappingRequest, targetNamespace, false);
            String enableEncryption = IDFFMetaUtils.getFirstAttributeValueFromConfig(hostedConfig, IFSConstants.ENABLE_NAMEID_ENCRYPTION);
            if (enableEncryption != null && enableEncryption.equalsIgnoreCase("true")) {
                nameIdentifier = EncryptedNameIdentifier.getEncryptedNameIdentifier(nameIdentifier, realm, targetNamespace);
            }
            FSNameIdentifierMappingResponse mappingResponse = new FSNameIdentifierMappingResponse(hostedEntityId, inResponseTo, status, nameIdentifier);
            if (FSServiceUtils.isSigningOn()) {
                String certAlias = IDFFMetaUtils.getFirstAttributeValueFromConfig(hostedConfig, IFSConstants.SIGNING_CERT_ALIAS);
                mappingResponse.signXML(certAlias);
            }
            SOAPMessage retMessage = soapService.bind(mappingResponse.toXMLString(true, true));
            returnSOAPMessage(retMessage, response);
            return;
        } else if (nodeName.equalsIgnoreCase("FederationTerminationNotification") && (ns.equalsIgnoreCase(IFSConstants.libertyMessageNamespaceURI) || ns.equalsIgnoreCase(IFSConstants.FF_12_XML_NS))) {
            try {
                FSUtils.debug.message("calling FSSOAPReceiver::handleTerminationRequest");
                boolean bHandleStatus = handleTerminationRequest(elt, message, request, response);
                if (bHandleStatus) {
                    FSUtils.debug.message("Completed processing terminationRequest");
                    returnTerminationStatus(response);
                    return;
                } else {
                    FSUtils.debug.message("Failed processing terminationRequest");
                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                    return;
                }
            } catch (Exception se) {
                FSUtils.debug.error("Error in processing Federation Termination Request", se);
                String[] data = { IFSConstants.TERMINATION_REQUEST_PROCESSING_FAILED };
                LogUtil.error(Level.INFO, LogUtil.TERMINATION_REQUEST_PROCESSING_FAILED, data);
                returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                return;
            }
        } else if (nodeName.equalsIgnoreCase("LogoutRequest") && (ns.equalsIgnoreCase(IFSConstants.libertyMessageNamespaceURI) || ns.equalsIgnoreCase(IFSConstants.FF_12_XML_NS))) {
            try {
                FSUtils.debug.message("calling FSSOAPReceiver::handleLogoutRequest");
                ProviderDescriptorType hostedProviderDesc = null;
                BaseConfigType hostedConfig = null;
                String providerAlias = null;
                String realm = null;
                String hostedEntityId = null;
                String hostedRole = null;
                try {
                    providerAlias = FSServiceUtils.getMetaAlias(request);
                    realm = IDFFMetaUtils.getRealmByMetaAlias(providerAlias);
                    IDFFMetaManager metaManager = FSUtils.getIDFFMetaManager();
                    hostedRole = metaManager.getProviderRoleByMetaAlias(providerAlias);
                    hostedEntityId = metaManager.getEntityIDByMetaAlias(providerAlias);
                    if (hostedRole != null) {
                        if (hostedRole.equalsIgnoreCase(IFSConstants.IDP)) {
                            hostedProviderDesc = metaManager.getIDPDescriptor(realm, hostedEntityId);
                            hostedConfig = metaManager.getIDPDescriptorConfig(realm, hostedEntityId);
                        } else if (hostedRole.equalsIgnoreCase(IFSConstants.SP)) {
                            hostedProviderDesc = metaManager.getSPDescriptor(realm, hostedEntityId);
                            hostedConfig = metaManager.getSPDescriptorConfig(realm, hostedEntityId);
                        }
                    }
                } catch (Exception e) {
                    FSUtils.debug.error("FSSOAPReceiver, provider", e);
                }
                FSLogoutNotification logoutRequest = new FSLogoutNotification(elt);
                Map map = handleLogoutRequest(elt, logoutRequest, message, request, response, hostedProviderDesc, hostedConfig, providerAlias, realm, hostedEntityId, hostedRole);
                String responseID = SAMLUtils.generateID();
                String inResponseTo = logoutRequest.getRequestID();
                String relayState = logoutRequest.getRelayState();
                FSLogoutResponse resp = null;
                boolean statusSuccess = false;
                SOAPMessage retSoapMessage = null;
                if (map == null) {
                    StatusCode statusCode = new StatusCode(IFSConstants.SAML_RESPONDER);
                    Status status = new Status(statusCode);
                    resp = new FSLogoutResponse(responseID, inResponseTo, status, hostedEntityId, relayState);
                } else {
                    retSoapMessage = (SOAPMessage) map.get(MESSAGE);
                    SOAPPart sp = retSoapMessage.getSOAPPart();
                    SOAPEnvelope se = sp.getEnvelope();
                    SOAPBody sb = se.getBody();
                    if (sb.hasFault()) {
                        StatusCode secondLevelstatusCode = new StatusCode(IFSConstants.SAML_UNSUPPORTED);
                        StatusCode statusCode = new StatusCode(IFSConstants.SAML_RESPONDER, secondLevelstatusCode);
                        Status status = new Status(statusCode);
                        resp = new FSLogoutResponse(responseID, inResponseTo, status, hostedEntityId, relayState);
                    } else {
                        StatusCode statusCode = new StatusCode(IFSConstants.SAML_SUCCESS);
                        Status status = new Status(statusCode);
                        resp = new FSLogoutResponse(responseID, inResponseTo, status, hostedEntityId, relayState);
                        statusSuccess = true;
                    }
                }
                resp.setID(IFSConstants.LOGOUTID);
                resp.setMinorVersion(logoutRequest.getMinorVersion());
                retSoapMessage = soapService.bind(resp.toXMLString(true, true));
                // Call SP Adapter postSingleLogoutSuccess for IDP/SOAP
                if (hostedRole != null && hostedRole.equalsIgnoreCase(IFSConstants.SP) && statusSuccess) {
                    FederationSPAdapter spAdapter = FSServiceUtils.getSPAdapter(hostedEntityId, hostedConfig);
                    if (spAdapter != null) {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("FSSOAPReceiver, " + "call postSingleLogoutSuccess, IDP/SOAP");
                        }
                        try {
                            spAdapter.postSingleLogoutSuccess(hostedEntityId, request, response, (String) map.get(USERID), logoutRequest, resp, IFSConstants.LOGOUT_IDP_SOAP_PROFILE);
                        } catch (Exception e) {
                            // ignore adapter exception
                            FSUtils.debug.error("postSingleLogoutSuccess." + "IDP/SOAP", e);
                        }
                    }
                }
                if (FSServiceUtils.isSigningOn()) {
                    try {
                        int minorVersion = resp.getMinorVersion();
                        if (minorVersion == IFSConstants.FF_11_PROTOCOL_MINOR_VERSION) {
                            retSoapMessage = signResponse(retSoapMessage, IFSConstants.ID, resp.getID(), hostedConfig);
                        } else if (minorVersion == IFSConstants.FF_12_PROTOCOL_MINOR_VERSION) {
                            retSoapMessage = signResponse(retSoapMessage, IFSConstants.RESPONSE_ID, resp.getResponseID(), hostedConfig);
                        } else {
                            FSUtils.debug.error("invalid minor version.");
                        }
                    } catch (SAMLException e) {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("LogoutResponse failed", e);
                        }
                        returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                        return;
                    } catch (FSMsgException e) {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("LogoutResponse failed", e);
                        }
                        returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                        return;
                    } catch (Exception e) {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("Logout exception:", e);
                        }
                    }
                }
                returnSOAPMessage(retSoapMessage, response);
                return;
            } catch (Exception se) {
                FSUtils.debug.error("Error in processing logout Request", se);
                String[] data = { FSUtils.bundle.getString(IFSConstants.LOGOUT_REQUEST_PROCESSING_FAILED) };
                LogUtil.error(Level.INFO, LogUtil.LOGOUT_REQUEST_PROCESSING_FAILED, data);
                returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                return;
            }
        }
    //check for other Liberty msgs should go here
    } catch (Exception e) {
        FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing Request: Exception occured: ", e);
        response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        java.io.ByteArrayOutputStream strm = new java.io.ByteArrayOutputStream();
        e.printStackTrace(new java.io.PrintStream(strm));
        FSUtils.debug.error(strm.toString());
        returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
        return;
    }
    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
    return;
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) NameIdentifier(com.sun.identity.saml.assertion.NameIdentifier) EncryptedNameIdentifier(com.sun.identity.federation.message.common.EncryptedNameIdentifier) Element(org.w3c.dom.Element) FSAuthnRequest(com.sun.identity.federation.message.FSAuthnRequest) FSLogoutNotification(com.sun.identity.federation.message.FSLogoutNotification) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) Document(org.w3c.dom.Document) SOAPMessage(javax.xml.soap.SOAPMessage) BaseConfigType(com.sun.identity.federation.jaxb.entityconfig.BaseConfigType) FSAssertion(com.sun.identity.federation.message.FSAssertion) Iterator(java.util.Iterator) FSException(com.sun.identity.federation.common.FSException) SOAPPart(javax.xml.soap.SOAPPart) List(java.util.List) FSSAMLRequest(com.sun.identity.federation.message.FSSAMLRequest) FederationSPAdapter(com.sun.identity.federation.plugins.FederationSPAdapter) FSLogoutStatus(com.sun.identity.federation.services.logout.FSLogoutStatus) FSMsgException(com.sun.identity.federation.message.common.FSMsgException) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) ProviderDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.ProviderDescriptorType) XMLSignatureManager(com.sun.identity.saml.xmlsig.XMLSignatureManager) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FSNameIdentifierMappingResponse(com.sun.identity.federation.message.FSNameIdentifierMappingResponse) FSLogoutResponse(com.sun.identity.federation.message.FSLogoutResponse) SOAPException(javax.xml.soap.SOAPException) SystemConfigurationException(com.sun.identity.common.SystemConfigurationException) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) FSMsgException(com.sun.identity.federation.message.common.FSMsgException) FSException(com.sun.identity.federation.common.FSException) IDPDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.IDPDescriptorType) SOAPBody(javax.xml.soap.SOAPBody) FSSSOBrowserArtifactProfileHandler(com.sun.identity.federation.services.fednsso.FSSSOBrowserArtifactProfileHandler) FSNameMappingHandler(com.sun.identity.federation.services.namemapping.FSNameMappingHandler) IDFFMetaManager(com.sun.identity.federation.meta.IDFFMetaManager) FSResponse(com.sun.identity.federation.message.FSResponse) FSNameRegistrationResponse(com.sun.identity.federation.message.FSNameRegistrationResponse) FSNameIdentifierMappingRequest(com.sun.identity.federation.message.FSNameIdentifierMappingRequest) Map(java.util.Map) HashMap(java.util.HashMap)

Example 4 with SOAPEnvelope

use of javax.xml.soap.SOAPEnvelope 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 5 with SOAPEnvelope

use of javax.xml.soap.SOAPEnvelope in project camel by apache.

the class TesterBean method processSOAP.

public SOAPMessage processSOAP(Exchange exchange) {
    // Since the Camel-CXF endpoint uses a list to store the parameters
    // and bean component uses the bodyAs expression to get the value
    // we'll need to deal with the parameters ourself
    SOAPMessage soapMessage = (SOAPMessage) exchange.getIn().getBody(List.class).get(0);
    if (soapMessage == null) {
        System.out.println("Incoming null message detected...");
        return createDefaultSoapMessage("Greetings from Apache Camel!!!!", "null");
    }
    try {
        SOAPPart sp = soapMessage.getSOAPPart();
        SOAPEnvelope se = sp.getEnvelope();
        SOAPBody sb = se.getBody();
        String requestText = sb.getFirstChild().getTextContent();
        System.out.println(requestText);
        return createDefaultSoapMessage("Greetings from Apache Camel!!!!", requestText);
    } catch (Exception e) {
        e.printStackTrace();
        return createDefaultSoapMessage("Greetings from Apache Camel!!!!", e.getClass().getName());
    }
}
Also used : SOAPBody(javax.xml.soap.SOAPBody) SOAPPart(javax.xml.soap.SOAPPart) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) SOAPMessage(javax.xml.soap.SOAPMessage) SOAPException(javax.xml.soap.SOAPException)

Aggregations

SOAPEnvelope (javax.xml.soap.SOAPEnvelope)62 SOAPMessage (javax.xml.soap.SOAPMessage)37 SOAPException (javax.xml.soap.SOAPException)32 SOAPPart (javax.xml.soap.SOAPPart)26 SOAPBody (javax.xml.soap.SOAPBody)25 SOAPElement (javax.xml.soap.SOAPElement)22 SOAPHeader (javax.xml.soap.SOAPHeader)17 SOAPHeaderElement (javax.xml.soap.SOAPHeaderElement)14 Name (javax.xml.soap.Name)13 Iterator (java.util.Iterator)12 QName (javax.xml.namespace.QName)12 WebServiceException (javax.xml.ws.WebServiceException)10 MessageFactory (javax.xml.soap.MessageFactory)8 ProtocolException (javax.xml.ws.ProtocolException)7 SOAPMessageContext (javax.xml.ws.handler.soap.SOAPMessageContext)6 CoordinationContextType (org.oasis_open.docs.ws_tx.wscoor._2006._06.CoordinationContextType)6 Document (org.w3c.dom.Document)6 Detail (javax.xml.soap.Detail)5 SOAPConnection (javax.xml.soap.SOAPConnection)5 SOAPFault (javax.xml.soap.SOAPFault)5