Search in sources :

Example 6 with AS4ResourceHelper

use of com.helger.phase4.util.AS4ResourceHelper in project phase4 by phax.

the class AS4IncomingHandler method parseAS4Message.

public static void parseAS4Message(@Nonnull final IAS4IncomingAttachmentFactory aIAF, @Nonnull @WillNotClose final AS4ResourceHelper aResHelper, @Nonnull final IAS4IncomingMessageMetadata aMessageMetadata, @Nonnull @WillClose final InputStream aPayloadIS, @Nonnull final HttpHeaderMap aHttpHeaders, @Nonnull final IAS4ParsedMessageCallback aCallback, @Nullable final IAS4IncomingDumper aIncomingDumper) throws Phase4Exception, IOException, MessagingException, WSSecurityException {
    // Determine content type
    final String sContentType = aHttpHeaders.getFirstHeaderValue(CHttpHeader.CONTENT_TYPE);
    if (StringHelper.hasNoText(sContentType))
        throw new Phase4Exception("Content-Type header is missing");
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Received Content-Type string: '" + sContentType + "'");
    final IMimeType aContentType = MimeTypeParser.safeParseMimeType(sContentType);
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Received Content-Type object: " + aContentType);
    if (aContentType == null)
        throw new Phase4Exception("Failed to parse Content-Type '" + sContentType + "'");
    final IMimeType aPlainContentType = aContentType.getCopyWithoutParameters();
    // Fallback to global dumper if none is provided
    final IAS4IncomingDumper aRealIncomingDumper = aIncomingDumper != null ? aIncomingDumper : AS4DumpManager.getIncomingDumper();
    Document aSoapDocument = null;
    ESoapVersion eSoapVersion = null;
    final ICommonsList<WSS4JAttachment> aIncomingAttachments = new CommonsArrayList<>();
    final Wrapper<OutputStream> aDumpOSHolder = new Wrapper<>();
    if (aPlainContentType.equals(AS4RequestHandler.MT_MULTIPART_RELATED)) {
        // MIME message
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Received MIME message");
        final String sBoundary = aContentType.getParameterValueWithName("boundary");
        if (StringHelper.hasNoText(sBoundary))
            throw new Phase4Exception("Content-Type '" + sContentType + "' misses 'boundary' parameter");
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("MIME Boundary: '" + sBoundary + "'");
        // Ensure the stream gets closed correctly
        try (final InputStream aRequestIS = AS4DumpManager.getIncomingDumpAwareInputStream(aRealIncomingDumper, aPayloadIS, aMessageMetadata, aHttpHeaders, aDumpOSHolder)) {
            // PARSING MIME Message via MultipartStream
            final MultipartStream aMulti = new MultipartStream(aRequestIS, sBoundary.getBytes(StandardCharsets.ISO_8859_1), (MultipartProgressNotifier) null);
            int nIndex = 0;
            while (true) {
                final boolean bHasNextPart = nIndex == 0 ? aMulti.skipPreamble() : aMulti.readBoundary();
                if (!bHasNextPart)
                    break;
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("Found MIME part #" + nIndex);
                try (final MultipartItemInputStream aBodyPartIS = aMulti.createInputStream()) {
                    // Read headers AND content
                    final MimeBodyPart aBodyPart = new MimeBodyPart(aBodyPartIS);
                    if (nIndex == 0) {
                        // First MIME part -> SOAP document
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug("Parsing first MIME part as SOAP document");
                        // Read SOAP document
                        aSoapDocument = DOMReader.readXMLDOM(aBodyPart.getInputStream());
                        IMimeType aPlainPartMT = MimeTypeParser.safeParseMimeType(aBodyPart.getContentType());
                        if (aPlainPartMT != null)
                            aPlainPartMT = aPlainPartMT.getCopyWithoutParameters();
                        // Determine SOAP version from MIME part content type
                        eSoapVersion = ESoapVersion.getFromMimeTypeOrNull(aPlainPartMT);
                        if (eSoapVersion != null && LOGGER.isDebugEnabled())
                            LOGGER.debug("Determined SOAP version " + eSoapVersion + " from Content-Type");
                        if (eSoapVersion == null && aSoapDocument != null) {
                            // Determine SOAP version from the read document
                            eSoapVersion = ESoapVersion.getFromNamespaceURIOrNull(XMLHelper.getNamespaceURI(aSoapDocument));
                            if (eSoapVersion != null && LOGGER.isDebugEnabled())
                                LOGGER.debug("Determined SOAP version " + eSoapVersion + " from XML root element namespace URI");
                        }
                    } else {
                        // MIME Attachment (index is gt 0)
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug("Parsing MIME part #" + nIndex + " as attachment");
                        final WSS4JAttachment aAttachment = aIAF.createAttachment(aBodyPart, aResHelper);
                        aIncomingAttachments.add(aAttachment);
                    }
                }
                nIndex++;
            }
        }
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Read MIME message with " + aIncomingAttachments.size() + " attachment(s)");
    } else {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Received plain message");
        // Expect plain SOAP - read whole request to DOM
        // Note: this may require a huge amount of memory for large requests
        aSoapDocument = DOMReader.readXMLDOM(AS4DumpManager.getIncomingDumpAwareInputStream(aRealIncomingDumper, aPayloadIS, aMessageMetadata, aHttpHeaders, aDumpOSHolder));
        if (LOGGER.isDebugEnabled())
            if (aSoapDocument != null)
                LOGGER.debug("Successfully parsed payload as XML");
            else
                LOGGER.debug("Failed to parse payload as XML");
        if (aSoapDocument != null) {
            // Determine SOAP version from the read document
            eSoapVersion = ESoapVersion.getFromNamespaceURIOrNull(XMLHelper.getNamespaceURI(aSoapDocument));
            if (eSoapVersion != null && LOGGER.isDebugEnabled())
                LOGGER.debug("Determined SOAP version " + eSoapVersion + " from XML root element namespace URI");
        }
        if (eSoapVersion == null) {
            // Determine SOAP version from content type
            eSoapVersion = ESoapVersion.getFromMimeTypeOrNull(aPlainContentType);
            if (eSoapVersion != null && LOGGER.isDebugEnabled())
                LOGGER.debug("Determined SOAP version " + eSoapVersion + " from Content-Type");
        }
    }
    try {
        if (aSoapDocument == null) {
            // We don't have a SOAP document
            throw new Phase4Exception(eSoapVersion == null ? "Failed to parse incoming message!" : "Failed to parse incoming SOAP " + eSoapVersion.getVersion() + " document!");
        }
        if (eSoapVersion == null) {
            // We're missing a SOAP version
            throw new Phase4Exception("Failed to determine SOAP version of XML document!");
        }
        aCallback.handle(aHttpHeaders, aSoapDocument, eSoapVersion, aIncomingAttachments);
    } finally {
        // Here, the incoming dump is finally ready closed and usable
        if (aRealIncomingDumper != null && aDumpOSHolder.isSet())
            try {
                aRealIncomingDumper.onEndRequest(aMessageMetadata);
            } catch (final Exception ex) {
                LOGGER.error("IncomingDumper.onEndRequest failed. Dumper=" + aRealIncomingDumper + "; MessageMetadata=" + aMessageMetadata, ex);
            }
    }
}
Also used : Wrapper(com.helger.commons.wrapper.Wrapper) IAS4IncomingDumper(com.helger.phase4.dump.IAS4IncomingDumper) MultipartItemInputStream(com.helger.web.multipart.MultipartStream.MultipartItemInputStream) NonBlockingByteArrayInputStream(com.helger.commons.io.stream.NonBlockingByteArrayInputStream) HasInputStream(com.helger.commons.io.stream.HasInputStream) IHasInputStream(com.helger.commons.io.IHasInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Document(org.w3c.dom.Document) 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) Phase4Exception(com.helger.phase4.util.Phase4Exception) IMimeType(com.helger.commons.mime.IMimeType) MultipartItemInputStream(com.helger.web.multipart.MultipartStream.MultipartItemInputStream) ESoapVersion(com.helger.phase4.soap.ESoapVersion) MimeBodyPart(javax.mail.internet.MimeBodyPart) MultipartStream(com.helger.web.multipart.MultipartStream) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment)

Example 7 with AS4ResourceHelper

use of com.helger.phase4.util.AS4ResourceHelper in project phase4 by phax.

the class MockMessages method createErrorMessageSigned.

@Nonnull
public static Document createErrorMessageSigned(@Nonnull final ESoapVersion eSOAPVersion, @Nullable final ICommonsList<WSS4JAttachment> aAttachments, @Nonnull final AS4ResourceHelper aResMgr) throws WSSecurityException {
    final ICommonsList<Ebms3Error> aEbms3ErrorList = new CommonsArrayList<>(EEbmsError.EBMS_INVALID_HEADER.getAsEbms3Error(Locale.US, null));
    final AS4ErrorMessage aErrorMsg = AS4ErrorMessage.create(eSOAPVersion, "srcmsgid", aEbms3ErrorList).setMustUnderstand(true);
    return AS4Signer.createSignedMessage(AS4CryptoFactoryProperties.getDefaultInstance(), aErrorMsg.getAsSoapDocument(), eSOAPVersion, aErrorMsg.getMessagingID(), aAttachments, aResMgr, false, AS4SigningParams.createDefault());
}
Also used : Ebms3Error(com.helger.phase4.ebms3header.Ebms3Error) CommonsArrayList(com.helger.commons.collection.impl.CommonsArrayList) AS4ErrorMessage(com.helger.phase4.messaging.domain.AS4ErrorMessage) Nonnull(javax.annotation.Nonnull)

Example 8 with AS4ResourceHelper

use of com.helger.phase4.util.AS4ResourceHelper in project phase4 by phax.

the class AbstractAS4PullRequestBuilder method mainSendMessage.

@Override
protected final void mainSendMessage() throws Phase4Exception {
    // Temporary file manager
    try (final AS4ResourceHelper aResHelper = new AS4ResourceHelper()) {
        // Start building AS4 User Message
        final AS4ClientPullRequestMessage aPullRequestMsg = new AS4ClientPullRequestMessage(aResHelper);
        applyToPullRequest(aPullRequestMsg);
        // Main sending
        AS4BidirectionalClientHelper.sendAS4PullRequestAndReceiveAS4UserMessage(m_aCryptoFactory, pmodeResolver(), incomingAttachmentFactory(), incomingProfileSelector(), aPullRequestMsg, m_aLocale, m_sEndpointURL, m_aBuildMessageCallback, m_aOutgoingDumper, m_aIncomingDumper, m_aRetryCallback, m_aResponseConsumer, m_aUserMsgConsumer);
    } catch (final Phase4Exception ex) {
        // Re-throw
        throw ex;
    } catch (final Exception ex) {
        // wrap
        throw new Phase4Exception("Wrapped Phase4Exception", ex);
    }
}
Also used : Phase4Exception(com.helger.phase4.util.Phase4Exception) AS4ClientPullRequestMessage(com.helger.phase4.client.AS4ClientPullRequestMessage) AS4ResourceHelper(com.helger.phase4.util.AS4ResourceHelper) Phase4Exception(com.helger.phase4.util.Phase4Exception)

Example 9 with AS4ResourceHelper

use of com.helger.phase4.util.AS4ResourceHelper in project phase4 by phax.

the class AbstractAS4UserMessageBuilderMIMEPayload method mainSendMessage.

@Override
protected final void mainSendMessage() throws Phase4Exception {
    // Temporary file manager
    try (final AS4ResourceHelper aResHelper = new AS4ResourceHelper()) {
        // Start building AS4 User Message
        final AS4ClientUserMessage aUserMsg = new AS4ClientUserMessage(aResHelper);
        applyToUserMessage(aUserMsg);
        // No payload - only one attachment
        aUserMsg.setPayload(null);
        // Add main attachment
        aUserMsg.addAttachment(WSS4JAttachment.createOutgoingFileAttachment(m_aPayload, aResHelper));
        // Add other attachments
        for (final Phase4OutgoingAttachment aAttachment : m_aAttachments) aUserMsg.addAttachment(WSS4JAttachment.createOutgoingFileAttachment(aAttachment, aResHelper));
        // Main sending
        AS4BidirectionalClientHelper.sendAS4UserMessageAndReceiveAS4SignalMessage(m_aCryptoFactory, pmodeResolver(), incomingAttachmentFactory(), incomingProfileSelector(), aUserMsg, m_aLocale, m_sEndpointURL, m_aBuildMessageCallback, m_aOutgoingDumper, m_aIncomingDumper, m_aRetryCallback, m_aResponseConsumer, m_aSignalMsgConsumer);
    } catch (final Phase4Exception ex) {
        // Re-throw
        throw ex;
    } catch (final Exception ex) {
        // wrap
        throw new Phase4Exception("Wrapped Phase4Exception", ex);
    }
}
Also used : Phase4Exception(com.helger.phase4.util.Phase4Exception) Phase4OutgoingAttachment(com.helger.phase4.attachment.Phase4OutgoingAttachment) AS4ClientUserMessage(com.helger.phase4.client.AS4ClientUserMessage) AS4ResourceHelper(com.helger.phase4.util.AS4ResourceHelper) Phase4Exception(com.helger.phase4.util.Phase4Exception)

Example 10 with AS4ResourceHelper

use of com.helger.phase4.util.AS4ResourceHelper 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)

Aggregations

Nonnull (javax.annotation.Nonnull)9 Document (org.w3c.dom.Document)9 AS4ResourceHelper (com.helger.phase4.util.AS4ResourceHelper)7 WSS4JAttachment (com.helger.phase4.attachment.WSS4JAttachment)6 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)5 Phase4Exception (com.helger.phase4.util.Phase4Exception)5 IOException (java.io.IOException)5 Ebms3Error (com.helger.phase4.ebms3header.Ebms3Error)4 File (java.io.File)4 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)4 ErrorList (com.helger.commons.error.list.ErrorList)3 WSS4JAttachmentCallbackHandler (com.helger.phase4.attachment.WSS4JAttachmentCallbackHandler)3 Ebms3UserMessage (com.helger.phase4.ebms3header.Ebms3UserMessage)3 Nullable (javax.annotation.Nullable)3 IHasInputStream (com.helger.commons.io.IHasInputStream)2 HasInputStream (com.helger.commons.io.stream.HasInputStream)2 NonBlockingByteArrayInputStream (com.helger.commons.io.stream.NonBlockingByteArrayInputStream)2 IMimeType (com.helger.commons.mime.IMimeType)2 AS4ClientUserMessage (com.helger.phase4.client.AS4ClientUserMessage)2 Ebms3PullRequest (com.helger.phase4.ebms3header.Ebms3PullRequest)2