Search in sources :

Example 21 with HttpHeaderMap

use of com.helger.commons.http.HttpHeaderMap 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 22 with HttpHeaderMap

use of com.helger.commons.http.HttpHeaderMap in project phase4 by phax.

the class AS4DumpReader method decryptAS4In.

/**
 * Utility method to decrypt dumped .as4in message late.<br>
 * Note: this method was mainly created for internal use and does not win the
 * prize for the most sexy piece of software in the world ;-)
 *
 * @param aAS4InData
 *        The byte array with the dumped data.
 * @param aCF
 *        The Crypto factory to be used. This crypto factory must use use the
 *        private key that can be used to decrypt this particular message. May
 *        not be <code>null</code>.
 * @param aHttpHeaderConsumer
 *        An optional HTTP Header map consumer. May be <code>null</code>.
 * @param aDecryptedConsumer
 *        The consumer for the decrypted payload - whatever that is :). May
 *        not be <code>null</code>.
 * @throws WSSecurityException
 *         In case of error
 * @throws Phase4Exception
 *         In case of error
 * @throws IOException
 *         In case of error
 * @throws MessagingException
 *         In case of error
 */
public static void decryptAS4In(@Nonnull final byte[] aAS4InData, final IAS4CryptoFactory aCF, @Nullable final Consumer<HttpHeaderMap> aHttpHeaderConsumer, @Nonnull final Consumer<byte[]> aDecryptedConsumer) throws WSSecurityException, Phase4Exception, IOException, MessagingException {
    final HttpHeaderMap hm = new HttpHeaderMap();
    int nHttpStart = 0;
    int nHttpEnd = -1;
    boolean bLastWasCR = false;
    for (int i = 0; i < aAS4InData.length; ++i) {
        final byte b = aAS4InData[i];
        if (b == '\n') {
            if (bLastWasCR) {
                nHttpEnd = i;
                break;
            }
            bLastWasCR = true;
            final String sLine = new String(aAS4InData, nHttpStart, i - nHttpStart, StandardCharsets.ISO_8859_1);
            final String[] aParts = StringHelper.getExplodedArray(':', sLine, 2);
            hm.addHeader(aParts[0].trim(), aParts[1].trim());
            nHttpStart = i + 1;
        } else {
            if (b != '\r')
                bLastWasCR = false;
        }
    }
    if (aHttpHeaderConsumer != null)
        aHttpHeaderConsumer.accept(hm);
    LOGGER.info("Now at byte " + nHttpEnd + " having " + hm.getCount() + " HTTP headers");
    WebScopeManager.onGlobalBegin(MockServletContext.create());
    try (final WebScoped w = new WebScoped();
        final AS4RequestHandler rh = new AS4RequestHandler(aCF, DefaultPModeResolver.DEFAULT_PMODE_RESOLVER, IAS4IncomingAttachmentFactory.DEFAULT_INSTANCE, new AS4IncomingMessageMetadata(EAS4MessageMode.REQUEST))) {
        final IAS4ServletMessageProcessorSPI aSPI = new IAS4ServletMessageProcessorSPI() {

            public AS4MessageProcessorResult processAS4UserMessage(final IAS4IncomingMessageMetadata aMessageMetadata, final HttpHeaderMap aHttpHeaders, final Ebms3UserMessage aUserMessage, final IPMode aPMode, final Node aPayload, final ICommonsList<WSS4JAttachment> aIncomingAttachments, final IAS4MessageState aState, final ICommonsList<Ebms3Error> aProcessingErrorMessages) {
                try {
                    final byte[] aDecryptedBytes = StreamHelper.getAllBytes(aIncomingAttachments.getFirst().getInputStreamProvider());
                    aDecryptedConsumer.accept(aDecryptedBytes);
                    LOGGER.info("Handled decrypted payload with " + aDecryptedBytes.length + " bytes");
                    return AS4MessageProcessorResult.createSuccess();
                } catch (final Exception ex) {
                    throw new IllegalStateException(ex);
                }
            }

            public AS4SignalMessageProcessorResult processAS4SignalMessage(final IAS4IncomingMessageMetadata aMessageMetadata, final HttpHeaderMap aHttpHeaders, final Ebms3SignalMessage aSignalMessage, final IPMode aPMode, final IAS4MessageState aState, final ICommonsList<Ebms3Error> aProcessingErrorMessages) {
                LOGGER.error("Unexpected signal msg");
                return AS4SignalMessageProcessorResult.createSuccess();
            }
        };
        rh.setProcessorSupplier(() -> new CommonsArrayList<>(aSPI));
        rh.handleRequest(new NonBlockingByteArrayInputStream(aAS4InData, nHttpEnd, aAS4InData.length - nHttpEnd), hm, new IAS4ResponseAbstraction() {

            public void setStatus(final int nStatusCode) {
            }

            public void setMimeType(final IMimeType aMimeType) {
            }

            public void setContent(final HttpHeaderMap aHeaderMap, final IHasInputStream aHasIS) {
            }

            public void setContent(final byte[] aResultBytes, final Charset aCharset) {
            }
        });
    } finally {
        WebScopeManager.onGlobalEnd();
    }
}
Also used : Ebms3SignalMessage(com.helger.phase4.ebms3header.Ebms3SignalMessage) ICommonsList(com.helger.commons.collection.impl.ICommonsList) Node(org.w3c.dom.Node) IHasInputStream(com.helger.commons.io.IHasInputStream) IAS4ServletMessageProcessorSPI(com.helger.phase4.servlet.spi.IAS4ServletMessageProcessorSPI) IAS4MessageState(com.helger.phase4.servlet.IAS4MessageState) IAS4IncomingMessageMetadata(com.helger.phase4.messaging.IAS4IncomingMessageMetadata) NonBlockingByteArrayInputStream(com.helger.commons.io.stream.NonBlockingByteArrayInputStream) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) IAS4ResponseAbstraction(com.helger.phase4.servlet.IAS4ResponseAbstraction) IMimeType(com.helger.commons.mime.IMimeType) WebScoped(com.helger.web.scope.mgr.WebScoped) IAS4IncomingMessageMetadata(com.helger.phase4.messaging.IAS4IncomingMessageMetadata) AS4IncomingMessageMetadata(com.helger.phase4.servlet.AS4IncomingMessageMetadata) Charset(java.nio.charset.Charset) MessagingException(javax.mail.MessagingException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Phase4Exception(com.helger.phase4.util.Phase4Exception) IOException(java.io.IOException) AS4RequestHandler(com.helger.phase4.servlet.AS4RequestHandler) IPMode(com.helger.phase4.model.pmode.IPMode) Ebms3UserMessage(com.helger.phase4.ebms3header.Ebms3UserMessage)

Aggregations

HttpHeaderMap (com.helger.commons.http.HttpHeaderMap)22 Nonnull (javax.annotation.Nonnull)7 ICommonsList (com.helger.commons.collection.impl.ICommonsList)5 IOException (java.io.IOException)5 Nullable (javax.annotation.Nullable)5 MessagingException (javax.mail.MessagingException)5 IMessageMDN (com.helger.as2lib.message.IMessageMDN)4 Ebms3SignalMessage (com.helger.phase4.ebms3header.Ebms3SignalMessage)4 Ebms3UserMessage (com.helger.phase4.ebms3header.Ebms3UserMessage)4 IPMode (com.helger.phase4.model.pmode.IPMode)4 Phase4Exception (com.helger.phase4.util.Phase4Exception)4 MimeBodyPart (javax.mail.internet.MimeBodyPart)4 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)4 Test (org.junit.Test)4 Node (org.w3c.dom.Node)4 ValueEnforcer (com.helger.commons.ValueEnforcer)3 ReturnsMutableCopy (com.helger.commons.annotation.ReturnsMutableCopy)3 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)3 IHasInputStream (com.helger.commons.io.IHasInputStream)3 NonBlockingByteArrayOutputStream (com.helger.commons.io.stream.NonBlockingByteArrayOutputStream)3