Search in sources :

Example 1 with SOAPHeaderElementProcessorRegistry

use of com.helger.phase4.servlet.soap.SOAPHeaderElementProcessorRegistry in project phase4 by phax.

the class AS4RequestHandler method _handleSoapMessage.

@Nullable
private IAS4ResponseFactory _handleSoapMessage(@Nonnull final HttpHeaderMap aHttpHeaders, @Nonnull final Document aSoapDocument, @Nonnull final ESoapVersion eSoapVersion, @Nonnull final ICommonsList<WSS4JAttachment> aIncomingAttachments, @Nonnull final ICommonsList<Ebms3Error> aErrorMessagesTarget) throws WSSecurityException, MessagingException, Phase4Exception {
    final SOAPHeaderElementProcessorRegistry aRegistry = SOAPHeaderElementProcessorRegistry.createDefault(m_aPModeResolver, m_aCryptoFactory, (IPMode) null);
    final IAS4MessageState aState = AS4IncomingHandler.processEbmsMessage(m_aResHelper, m_aLocale, aRegistry, aHttpHeaders, aSoapDocument, eSoapVersion, aIncomingAttachments, m_aIncomingProfileSelector, aErrorMessagesTarget);
    final IPMode aPMode = aState.getPMode();
    final PModeLeg aEffectiveLeg = aState.getEffectivePModeLeg();
    final String sMessageID = aState.getMessageID();
    final ICommonsList<WSS4JAttachment> aDecryptedAttachments = aState.hasDecryptedAttachments() ? aState.getDecryptedAttachments() : aState.getOriginalAttachments();
    final Node aPayloadNode = aState.getSoapBodyPayloadNode();
    final Ebms3UserMessage aEbmsUserMessage = aState.getEbmsUserMessage();
    final Ebms3SignalMessage aEbmsSignalMessage = aState.getEbmsSignalMessage();
    if (aState.isSoapHeaderElementProcessingSuccessful()) {
        final String sProfileID = aState.getProfileID();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("No checking for duplicate message with message ID '" + sMessageID + "' and profile ID '" + sProfileID + "'");
        final boolean bIsDuplicate = MetaAS4Manager.getIncomingDuplicateMgr().registerAndCheck(sMessageID, sProfileID, aPMode == null ? null : aPMode.getID()).isBreak();
        if (bIsDuplicate) {
            LOGGER.error("Not invoking SPIs, because message with Message ID '" + sMessageID + "' was already handled!");
            aErrorMessagesTarget.add(EEbmsError.EBMS_OTHER.getAsEbms3Error(m_aLocale, sMessageID, "Another message with the same Message ID '" + sMessageID + "' was already received!"));
        } else {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Message is not a duplicate");
        }
    }
    final SPIInvocationResult aSPIResult = new SPIInvocationResult();
    // Storing for two-way response messages
    final ICommonsList<WSS4JAttachment> aResponseAttachments = new CommonsArrayList<>();
    // Invoke SPIs if
    // * No errors so far (sign, encrypt, ...)
    // * Valid PMode
    // * Exactly one UserMessage or SignalMessage
    // * No ping/test message
    // * No Duplicate message ID
    final boolean bCanInvokeSPIs = aErrorMessagesTarget.isEmpty() && !aState.isPingMessage();
    if (bCanInvokeSPIs) {
        // PMode may be null for receipts
        if (aPMode == null || aPMode.getMEPBinding().isSynchronous() || aPMode.getMEPBinding().isAsynchronousInitiator() || aState.getEffectivePModeLegNumber() != 1) {
            // Call synchronous
            // Might add to aErrorMessages
            // Might add to aResponseAttachments
            // Might add to m_aPullReturnUserMsg
            _invokeSPIsForIncoming(aHttpHeaders, aEbmsUserMessage, aEbmsSignalMessage, aPayloadNode, aDecryptedAttachments, aPMode, aState, aErrorMessagesTarget, aResponseAttachments, aSPIResult);
            if (aSPIResult.isFailure())
                LOGGER.warn("Error invoking synchronous SPIs");
            else if (LOGGER.isDebugEnabled())
                LOGGER.debug("Successfully invoked synchronous SPIs");
            if (m_aSoapProcessingFinalizedCB != null)
                m_aSoapProcessingFinalizedCB.onProcessingFinalized(true);
        } else {
            // Call asynchronous
            // Only leg1 can be async!
            final IThrowingRunnable<Exception> r = () -> {
                // Start async
                final ICommonsList<Ebms3Error> aLocalErrorMessages = new CommonsArrayList<>();
                final ICommonsList<WSS4JAttachment> aLocalResponseAttachments = new CommonsArrayList<>();
                final SPIInvocationResult aAsyncSPIResult = new SPIInvocationResult();
                _invokeSPIsForIncoming(aHttpHeaders, aEbmsUserMessage, aEbmsSignalMessage, aPayloadNode, aDecryptedAttachments, aPMode, aState, aLocalErrorMessages, aLocalResponseAttachments, aAsyncSPIResult);
                final IAS4ResponseFactory aAsyncResponseFactory;
                final String sResponseMessageID;
                if (aAsyncSPIResult.isSuccess()) {
                    // SPI processing succeeded
                    assert aLocalErrorMessages.isEmpty();
                    // The response user message has no explicit payload. All data of
                    // the response user message is in the local attachments
                    sResponseMessageID = MessageHelperMethods.createRandomMessageID();
                    final AS4UserMessage aResponseUserMsg = _createReversedUserMessage(eSoapVersion, sResponseMessageID, aEbmsUserMessage, aLocalResponseAttachments);
                    // Send UserMessage
                    final AS4SigningParams aSigningParams = new AS4SigningParams().setFromPMode(aEffectiveLeg.getSecurity());
                    // Use the original receiver ID as the alias into the keystore for
                    // encrypting the response message
                    final String sEncryptionAlias = aEbmsUserMessage.getPartyInfo().getTo().getPartyIdAtIndex(0).getValue();
                    final AS4CryptParams aCryptParams = new AS4CryptParams().setFromPMode(aEffectiveLeg.getSecurity()).setAlias(sEncryptionAlias);
                    aAsyncResponseFactory = _createResponseUserMessage(aState, aEffectiveLeg.getProtocol().getSoapVersion(), aResponseUserMsg, aResponseAttachments, aSigningParams, aCryptParams);
                } else {
                    // SPI processing failed
                    // Send ErrorMessage Undefined - see
                    // https://github.com/phax/phase4/issues/4
                    final AS4ErrorMessage aResponseErrorMsg = AS4ErrorMessage.create(eSoapVersion, aState.getMessageID(), aLocalErrorMessages);
                    sResponseMessageID = aResponseErrorMsg.getEbms3SignalMessage().getMessageInfo().getMessageId();
                    // Pass error messages to the outside
                    if (m_aErrorConsumer != null && aLocalErrorMessages.isNotEmpty())
                        m_aErrorConsumer.onAS4ErrorMessage(aState, aLocalErrorMessages, aResponseErrorMsg);
                    aAsyncResponseFactory = new AS4ResponseFactoryXML(m_aMessageMetadata, aState, sResponseMessageID, aResponseErrorMsg.getAsSoapDocument(), eSoapVersion.getMimeType());
                }
                // where to send it back (must be determined by SPI!)
                final String sAsyncResponseURL = aAsyncSPIResult.getAsyncResponseURL();
                if (StringHelper.hasNoText(sAsyncResponseURL))
                    throw new IllegalStateException("No asynchronous response URL present - please check your SPI implementation");
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Responding asynchronous to: " + sAsyncResponseURL);
                // Ensure HttpEntity is repeatable
                HttpEntity aHttpEntity = aAsyncResponseFactory.getHttpEntityForSending(eSoapVersion.getMimeType());
                aHttpEntity = m_aResHelper.createRepeatableHttpEntity(aHttpEntity);
                // Use the prebuilt entity for dumping
                _invokeSPIsForResponse(aState, aAsyncResponseFactory, aHttpEntity, eSoapVersion.getMimeType(), sResponseMessageID);
                // invoke client with new document
                final BasicHttpPoster aSender = new BasicHttpPoster();
                final Document aAsyncResponse;
                if (true) {
                    final HttpHeaderMap aResponseHttpHeaders = null;
                    // TODO make async send parameters customizable
                    final HttpRetrySettings aRetrySettings = new HttpRetrySettings();
                    aAsyncResponse = aSender.sendGenericMessageWithRetries(sAsyncResponseURL, aResponseHttpHeaders, aHttpEntity, sMessageID, aRetrySettings, new ResponseHandlerXml(), m_aOutgoingDumper, m_aRetryCallback);
                } else {
                    aAsyncResponse = aSender.sendGenericMessage(sAsyncResponseURL, null, aHttpEntity, new ResponseHandlerXml());
                }
                AS4HttpDebug.debug(() -> "SEND-RESPONSE [async sent] received: " + XMLWriter.getNodeAsString(aAsyncResponse, AS4HttpDebug.getDebugXMLWriterSettings()));
            };
            final CompletableFuture<Void> aFuture = PhotonWorkerPool.getInstance().runThrowing(CAS4.LIB_NAME + " async processing", r);
            if (m_aSoapProcessingFinalizedCB != null) {
                // Give the outside world the possibility to get notified when the
                // processing is done
                aFuture.thenRun(() -> m_aSoapProcessingFinalizedCB.onProcessingFinalized(false));
            }
        }
    }
    // Try building error message
    final String sResponseMessageID;
    final IAS4ResponseFactory ret;
    if (!aState.isSoapHeaderElementProcessingSuccessful() || aState.getEbmsError() == null) {
        // Not an incoming Ebms Error Message
        if (aErrorMessagesTarget.isNotEmpty()) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Creating AS4 error message with these " + aErrorMessagesTarget.size() + " errors: " + aErrorMessagesTarget.getAllMapped(Ebms3Error::getDescriptionValue));
            final AS4ErrorMessage aResponseErrorMsg = AS4ErrorMessage.create(eSoapVersion, aState.getMessageID(), aErrorMessagesTarget);
            // Call optional consumer
            if (m_aErrorConsumer != null)
                m_aErrorConsumer.onAS4ErrorMessage(aState, aErrorMessagesTarget, aResponseErrorMsg);
            // When aLeg == null, the response is true
            if (_isSendErrorAsResponse(aEffectiveLeg)) {
                sResponseMessageID = aResponseErrorMsg.getEbms3SignalMessage().getMessageInfo().getMessageId();
                ret = new AS4ResponseFactoryXML(m_aMessageMetadata, aState, sResponseMessageID, aResponseErrorMsg.getAsSoapDocument(), eSoapVersion.getMimeType());
            } else {
                LOGGER.warn("Not sending back the error, because sending error response is prohibited in PMode");
                sResponseMessageID = null;
                ret = null;
            }
        } else {
            // Do not respond to receipt (except with error message - see above)
            if (aEbmsSignalMessage == null || aEbmsSignalMessage.getReceipt() == null) {
                // So now the incoming message is a user message or a pull request
                if (aPMode.getMEP().isOneWay() || aPMode.getMEPBinding().isAsynchronous()) {
                    // the pull phase
                    if (aPMode.getMEPBinding().equals(EMEPBinding.PULL) || (aPMode.getMEPBinding().equals(EMEPBinding.PULL_PUSH) && aSPIResult.hasPullReturnUserMsg()) || (aPMode.getMEPBinding().equals(EMEPBinding.PUSH_PULL) && aSPIResult.hasPullReturnUserMsg())) {
                        // TODO would be nice to have attachments here I guess
                        final AS4UserMessage aResponseUserMsg = new AS4UserMessage(eSoapVersion, aSPIResult.getPullReturnUserMsg());
                        sResponseMessageID = aResponseUserMsg.getEbms3UserMessage().getMessageInfo().getMessageId();
                        ret = new AS4ResponseFactoryXML(m_aMessageMetadata, aState, sResponseMessageID, aResponseUserMsg.getAsSoapDocument(), eSoapVersion.getMimeType());
                    } else if (aEbmsUserMessage != null) {
                        // We received an incoming user message and no errors occurred
                        final boolean bSendReceiptAsResponse = _isSendReceiptAsResponse(aEffectiveLeg);
                        if (bSendReceiptAsResponse) {
                            sResponseMessageID = MessageHelperMethods.createRandomMessageID();
                            ret = _createResponseReceiptMessage(aState, aSoapDocument, eSoapVersion, sResponseMessageID, aEffectiveLeg, aEbmsUserMessage, aResponseAttachments);
                        } else {
                            // TODO what shall we send back here?
                            LOGGER.info("Not sending back the Receipt response, because sending Receipt response is prohibited in PMode");
                            sResponseMessageID = null;
                            ret = null;
                        }
                    } else {
                        sResponseMessageID = null;
                        ret = null;
                    }
                } else {
                    // synchronous TWO - WAY (= "SYNC")
                    final PModeLeg aLeg2 = aPMode.getLeg2();
                    if (aLeg2 == null)
                        throw new Phase4Exception("PMode has no leg2!");
                    if (MEPHelper.isValidResponseTypeLeg2(aPMode.getMEP(), aPMode.getMEPBinding(), EAS4MessageType.USER_MESSAGE)) {
                        sResponseMessageID = MessageHelperMethods.createRandomMessageID();
                        final AS4UserMessage aResponseUserMsg = _createReversedUserMessage(eSoapVersion, sResponseMessageID, aEbmsUserMessage, aResponseAttachments);
                        final AS4SigningParams aSigningParams = new AS4SigningParams().setFromPMode(aLeg2.getSecurity());
                        final String sEncryptionAlias = aEbmsUserMessage.getPartyInfo().getTo().getPartyIdAtIndex(0).getValue();
                        final AS4CryptParams aCryptParams = new AS4CryptParams().setFromPMode(aLeg2.getSecurity()).setAlias(sEncryptionAlias);
                        ret = _createResponseUserMessage(aState, aLeg2.getProtocol().getSoapVersion(), aResponseUserMsg, aResponseAttachments, aSigningParams, aCryptParams);
                    } else {
                        sResponseMessageID = null;
                        ret = null;
                    }
                }
            } else {
                sResponseMessageID = null;
                ret = null;
            }
        }
    } else {
        sResponseMessageID = null;
        ret = null;
    }
    // Create the HttpEntity on demand
    _invokeSPIsForResponse(aState, ret, null, eSoapVersion.getMimeType(), sResponseMessageID);
    return ret;
}
Also used : Ebms3SignalMessage(com.helger.phase4.ebms3header.Ebms3SignalMessage) ICommonsList(com.helger.commons.collection.impl.ICommonsList) PModeLeg(com.helger.phase4.model.pmode.leg.PModeLeg) HttpEntity(org.apache.http.HttpEntity) SOAPHeaderElementProcessorRegistry(com.helger.phase4.servlet.soap.SOAPHeaderElementProcessorRegistry) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) HttpRetrySettings(com.helger.phase4.http.HttpRetrySettings) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) Phase4Exception(com.helger.phase4.util.Phase4Exception) AS4CryptParams(com.helger.phase4.crypto.AS4CryptParams) AS4SigningParams(com.helger.phase4.crypto.AS4SigningParams) BasicHttpPoster(com.helger.phase4.http.BasicHttpPoster) AS4UserMessage(com.helger.phase4.messaging.domain.AS4UserMessage) AS4DecompressException(com.helger.phase4.attachment.AS4DecompressException) MessagingException(javax.mail.MessagingException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Phase4Exception(com.helger.phase4.util.Phase4Exception) IOException(java.io.IOException) IPMode(com.helger.phase4.model.pmode.IPMode) ResponseHandlerXml(com.helger.httpclient.response.ResponseHandlerXml) Ebms3UserMessage(com.helger.phase4.ebms3header.Ebms3UserMessage) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment) AS4ErrorMessage(com.helger.phase4.messaging.domain.AS4ErrorMessage) Nullable(javax.annotation.Nullable)

Example 2 with SOAPHeaderElementProcessorRegistry

use of com.helger.phase4.servlet.soap.SOAPHeaderElementProcessorRegistry in project phase4 by phax.

the class AS4IncomingHandler method _processSoapHeaderElements.

private static void _processSoapHeaderElements(@Nonnull final SOAPHeaderElementProcessorRegistry aRegistry, @Nonnull final Document aSoapDocument, @Nonnull final ICommonsList<WSS4JAttachment> aIncomingAttachments, @Nonnull final AS4MessageState aState, @Nonnull final ICommonsList<Ebms3Error> aErrorMessages) throws Phase4Exception {
    final ESoapVersion eSoapVersion = aState.getSoapVersion();
    final ICommonsList<AS4SingleSOAPHeader> aHeaders = new CommonsArrayList<>();
    {
        // Find SOAP header
        final Node aHeaderNode = XMLHelper.getFirstChildElementOfName(aSoapDocument.getDocumentElement(), eSoapVersion.getNamespaceURI(), eSoapVersion.getHeaderElementName());
        if (aHeaderNode == null)
            throw new Phase4Exception("SOAP document is missing a Header element {" + eSoapVersion.getNamespaceURI() + "}" + eSoapVersion.getHeaderElementName());
        // Extract all header elements including their "mustUnderstand" value
        for (final Element aHeaderChild : new ChildElementIterator(aHeaderNode)) {
            final QName aQName = XMLHelper.getQName(aHeaderChild);
            final String sMustUnderstand = aHeaderChild.getAttributeNS(eSoapVersion.getNamespaceURI(), "mustUnderstand");
            final boolean bIsMustUnderstand = eSoapVersion.getMustUnderstandValue(true).equals(sMustUnderstand);
            aHeaders.add(new AS4SingleSOAPHeader(aHeaderChild, aQName, bIsMustUnderstand));
        }
    }
    final ICommonsOrderedMap<QName, ISOAPHeaderElementProcessor> aAllProcessors = aRegistry.getAllElementProcessors();
    if (aAllProcessors.isEmpty())
        LOGGER.error("No SOAP Header element processor is registered");
    // handle all headers in the order of the registered handlers!
    for (final Map.Entry<QName, ISOAPHeaderElementProcessor> aEntry : aAllProcessors.entrySet()) {
        final QName aQName = aEntry.getKey();
        // Check if this message contains a header for the current handler
        final AS4SingleSOAPHeader aHeader = aHeaders.findFirst(x -> aQName.equals(x.getQName()));
        if (aHeader == null) {
            // no header element for current processor
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Message contains no SOAP header element with QName " + aQName.toString());
            continue;
        }
        final ISOAPHeaderElementProcessor aProcessor = aEntry.getValue();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Processing SOAP header element " + aQName.toString() + " with processor " + aProcessor);
        // Error list for this processor
        final ErrorList aErrorList = new ErrorList();
        try {
            // Process element
            if (aProcessor.processHeaderElement(aSoapDocument, aHeader.getNode(), aIncomingAttachments, aState, aErrorList).isSuccess()) {
                // Mark header as processed (for mustUnderstand check)
                aHeader.setProcessed(true);
            } else {
                // upon failure, the element stays unprocessed and sends back a signal
                // message with the errors
                LOGGER.error("Failed to process SOAP header element " + aQName.toString() + " with processor " + aProcessor + "; error details: " + aErrorList);
                final String sRefToMessageID = aState.getMessageID();
                final Locale aLocale = aState.getLocale();
                for (final IError aError : aErrorList) {
                    final EEbmsError ePredefinedError = EEbmsError.getFromErrorCodeOrNull(aError.getErrorID());
                    if (ePredefinedError != null)
                        aErrorMessages.add(ePredefinedError.getAsEbms3Error(aLocale, sRefToMessageID));
                    else {
                        final Ebms3Error aEbms3Error = new Ebms3Error();
                        aEbms3Error.setErrorDetail(aError.getErrorText(aLocale));
                        aEbms3Error.setErrorCode(aError.getErrorID());
                        aEbms3Error.setSeverity(aError.getErrorLevel().getID());
                        aEbms3Error.setOrigin(aError.getErrorFieldName());
                        aEbms3Error.setRefToMessageInError(sRefToMessageID);
                        aErrorMessages.add(aEbms3Error);
                    }
                }
                // Stop processing of other headers
                break;
            }
        } catch (final Exception ex) {
            // upon failure, the element stays unprocessed and sends back a signal
            // message with the errors
            LOGGER.error("Error processing SOAP header element " + aQName.toString() + " with processor " + aProcessor, ex);
            aErrorMessages.add(EEbmsError.EBMS_OTHER.getAsEbms3Error(aState.getLocale(), aState.getMessageID(), "Error processing SOAP header element " + aQName.toString()));
            // Stop processing of other headers
            break;
        }
    }
    // If an error message is present, send it back gracefully
    if (aErrorMessages.isEmpty()) {
        // Are all must-understand headers processed?
        for (final AS4SingleSOAPHeader aHeader : aHeaders) if (aHeader.isMustUnderstand() && !aHeader.isProcessed())
            throw new Phase4Exception("Required SOAP header element " + aHeader.getQName().toString() + " could not be handled");
    }
}
Also used : Locale(java.util.Locale) QName(javax.xml.namespace.QName) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Ebms3Error(com.helger.phase4.ebms3header.Ebms3Error) IError(com.helger.commons.error.IError) AS4DecompressException(com.helger.phase4.attachment.AS4DecompressException) MessagingException(javax.mail.MessagingException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Phase4Exception(com.helger.phase4.util.Phase4Exception) IOException(java.io.IOException) AS4SingleSOAPHeader(com.helger.phase4.servlet.soap.AS4SingleSOAPHeader) Phase4Exception(com.helger.phase4.util.Phase4Exception) ErrorList(com.helger.commons.error.list.ErrorList) ESoapVersion(com.helger.phase4.soap.ESoapVersion) ChildElementIterator(com.helger.xml.ChildElementIterator) EEbmsError(com.helger.phase4.error.EEbmsError) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) Map(java.util.Map) ICommonsOrderedMap(com.helger.commons.collection.impl.ICommonsOrderedMap) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) ISOAPHeaderElementProcessor(com.helger.phase4.servlet.soap.ISOAPHeaderElementProcessor)

Example 3 with SOAPHeaderElementProcessorRegistry

use of com.helger.phase4.servlet.soap.SOAPHeaderElementProcessorRegistry in project phase4 by phax.

the class AS4IncomingHandler method _parseMessage.

@Nullable
private static IAS4MessageState _parseMessage(@Nonnull final IAS4CryptoFactory aCryptoFactory, @Nonnull final IPModeResolver aPModeResolver, @Nonnull final IAS4IncomingAttachmentFactory aIAF, @Nonnull final IAS4IncomingProfileSelector aAS4ProfileSelector, @Nonnull @WillNotClose final AS4ResourceHelper aResHelper, @Nullable final IPMode aSendingPMode, @Nonnull final Locale aLocale, @Nonnull final IAS4IncomingMessageMetadata aMessageMetadata, @Nonnull final HttpResponse aHttpResponse, @Nonnull final byte[] aResponsePayload, @Nullable final IAS4IncomingDumper aIncomingDumper) throws Phase4Exception {
    // This wrapper will take the result
    final Wrapper<IAS4MessageState> aRetWrapper = new Wrapper<>();
    // Handler for the parsed message
    final IAS4ParsedMessageCallback aCallback = (aHttpHeaders, aSoapDocument, eSoapVersion, aIncomingAttachments) -> {
        final ICommonsList<Ebms3Error> aErrorMessages = new CommonsArrayList<>();
        // Use the sending PMode as fallback, because from the incoming
        // receipt/error it is impossible to detect a PMode
        final SOAPHeaderElementProcessorRegistry aRegistry = SOAPHeaderElementProcessorRegistry.createDefault(aPModeResolver, aCryptoFactory, aSendingPMode);
        // Parse AS4, verify signature etc
        final IAS4MessageState aState = processEbmsMessage(aResHelper, aLocale, aRegistry, aHttpHeaders, aSoapDocument, eSoapVersion, aIncomingAttachments, aAS4ProfileSelector, aErrorMessages);
        if (aState.isSoapHeaderElementProcessingSuccessful()) {
            // Remember the parsed signal message
            aRetWrapper.set(aState);
        } else {
            throw new Phase4Exception("Error processing AS4 message", aState.getSoapWSS4JException());
        }
    };
    // Create header map from response headers
    final HttpHeaderMap aHttpHeaders = new HttpHeaderMap();
    for (final Header aHeader : aHttpResponse.getAllHeaders()) aHttpHeaders.addHeader(aHeader.getName(), aHeader.getValue());
    try (final NonBlockingByteArrayInputStream aPayloadIS = new NonBlockingByteArrayInputStream(aResponsePayload)) {
        // Parse incoming message
        parseAS4Message(aIAF, aResHelper, aMessageMetadata, aPayloadIS, aHttpHeaders, aCallback, aIncomingDumper);
    } catch (final Phase4Exception ex) {
        throw ex;
    } catch (final Exception ex) {
        throw new Phase4Exception("Error parsing AS4 message", ex);
    }
    // This one contains the result
    return aRetWrapper.get();
}
Also used : AS4DecompressException(com.helger.phase4.attachment.AS4DecompressException) AS4SingleSOAPHeader(com.helger.phase4.servlet.soap.AS4SingleSOAPHeader) ESoapVersion(com.helger.phase4.soap.ESoapVersion) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) XMLHelper(com.helger.xml.XMLHelper) LoggerFactory(org.slf4j.LoggerFactory) MessagingException(javax.mail.MessagingException) CollectionHelper(com.helger.commons.collection.CollectionHelper) Header(org.apache.http.Header) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Locale(java.util.Locale) Document(org.w3c.dom.Document) Map(java.util.Map) IAS4IncomingMessageMetadata(com.helger.phase4.messaging.IAS4IncomingMessageMetadata) PModeLeg(com.helger.phase4.model.pmode.leg.PModeLeg) IAS4IncomingAttachmentFactory(com.helger.phase4.attachment.IAS4IncomingAttachmentFactory) IAS4ProfileValidator(com.helger.phase4.profile.IAS4ProfileValidator) IAS4Profile(com.helger.phase4.profile.IAS4Profile) ICommonsOrderedMap(com.helger.commons.collection.impl.ICommonsOrderedMap) SOAPHeaderElementProcessorRegistry(com.helger.phase4.servlet.soap.SOAPHeaderElementProcessorRegistry) StandardCharsets(java.nio.charset.StandardCharsets) MimeTypeParser(com.helger.commons.mime.MimeTypeParser) AS4DumpManager(com.helger.phase4.dump.AS4DumpManager) Ebms3Error(com.helger.phase4.ebms3header.Ebms3Error) DOMReader(com.helger.xml.serialize.read.DOMReader) ICommonsList(com.helger.commons.collection.impl.ICommonsList) QName(javax.xml.namespace.QName) MultipartItemInputStream(com.helger.web.multipart.MultipartStream.MultipartItemInputStream) Ebms3SignalMessage(com.helger.phase4.ebms3header.Ebms3SignalMessage) Ebms3PartInfo(com.helger.phase4.ebms3header.Ebms3PartInfo) MessageHelperMethods(com.helger.phase4.messaging.domain.MessageHelperMethods) WillClose(javax.annotation.WillClose) MimeBodyPart(javax.mail.internet.MimeBodyPart) IError(com.helger.commons.error.IError) ErrorList(com.helger.commons.error.list.ErrorList) MultipartProgressNotifier(com.helger.web.multipart.MultipartProgressNotifier) MetaAS4Manager(com.helger.phase4.mgr.MetaAS4Manager) IAS4CryptoFactory(com.helger.phase4.crypto.IAS4CryptoFactory) CHttpHeader(com.helger.commons.http.CHttpHeader) MultipartStream(com.helger.web.multipart.MultipartStream) Node(org.w3c.dom.Node) IAS4IncomingDumper(com.helger.phase4.dump.IAS4IncomingDumper) AS4ResourceHelper(com.helger.phase4.util.AS4ResourceHelper) NonBlockingByteArrayInputStream(com.helger.commons.io.stream.NonBlockingByteArrayInputStream) Nonnull(javax.annotation.Nonnull) Phase4Exception(com.helger.phase4.util.Phase4Exception) Nullable(javax.annotation.Nullable) EEbmsError(com.helger.phase4.error.EEbmsError) Ebms3Property(com.helger.phase4.ebms3header.Ebms3Property) OutputStream(java.io.OutputStream) WillNotClose(javax.annotation.WillNotClose) Ebms3UserMessage(com.helger.phase4.ebms3header.Ebms3UserMessage) Logger(org.slf4j.Logger) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) HasInputStream(com.helger.commons.io.stream.HasInputStream) IPMode(com.helger.phase4.model.pmode.IPMode) StringHelper(com.helger.commons.string.StringHelper) IPModeResolver(com.helger.phase4.model.pmode.resolve.IPModeResolver) ChildElementIterator(com.helger.xml.ChildElementIterator) IOException(java.io.IOException) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment) ValueEnforcer(com.helger.commons.ValueEnforcer) Ebms3PullRequest(com.helger.phase4.ebms3header.Ebms3PullRequest) Element(org.w3c.dom.Element) Wrapper(com.helger.commons.wrapper.Wrapper) IHasInputStream(com.helger.commons.io.IHasInputStream) ISOAPHeaderElementProcessor(com.helger.phase4.servlet.soap.ISOAPHeaderElementProcessor) IMimeType(com.helger.commons.mime.IMimeType) Ebms3Receipt(com.helger.phase4.ebms3header.Ebms3Receipt) HttpResponse(org.apache.http.HttpResponse) AS4Helper(com.helger.phase4.model.AS4Helper) AS4XMLHelper(com.helger.phase4.util.AS4XMLHelper) EAS4CompressionMode(com.helger.phase4.attachment.EAS4CompressionMode) InputStream(java.io.InputStream) Wrapper(com.helger.commons.wrapper.Wrapper) ICommonsList(com.helger.commons.collection.impl.ICommonsList) SOAPHeaderElementProcessorRegistry(com.helger.phase4.servlet.soap.SOAPHeaderElementProcessorRegistry) AS4DecompressException(com.helger.phase4.attachment.AS4DecompressException) MessagingException(javax.mail.MessagingException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Phase4Exception(com.helger.phase4.util.Phase4Exception) IOException(java.io.IOException) NonBlockingByteArrayInputStream(com.helger.commons.io.stream.NonBlockingByteArrayInputStream) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) Phase4Exception(com.helger.phase4.util.Phase4Exception) AS4SingleSOAPHeader(com.helger.phase4.servlet.soap.AS4SingleSOAPHeader) Header(org.apache.http.Header) CHttpHeader(com.helger.commons.http.CHttpHeader) Nullable(javax.annotation.Nullable)

Example 4 with SOAPHeaderElementProcessorRegistry

use of com.helger.phase4.servlet.soap.SOAPHeaderElementProcessorRegistry in project phase4 by phax.

the class AS4IncomingHandler method processEbmsMessage.

@Nonnull
public static IAS4MessageState processEbmsMessage(@Nonnull @WillNotClose final AS4ResourceHelper aResHelper, @Nonnull final Locale aLocale, @Nonnull final SOAPHeaderElementProcessorRegistry aRegistry, @Nonnull final HttpHeaderMap aHttpHeaders, @Nonnull final Document aSoapDocument, @Nonnull final ESoapVersion eSoapVersion, @Nonnull final ICommonsList<WSS4JAttachment> aIncomingAttachments, @Nonnull final IAS4IncomingProfileSelector aAS4ProfileSelector, @Nonnull final ICommonsList<Ebms3Error> aErrorMessagesTarget) throws Phase4Exception {
    ValueEnforcer.notNull(aResHelper, "ResHelper");
    ValueEnforcer.notNull(aLocale, "Locale");
    ValueEnforcer.notNull(aHttpHeaders, "HttpHeaders");
    ValueEnforcer.notNull(aSoapDocument, "SoapDocument");
    ValueEnforcer.notNull(eSoapVersion, "SoapVersion");
    ValueEnforcer.notNull(aIncomingAttachments, "IncomingAttachments");
    ValueEnforcer.notNull(aAS4ProfileSelector, "AS4ProfileSelector");
    ValueEnforcer.notNull(aErrorMessagesTarget, "aErrorMessagesTarget");
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Received the following SOAP " + eSoapVersion.getVersion() + " document:");
        LOGGER.debug(AS4XMLHelper.serializeXML(aSoapDocument));
        if (aIncomingAttachments.isEmpty()) {
            LOGGER.debug("Without any incoming attachments");
        } else {
            LOGGER.debug("Including the following " + aIncomingAttachments.size() + " attachments:");
            LOGGER.debug(aIncomingAttachments.toString());
        }
    }
    // This is where all data from the SOAP headers is stored to
    final AS4MessageState aState = new AS4MessageState(eSoapVersion, aResHelper, aLocale);
    // Handle all headers - modifies the state
    _processSoapHeaderElements(aRegistry, aSoapDocument, aIncomingAttachments, aState, aErrorMessagesTarget);
    // Remember if header processing was successful or not
    final boolean bSoapHeaderElementProcessingSuccess = aErrorMessagesTarget.isEmpty();
    aState.setSoapHeaderElementProcessingSuccessful(bSoapHeaderElementProcessingSuccess);
    if (bSoapHeaderElementProcessingSuccess) {
        // Every message can only contain 1 User message or 1 pull message
        // aUserMessage can be null on incoming Pull-Message!
        final Ebms3UserMessage aEbmsUserMessage = aState.getEbmsUserMessage();
        final Ebms3Error aEbmsError = aState.getEbmsError();
        final Ebms3PullRequest aEbmsPullRequest = aState.getEbmsPullRequest();
        final Ebms3Receipt aEbmsReceipt = aState.getEbmsReceipt();
        // Check payload consistency
        final int nCountData = (aEbmsUserMessage != null ? 1 : 0) + (aEbmsPullRequest != null ? 1 : 0) + (aEbmsReceipt != null ? 1 : 0) + (aEbmsError != null ? 1 : 0);
        if (nCountData != 1) {
            LOGGER.error("Expected a UserMessage(" + (aEbmsUserMessage != null ? 1 : 0) + "), a PullRequest(" + (aEbmsPullRequest != null ? 1 : 0) + "), a Receipt(" + (aEbmsReceipt != null ? 1 : 0) + ") or an Error(" + (aEbmsError != null ? 1 : 0) + ")");
            // send EBMS:0001 error back
            aErrorMessagesTarget.add(EEbmsError.EBMS_VALUE_NOT_RECOGNIZED.getAsEbms3Error(aLocale, aState.getMessageID()));
        }
        // Determine AS4 profile ID (since 0.13.0)
        final String sProfileID = aAS4ProfileSelector.getAS4ProfileID(aState);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Determined AS4 profile ID '" + sProfileID + "' for current message");
        aState.setProfileID(sProfileID);
        final IPMode aPMode = aState.getPMode();
        final PModeLeg aEffectiveLeg = aState.getEffectivePModeLeg();
        if (aEbmsUserMessage != null) {
            // User message requires PMode
            if (aPMode == null)
                throw new Phase4Exception("No AS4 P-Mode configuration found for user-message!");
            // Only check leg if the message is a usermessage
            if (aEffectiveLeg == null)
                throw new Phase4Exception("No AS4 P-Mode leg could be determined!");
            // Only do profile checks if a profile is set
            if (StringHelper.hasText(sProfileID)) {
                // Resolve profile ID
                final IAS4Profile aProfile = MetaAS4Manager.getProfileMgr().getProfileOfID(sProfileID);
                if (aProfile == null)
                    throw new IllegalStateException("The configured AS4 profile '" + sProfileID + "' does not exist.");
                // Profile Checks gets set when started with Server
                final IAS4ProfileValidator aValidator = aProfile.getValidator();
                if (aValidator != null) {
                    if (aAS4ProfileSelector.validateAgainstProfile()) {
                        final ErrorList aErrorList = new ErrorList();
                        aValidator.validatePMode(aPMode, aErrorList);
                        aValidator.validateUserMessage(aEbmsUserMessage, aErrorList);
                        if (aErrorList.isNotEmpty()) {
                            throw new Phase4Exception("Error validating incoming AS4 message with the profile " + aProfile.getDisplayName() + "\n Following errors are present: " + aErrorList.getAllErrors().getAllTexts(aLocale));
                        }
                    } else {
                        LOGGER.warn("The AS4 profile '" + sProfileID + "' has a validation configured, but the usage was disabled using the AS4ProfileSelector");
                    }
                }
            } else {
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("AS4 state contains no AS4 profile ID - therefore no consistency checks are performed");
            }
            // Ensure the decrypted attachments are used
            final ICommonsList<WSS4JAttachment> aDecryptedAttachments = aState.hasDecryptedAttachments() ? aState.getDecryptedAttachments() : aState.getOriginalAttachments();
            // Decompress attachments (if compressed)
            // Result is directly in the decrypted attachments list!
            _decompressAttachments(aDecryptedAttachments, aEbmsUserMessage, aState);
        } else {
            // Pull-request also requires PMode
            if (aEbmsPullRequest != null && aPMode == null)
                throw new Phase4Exception("No AS4 P-Mode configuration found for pull-request!");
        }
        final boolean bUseDecryptedSOAP = aState.hasDecryptedSoapDocument();
        final Document aRealSOAPDoc = bUseDecryptedSOAP ? aState.getDecryptedSoapDocument() : aSoapDocument;
        assert aRealSOAPDoc != null;
        // Find SOAP body (mandatory according to SOAP XSD)
        final Node aBodyNode = XMLHelper.getFirstChildElementOfName(aRealSOAPDoc.getDocumentElement(), eSoapVersion.getNamespaceURI(), eSoapVersion.getBodyElementName());
        if (aBodyNode == null)
            throw new Phase4Exception((bUseDecryptedSOAP ? "Decrypted" : "Original") + " SOAP document is missing a Body element");
        aState.setSoapBodyPayloadNode(aBodyNode.getFirstChild());
        final boolean bIsPingMessage = AS4Helper.isPingMessage(aPMode);
        aState.setPingMessage(bIsPingMessage);
        if (bIsPingMessage)
            LOGGER.info("Received an AS4 Ping message - meaning it will NOT be handled by the custom handlers.");
    }
    return aState;
}
Also used : Ebms3Receipt(com.helger.phase4.ebms3header.Ebms3Receipt) IAS4Profile(com.helger.phase4.profile.IAS4Profile) PModeLeg(com.helger.phase4.model.pmode.leg.PModeLeg) Node(org.w3c.dom.Node) Ebms3Error(com.helger.phase4.ebms3header.Ebms3Error) Document(org.w3c.dom.Document) Phase4Exception(com.helger.phase4.util.Phase4Exception) ErrorList(com.helger.commons.error.list.ErrorList) Ebms3PullRequest(com.helger.phase4.ebms3header.Ebms3PullRequest) IPMode(com.helger.phase4.model.pmode.IPMode) Ebms3UserMessage(com.helger.phase4.ebms3header.Ebms3UserMessage) IAS4ProfileValidator(com.helger.phase4.profile.IAS4ProfileValidator) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment) Nonnull(javax.annotation.Nonnull)

Aggregations

Phase4Exception (com.helger.phase4.util.Phase4Exception)4 Node (org.w3c.dom.Node)4 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)3 ErrorList (com.helger.commons.error.list.ErrorList)3 HttpHeaderMap (com.helger.commons.http.HttpHeaderMap)3 AS4DecompressException (com.helger.phase4.attachment.AS4DecompressException)3 WSS4JAttachment (com.helger.phase4.attachment.WSS4JAttachment)3 Ebms3Error (com.helger.phase4.ebms3header.Ebms3Error)3 Ebms3UserMessage (com.helger.phase4.ebms3header.Ebms3UserMessage)3 IPMode (com.helger.phase4.model.pmode.IPMode)3 PModeLeg (com.helger.phase4.model.pmode.leg.PModeLeg)3 IOException (java.io.IOException)3 MessagingException (javax.mail.MessagingException)3 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)3 Document (org.w3c.dom.Document)3 ICommonsList (com.helger.commons.collection.impl.ICommonsList)2 ICommonsOrderedMap (com.helger.commons.collection.impl.ICommonsOrderedMap)2 IError (com.helger.commons.error.IError)2 Ebms3PullRequest (com.helger.phase4.ebms3header.Ebms3PullRequest)2 Ebms3Receipt (com.helger.phase4.ebms3header.Ebms3Receipt)2