Search in sources :

Example 1 with AS4ClientSentMessage

use of com.helger.phase4.client.AS4ClientSentMessage in project phase4 by phax.

the class AbstractAS4Client method sendMessageWithRetries.

/**
 * Send the AS4 client message created by
 * {@link #buildMessage(String, IAS4ClientBuildMessageCallback)} to the
 * provided URL. This methods does take retries into account. It synchronously
 * handles the retries and only returns after the last retry.
 *
 * @param <T>
 *        The response data type
 * @param sURL
 *        The URL to send the HTTP POST to
 * @param aResponseHandler
 *        The response handler that converts the HTTP response to a domain
 *        object. May not be <code>null</code>.
 * @param aCallback
 *        An optional callback for the different stages of building the
 *        document. May be <code>null</code>.
 * @param aOutgoingDumper
 *        An outgoing dumper to be used. Maybe <code>null</code>. If
 *        <code>null</code> the global outgoing dumper from
 *        {@link AS4DumpManager} is used.
 * @param aRetryCallback
 *        An optional callback to be invoked if a retry happens on HTTP level.
 *        May be <code>null</code>.
 * @return The sent message that contains
 * @throws IOException
 *         in case of error when building or sending the message
 * @throws WSSecurityException
 *         In case there is an issue with signing/encryption
 * @throws MessagingException
 *         in case something happens in MIME wrapping
 * @since 0.9.14
 */
@Nonnull
public final <T> AS4ClientSentMessage<T> sendMessageWithRetries(@Nonnull final String sURL, @Nonnull final ResponseHandler<? extends T> aResponseHandler, @Nullable final IAS4ClientBuildMessageCallback aCallback, @Nullable final IAS4OutgoingDumper aOutgoingDumper, @Nullable final IAS4RetryCallback aRetryCallback) throws IOException, WSSecurityException, MessagingException {
    // Create a new message ID for each build!
    final String sMessageID = createMessageID();
    final AS4ClientBuiltMessage aBuiltMsg = buildMessage(sMessageID, aCallback);
    HttpEntity aBuiltEntity = aBuiltMsg.getHttpEntity();
    final HttpHeaderMap aBuiltHttpHeaders = aBuiltMsg.getCustomHeaders();
    if (m_aHttpRetrySettings.isRetryEnabled() || aOutgoingDumper != null || AS4DumpManager.getOutgoingDumper() != null) {
        // Ensure a repeatable entity is provided
        aBuiltEntity = m_aResHelper.createRepeatableHttpEntity(aBuiltEntity);
    }
    // Keep the HTTP response status line for external evaluation
    final Wrapper<StatusLine> aStatusLineKeeper = new Wrapper<>();
    // Keep the HTTP response headers for external evaluation
    final HttpHeaderMap aResponseHeaders = new HttpHeaderMap();
    final ResponseHandler<T> aRealResponseHandler = x -> {
        // Remember the HTTP response data
        aStatusLineKeeper.set(x.getStatusLine());
        final Header[] aHeaders = x.getAllHeaders();
        if (aHeaders != null)
            for (final Header aHeader : aHeaders) aResponseHeaders.addHeader(aHeader.getName(), aHeader.getValue());
        // Call the original handler
        return aResponseHandler.handleResponse(x);
    };
    final T aResponseContent = m_aHttpPoster.sendGenericMessageWithRetries(sURL, aBuiltHttpHeaders, aBuiltEntity, sMessageID, m_aHttpRetrySettings, aRealResponseHandler, aOutgoingDumper, aRetryCallback);
    return new AS4ClientSentMessage<>(aBuiltMsg, aStatusLineKeeper.get(), aResponseHeaders, aResponseContent);
}
Also used : StatusLine(org.apache.http.StatusLine) BasicHttpPoster(com.helger.phase4.http.BasicHttpPoster) IGenericImplTrait(com.helger.commons.traits.IGenericImplTrait) MessageHelperMethods(com.helger.phase4.messaging.domain.MessageHelperMethods) PModeReceptionAwareness(com.helger.phase4.model.pmode.PModeReceptionAwareness) ESoapVersion(com.helger.phase4.soap.ESoapVersion) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) AS4HttpDebug(com.helger.phase4.http.AS4HttpDebug) MessagingException(javax.mail.MessagingException) MetaAS4Manager(com.helger.phase4.mgr.MetaAS4Manager) IMicroDocument(com.helger.xml.microdom.IMicroDocument) IAS4CryptoFactory(com.helger.phase4.crypto.IAS4CryptoFactory) Supplier(java.util.function.Supplier) Header(org.apache.http.Header) StatusLine(org.apache.http.StatusLine) AS4CryptParams(com.helger.phase4.crypto.AS4CryptParams) EAS4MessageType(com.helger.phase4.messaging.domain.EAS4MessageType) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Nonempty(com.helger.commons.annotation.Nonempty) IHttpPoster(com.helger.phase4.http.IHttpPoster) Duration(java.time.Duration) AS4ResourceHelper(com.helger.phase4.util.AS4ResourceHelper) PModeLeg(com.helger.phase4.model.pmode.leg.PModeLeg) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) IAS4OutgoingDumper(com.helger.phase4.dump.IAS4OutgoingDumper) WillNotClose(javax.annotation.WillNotClose) AS4SigningParams(com.helger.phase4.crypto.AS4SigningParams) IPMode(com.helger.phase4.model.pmode.IPMode) StringHelper(com.helger.commons.string.StringHelper) HttpEntity(org.apache.http.HttpEntity) IOException(java.io.IOException) ResponseHandlerMicroDom(com.helger.httpclient.response.ResponseHandlerMicroDom) ValueEnforcer(com.helger.commons.ValueEnforcer) AS4DumpManager(com.helger.phase4.dump.AS4DumpManager) HttpRetrySettings(com.helger.phase4.http.HttpRetrySettings) MicroWriter(com.helger.xml.microdom.serialize.MicroWriter) OffsetDateTime(java.time.OffsetDateTime) Wrapper(com.helger.commons.wrapper.Wrapper) ReturnsMutableObject(com.helger.commons.annotation.ReturnsMutableObject) ResponseHandler(org.apache.http.client.ResponseHandler) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) Wrapper(com.helger.commons.wrapper.Wrapper) HttpEntity(org.apache.http.HttpEntity) Header(org.apache.http.Header) Nonnull(javax.annotation.Nonnull)

Example 2 with AS4ClientSentMessage

use of com.helger.phase4.client.AS4ClientSentMessage in project phase4 by phax.

the class AS4BidirectionalClientHelper method sendAS4PullRequestAndReceiveAS4UserMessage.

public static void sendAS4PullRequestAndReceiveAS4UserMessage(@Nonnull final IAS4CryptoFactory aCryptoFactory, @Nonnull final IPModeResolver aPModeResolver, @Nonnull final IAS4IncomingAttachmentFactory aIAF, @Nonnull final IAS4IncomingProfileSelector aIncomingProfileSelector, @Nonnull final AS4ClientPullRequestMessage aClientPullRequest, @Nonnull final Locale aLocale, @Nonnull final String sURL, @Nullable final IAS4ClientBuildMessageCallback aBuildMessageCallback, @Nullable final IAS4OutgoingDumper aOutgoingDumper, @Nullable final IAS4IncomingDumper aIncomingDumper, @Nullable final IAS4RetryCallback aRetryCallback, @Nullable final IAS4RawResponseConsumer aResponseConsumer, @Nullable final IAS4UserMessageConsumer aUserMsgConsumer) throws IOException, Phase4Exception, WSSecurityException, MessagingException {
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Sending AS4 PullRequest to '" + sURL + "' with max. " + aClientPullRequest.httpRetrySettings().getMaxRetries() + " retries");
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("  MPC = '" + aClientPullRequest.getMPC() + "'");
    final Wrapper<HttpResponse> aWrappedResponse = new Wrapper<>();
    final ResponseHandler<byte[]> aResponseHdl = aHttpResponse -> {
        // May throw an ExtendedHttpResponseException
        final HttpEntity aEntity = ResponseHandlerHttpEntity.INSTANCE.handleResponse(aHttpResponse);
        if (aEntity == null)
            return null;
        aWrappedResponse.set(aHttpResponse);
        return EntityUtils.toByteArray(aEntity);
    };
    final AS4ClientSentMessage<byte[]> aResponseEntity = aClientPullRequest.sendMessageWithRetries(sURL, aResponseHdl, aBuildMessageCallback, aOutgoingDumper, aRetryCallback);
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Successfully transmitted AS4 PullRequest with message ID '" + aResponseEntity.getMessageID() + "' to '" + sURL + "'");
    if (aResponseConsumer != null)
        aResponseConsumer.handleResponse(aResponseEntity);
    // Try interpret result as SignalMessage
    if (aResponseEntity.hasResponse() && aResponseEntity.getResponse().length > 0) {
        final IAS4IncomingMessageMetadata aMessageMetadata = new AS4IncomingMessageMetadata(EAS4MessageMode.RESPONSE).setRemoteAddr(sURL);
        // Read response as EBMS3 User Message
        // Read it in any case to ensure signature validation etc. happens
        final Ebms3UserMessage aUserMessage = AS4IncomingHandler.parseUserMessage(aCryptoFactory, aPModeResolver, aIAF, aIncomingProfileSelector, aClientPullRequest.getAS4ResourceHelper(), null, aLocale, aMessageMetadata, aWrappedResponse.get(), aResponseEntity.getResponse(), aIncomingDumper);
        if (aUserMessage != null && aUserMsgConsumer != null)
            aUserMsgConsumer.handleUserMessage(aUserMessage);
    } else
        LOGGER.info("AS4 ResponseEntity is empty");
}
Also used : Ebms3SignalMessage(com.helger.phase4.ebms3header.Ebms3SignalMessage) IAS4SignalMessageConsumer(com.helger.phase4.client.IAS4SignalMessageConsumer) IAS4RawResponseConsumer(com.helger.phase4.client.IAS4RawResponseConsumer) LoggerFactory(org.slf4j.LoggerFactory) MessagingException(javax.mail.MessagingException) IAS4CryptoFactory(com.helger.phase4.crypto.IAS4CryptoFactory) ResponseHandlerHttpEntity(com.helger.httpclient.response.ResponseHandlerHttpEntity) EntityUtils(org.apache.http.util.EntityUtils) IAS4IncomingProfileSelector(com.helger.phase4.servlet.IAS4IncomingProfileSelector) EAS4MessageMode(com.helger.phase4.messaging.EAS4MessageMode) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Locale(java.util.Locale) IAS4IncomingDumper(com.helger.phase4.dump.IAS4IncomingDumper) IAS4IncomingMessageMetadata(com.helger.phase4.messaging.IAS4IncomingMessageMetadata) IAS4RetryCallback(com.helger.phase4.client.IAS4RetryCallback) Nonnull(javax.annotation.Nonnull) IAS4IncomingAttachmentFactory(com.helger.phase4.attachment.IAS4IncomingAttachmentFactory) Phase4Exception(com.helger.phase4.util.Phase4Exception) Nullable(javax.annotation.Nullable) IAS4OutgoingDumper(com.helger.phase4.dump.IAS4OutgoingDumper) Ebms3Property(com.helger.phase4.ebms3header.Ebms3Property) AS4ClientPullRequestMessage(com.helger.phase4.client.AS4ClientPullRequestMessage) Ebms3UserMessage(com.helger.phase4.ebms3header.Ebms3UserMessage) Logger(org.slf4j.Logger) AS4IncomingMessageMetadata(com.helger.phase4.servlet.AS4IncomingMessageMetadata) IPModeResolver(com.helger.phase4.model.pmode.resolve.IPModeResolver) AS4ClientSentMessage(com.helger.phase4.client.AS4ClientSentMessage) HttpEntity(org.apache.http.HttpEntity) IOException(java.io.IOException) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment) IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) AS4IncomingHandler(com.helger.phase4.servlet.AS4IncomingHandler) Wrapper(com.helger.commons.wrapper.Wrapper) AS4ClientUserMessage(com.helger.phase4.client.AS4ClientUserMessage) HttpResponse(org.apache.http.HttpResponse) IAS4UserMessageConsumer(com.helger.phase4.client.IAS4UserMessageConsumer) ResponseHandler(org.apache.http.client.ResponseHandler) IAS4IncomingMessageMetadata(com.helger.phase4.messaging.IAS4IncomingMessageMetadata) Wrapper(com.helger.commons.wrapper.Wrapper) ResponseHandlerHttpEntity(com.helger.httpclient.response.ResponseHandlerHttpEntity) HttpEntity(org.apache.http.HttpEntity) IAS4IncomingMessageMetadata(com.helger.phase4.messaging.IAS4IncomingMessageMetadata) AS4IncomingMessageMetadata(com.helger.phase4.servlet.AS4IncomingMessageMetadata) Ebms3UserMessage(com.helger.phase4.ebms3header.Ebms3UserMessage) HttpResponse(org.apache.http.HttpResponse)

Example 3 with AS4ClientSentMessage

use of com.helger.phase4.client.AS4ClientSentMessage in project phase4 by phax.

the class AS4BidirectionalClientHelper method sendAS4UserMessageAndReceiveAS4SignalMessage.

public static void sendAS4UserMessageAndReceiveAS4SignalMessage(@Nonnull final IAS4CryptoFactory aCryptoFactory, @Nonnull final IPModeResolver aPModeResolver, @Nonnull final IAS4IncomingAttachmentFactory aIAF, @Nonnull final IAS4IncomingProfileSelector aIncomingProfileSelector, @Nonnull final AS4ClientUserMessage aClientUserMsg, @Nonnull final Locale aLocale, @Nonnull final String sURL, @Nullable final IAS4ClientBuildMessageCallback aBuildMessageCallback, @Nullable final IAS4OutgoingDumper aOutgoingDumper, @Nullable final IAS4IncomingDumper aIncomingDumper, @Nullable final IAS4RetryCallback aRetryCallback, @Nullable final IAS4RawResponseConsumer aResponseConsumer, @Nullable final IAS4SignalMessageConsumer aSignalMsgConsumer) throws IOException, Phase4Exception, WSSecurityException, MessagingException {
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Sending AS4 UserMessage to '" + sURL + "' with max. " + aClientUserMsg.httpRetrySettings().getMaxRetries() + " retries");
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("  ServiceType = '" + aClientUserMsg.getServiceType() + "'");
        LOGGER.debug("  Service = '" + aClientUserMsg.getServiceValue() + "'");
        LOGGER.debug("  Action = '" + aClientUserMsg.getAction() + "'");
        LOGGER.debug("  ConversationId = '" + aClientUserMsg.getConversationID() + "'");
        LOGGER.debug("  MessageProperties:");
        for (final Ebms3Property p : aClientUserMsg.ebms3Properties()) LOGGER.debug("    [" + p.getName() + "] = [" + p.getValue() + "]");
        LOGGER.debug("  Attachments (" + aClientUserMsg.attachments().size() + "):");
        for (final WSS4JAttachment a : aClientUserMsg.attachments()) {
            LOGGER.debug("    [" + a.getId() + "] with [" + a.getMimeType() + "] and [" + a.getCharsetOrDefault(null) + "] and [" + a.getCompressionMode() + "] and [" + a.getContentTransferEncoding() + "]");
        }
    }
    final Wrapper<HttpResponse> aWrappedResponse = new Wrapper<>();
    final ResponseHandler<byte[]> aResponseHdl = aHttpResponse -> {
        // throws an ExtendedHttpResponseException on exception
        final HttpEntity aEntity = ResponseHandlerHttpEntity.INSTANCE.handleResponse(aHttpResponse);
        if (aEntity == null)
            return null;
        aWrappedResponse.set(aHttpResponse);
        return EntityUtils.toByteArray(aEntity);
    };
    final AS4ClientSentMessage<byte[]> aResponseEntity = aClientUserMsg.sendMessageWithRetries(sURL, aResponseHdl, aBuildMessageCallback, aOutgoingDumper, aRetryCallback);
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Successfully transmitted AS4 UserMessage with message ID '" + aResponseEntity.getMessageID() + "' to '" + sURL + "'");
    if (aResponseConsumer != null)
        aResponseConsumer.handleResponse(aResponseEntity);
    // Try interpret result as SignalMessage
    if (aResponseEntity.hasResponse() && aResponseEntity.getResponse().length > 0) {
        final IAS4IncomingMessageMetadata aMessageMetadata = new AS4IncomingMessageMetadata(EAS4MessageMode.RESPONSE).setRemoteAddr(sURL);
        // Read response as EBMS3 Signal Message
        // Read it in any case to ensure signature validation etc. happens
        final Ebms3SignalMessage aSignalMessage = AS4IncomingHandler.parseSignalMessage(aCryptoFactory, aPModeResolver, aIAF, aIncomingProfileSelector, aClientUserMsg.getAS4ResourceHelper(), aClientUserMsg.getPMode(), aLocale, aMessageMetadata, aWrappedResponse.get(), aResponseEntity.getResponse(), aIncomingDumper);
        if (aSignalMessage != null && aSignalMsgConsumer != null)
            aSignalMsgConsumer.handleSignalMessage(aSignalMessage);
    } else
        LOGGER.info("AS4 ResponseEntity is empty");
}
Also used : Ebms3SignalMessage(com.helger.phase4.ebms3header.Ebms3SignalMessage) IAS4SignalMessageConsumer(com.helger.phase4.client.IAS4SignalMessageConsumer) IAS4RawResponseConsumer(com.helger.phase4.client.IAS4RawResponseConsumer) LoggerFactory(org.slf4j.LoggerFactory) MessagingException(javax.mail.MessagingException) IAS4CryptoFactory(com.helger.phase4.crypto.IAS4CryptoFactory) ResponseHandlerHttpEntity(com.helger.httpclient.response.ResponseHandlerHttpEntity) EntityUtils(org.apache.http.util.EntityUtils) IAS4IncomingProfileSelector(com.helger.phase4.servlet.IAS4IncomingProfileSelector) EAS4MessageMode(com.helger.phase4.messaging.EAS4MessageMode) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Locale(java.util.Locale) IAS4IncomingDumper(com.helger.phase4.dump.IAS4IncomingDumper) IAS4IncomingMessageMetadata(com.helger.phase4.messaging.IAS4IncomingMessageMetadata) IAS4RetryCallback(com.helger.phase4.client.IAS4RetryCallback) Nonnull(javax.annotation.Nonnull) IAS4IncomingAttachmentFactory(com.helger.phase4.attachment.IAS4IncomingAttachmentFactory) Phase4Exception(com.helger.phase4.util.Phase4Exception) Nullable(javax.annotation.Nullable) IAS4OutgoingDumper(com.helger.phase4.dump.IAS4OutgoingDumper) Ebms3Property(com.helger.phase4.ebms3header.Ebms3Property) AS4ClientPullRequestMessage(com.helger.phase4.client.AS4ClientPullRequestMessage) Ebms3UserMessage(com.helger.phase4.ebms3header.Ebms3UserMessage) Logger(org.slf4j.Logger) AS4IncomingMessageMetadata(com.helger.phase4.servlet.AS4IncomingMessageMetadata) IPModeResolver(com.helger.phase4.model.pmode.resolve.IPModeResolver) AS4ClientSentMessage(com.helger.phase4.client.AS4ClientSentMessage) HttpEntity(org.apache.http.HttpEntity) IOException(java.io.IOException) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment) IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) AS4IncomingHandler(com.helger.phase4.servlet.AS4IncomingHandler) Wrapper(com.helger.commons.wrapper.Wrapper) AS4ClientUserMessage(com.helger.phase4.client.AS4ClientUserMessage) HttpResponse(org.apache.http.HttpResponse) IAS4UserMessageConsumer(com.helger.phase4.client.IAS4UserMessageConsumer) ResponseHandler(org.apache.http.client.ResponseHandler) IAS4IncomingMessageMetadata(com.helger.phase4.messaging.IAS4IncomingMessageMetadata) Ebms3SignalMessage(com.helger.phase4.ebms3header.Ebms3SignalMessage) Wrapper(com.helger.commons.wrapper.Wrapper) ResponseHandlerHttpEntity(com.helger.httpclient.response.ResponseHandlerHttpEntity) HttpEntity(org.apache.http.HttpEntity) IAS4IncomingMessageMetadata(com.helger.phase4.messaging.IAS4IncomingMessageMetadata) AS4IncomingMessageMetadata(com.helger.phase4.servlet.AS4IncomingMessageMetadata) HttpResponse(org.apache.http.HttpResponse) Ebms3Property(com.helger.phase4.ebms3header.Ebms3Property) WSS4JAttachment(com.helger.phase4.attachment.WSS4JAttachment)

Example 4 with AS4ClientSentMessage

use of com.helger.phase4.client.AS4ClientSentMessage in project phase4 by phax.

the class AS4RawResponseConsumerWriteToFile method handleResponse.

public void handleResponse(@Nonnull final AS4ClientSentMessage<byte[]> aResponseEntity) throws Phase4Exception {
    final boolean bUseStatusLine = isHandleStatusLine() && aResponseEntity.hasResponseStatusLine();
    final boolean bUseHttpHeaders = isHandleHttpHeaders() && aResponseEntity.getResponseHeaders().isNotEmpty();
    final boolean bUseBody = aResponseEntity.hasResponse() && aResponseEntity.getResponse().length > 0;
    if (bUseStatusLine || bUseHttpHeaders || bUseBody) {
        final String sSentMessageID = aResponseEntity.getMessageID();
        // Use the configured data path as the base
        final File aResponseFile = m_aFileProvider.createFile(sSentMessageID);
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Logging AS4 response to '" + aResponseFile.getAbsolutePath() + "'");
        try (final OutputStream aOS = FileHelper.getBufferedOutputStream(aResponseFile)) {
            if (bUseStatusLine) {
                // Write the status line
                aOS.write(aResponseEntity.getResponseStatusLine().toString().getBytes(CHttp.HTTP_CHARSET));
            }
            if (bUseHttpHeaders) {
                // Write the response headers
                for (final Map.Entry<String, ICommonsList<String>> aEntry : aResponseEntity.getResponseHeaders()) {
                    final String sHeader = aEntry.getKey();
                    for (final String sValue : aEntry.getValue()) {
                        // By default quoting is disabled
                        final boolean bQuoteIfNecessary = false;
                        final String sUnifiedValue = HttpHeaderMap.getUnifiedValue(sValue, bQuoteIfNecessary);
                        aOS.write((sHeader + HttpHeaderMap.SEPARATOR_KEY_VALUE + sUnifiedValue + CHttp.EOL).getBytes(CHttp.HTTP_CHARSET));
                    }
                }
            }
            if ((bUseStatusLine || bUseHttpHeaders) && bUseBody) {
                // Separator line
                aOS.write(CHttp.EOL.getBytes(CHttp.HTTP_CHARSET));
            }
            if (bUseBody) {
                // Write the main content
                aOS.write(aResponseEntity.getResponse());
            }
        } catch (final IOException ex) {
            throw new Phase4Exception("Error writing AS4 response file to '" + aResponseFile.getAbsolutePath() + "'", ex);
        }
    }
}
Also used : ICommonsList(com.helger.commons.collection.impl.ICommonsList) Phase4Exception(com.helger.phase4.util.Phase4Exception) OutputStream(java.io.OutputStream) IOException(java.io.IOException) File(java.io.File) HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) Map(java.util.Map)

Example 5 with AS4ClientSentMessage

use of com.helger.phase4.client.AS4ClientSentMessage in project phase4 by phax.

the class DropFolderUserMessage method _send.

private static void _send(@Nonnull final IAS4CryptoFactory aCF, final Path aSendFile, final Path aIncomingDir) {
    final StopWatch aSW = StopWatch.createdStarted();
    boolean bSuccess = false;
    LOGGER.info("Trying to send " + aSendFile.toString());
    try (final AS4ResourceHelper aResHelper = new AS4ResourceHelper()) {
        // Read generic SBD
        final StandardBusinessDocument aSBD = SBDHReader.standardBusinessDocument().read(Files.newInputStream(aSendFile));
        if (aSBD == null) {
            LOGGER.error("Failed to read " + aSendFile.toString() + " as SBDH document!");
        } else {
            // Extract Peppol specific data
            final PeppolSBDHDocument aSBDH = new PeppolSBDHDocumentReader(IF).extractData(aSBD);
            final ISMPServiceMetadataProvider aSMPClient = new SMPClient(UP, aSBDH.getReceiverAsIdentifier(), ESML.DIGIT_TEST);
            final EndpointType aEndpoint = aSMPClient.getEndpoint(aSBDH.getReceiverAsIdentifier(), aSBDH.getDocumentTypeAsIdentifier(), aSBDH.getProcessAsIdentifier(), ESMPTransportProfile.TRANSPORT_PROFILE_BDXR_AS4);
            if (aEndpoint == null) {
                LOGGER.error("Found no endpoint for:\n  Receiver ID: " + aSBDH.getReceiverAsIdentifier().getURIEncoded() + "\n  Document type ID: " + aSBDH.getDocumentTypeAsIdentifier().getURIEncoded() + "\n  Process ID: " + aSBDH.getProcessAsIdentifier().getURIEncoded());
            } else {
                final KeyStore.PrivateKeyEntry aOurCert = aCF.getPrivateKeyEntry();
                final X509Certificate aTheirCert = CertificateHelper.convertStringToCertficate(aEndpoint.getCertificate());
                final AS4ClientUserMessage aClient = new AS4ClientUserMessage(aResHelper);
                aClient.setSoapVersion(ESoapVersion.SOAP_12);
                // Keystore data
                aClient.setAS4CryptoFactory(aCF);
                aClient.signingParams().setAlgorithmSign(ECryptoAlgorithmSign.RSA_SHA_512);
                aClient.signingParams().setAlgorithmSignDigest(ECryptoAlgorithmSignDigest.DIGEST_SHA_512);
                // FIXME Action, Service etc. are missing
                aClient.setAction("xxx");
                aClient.setServiceType("xxx");
                aClient.setServiceValue("xxx");
                aClient.setConversationID(MessageHelperMethods.createRandomConversationID());
                aClient.setAgreementRefValue("xxx");
                aClient.setFromRole(CAS4.DEFAULT_ROLE);
                aClient.setFromPartyID(PeppolCertificateHelper.getSubjectCN((X509Certificate) aOurCert.getCertificate()));
                aClient.setToRole(CAS4.DEFAULT_ROLE);
                aClient.setToPartyID(PeppolCertificateHelper.getSubjectCN(aTheirCert));
                aClient.ebms3Properties().setAll(MessageHelperMethods.createEbms3Property(CAS4.ORIGINAL_SENDER, aSBDH.getSenderScheme(), aSBDH.getSenderValue()), MessageHelperMethods.createEbms3Property(CAS4.FINAL_RECIPIENT, aSBDH.getReceiverScheme(), aSBDH.getReceiverValue()));
                aClient.setPayload(SBDHWriter.standardBusinessDocument().getAsDocument(aSBD));
                final IAS4ClientBuildMessageCallback aCallback = null;
                final IAS4OutgoingDumper aOutgoingDumper = null;
                final IAS4RetryCallback aRetryCallback = null;
                final AS4ClientSentMessage<byte[]> aResponseEntity = aClient.sendMessageWithRetries(W3CEndpointReferenceHelper.getAddress(aEndpoint.getEndpointReference()), new ResponseHandlerByteArray(), aCallback, aOutgoingDumper, aRetryCallback);
                LOGGER.info("Successfully transmitted document with message ID '" + aResponseEntity.getMessageID() + "' for '" + aSBDH.getReceiverAsIdentifier().getURIEncoded() + "' to '" + W3CEndpointReferenceHelper.getAddress(aEndpoint.getEndpointReference()) + "' in " + aSW.stopAndGetMillis() + " ms");
                if (aResponseEntity.hasResponse()) {
                    final String sMessageID = aResponseEntity.getMessageID();
                    final String sFilename = FilenameHelper.getAsSecureValidASCIIFilename(sMessageID) + "-response.xml";
                    final File aResponseFile = aIncomingDir.resolve(sFilename).toFile();
                    if (SimpleFileIO.writeFile(aResponseFile, aResponseEntity.getResponse()).isSuccess())
                        LOGGER.info("Response file was written to '" + aResponseFile.getAbsolutePath() + "'");
                    else
                        LOGGER.error("Error writing response file to '" + aResponseFile.getAbsolutePath() + "'");
                }
                bSuccess = true;
            }
        }
    } catch (final Exception ex) {
        LOGGER.error("Error sending " + aSendFile.toString(), ex);
    }
    // After the exception handler!
    {
        // Move to done or error directory?
        final Path aDest = aSendFile.resolveSibling(bSuccess ? PATH_DONE : PATH_ERROR).resolve(aSendFile.getFileName());
        try {
            Files.move(aSendFile, aDest);
        } catch (final IOException ex) {
            LOGGER.error("Error moving from '" + aSendFile.toString() + "' to '" + aDest + "'", ex);
        }
    }
}
Also used : Path(java.nio.file.Path) IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) IAS4OutgoingDumper(com.helger.phase4.dump.IAS4OutgoingDumper) PeppolSBDHDocument(com.helger.peppol.sbdh.PeppolSBDHDocument) ISMPServiceMetadataProvider(com.helger.smpclient.peppol.ISMPServiceMetadataProvider) StandardBusinessDocument(org.unece.cefact.namespaces.sbdh.StandardBusinessDocument) ResponseHandlerByteArray(com.helger.httpclient.response.ResponseHandlerByteArray) IAS4RetryCallback(com.helger.phase4.client.IAS4RetryCallback) PeppolSBDHDocumentReader(com.helger.peppol.sbdh.read.PeppolSBDHDocumentReader) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) StopWatch(com.helger.commons.timing.StopWatch) SMPClient(com.helger.smpclient.peppol.SMPClient) EndpointType(com.helger.xsds.peppol.smp1.EndpointType) AS4ClientUserMessage(com.helger.phase4.client.AS4ClientUserMessage) AS4ResourceHelper(com.helger.phase4.util.AS4ResourceHelper) File(java.io.File)

Aggregations

IOException (java.io.IOException)5 IAS4OutgoingDumper (com.helger.phase4.dump.IAS4OutgoingDumper)4 Wrapper (com.helger.commons.wrapper.Wrapper)3 AS4ClientUserMessage (com.helger.phase4.client.AS4ClientUserMessage)3 IAS4ClientBuildMessageCallback (com.helger.phase4.client.IAS4ClientBuildMessageCallback)3 IAS4RetryCallback (com.helger.phase4.client.IAS4RetryCallback)3 IAS4CryptoFactory (com.helger.phase4.crypto.IAS4CryptoFactory)3 Phase4Exception (com.helger.phase4.util.Phase4Exception)3 Nonnull (javax.annotation.Nonnull)3 Nullable (javax.annotation.Nullable)3 MessagingException (javax.mail.MessagingException)3 HttpEntity (org.apache.http.HttpEntity)3 ResponseHandler (org.apache.http.client.ResponseHandler)3 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)3 HttpHeaderMap (com.helger.commons.http.HttpHeaderMap)2 ResponseHandlerHttpEntity (com.helger.httpclient.response.ResponseHandlerHttpEntity)2 IAS4IncomingAttachmentFactory (com.helger.phase4.attachment.IAS4IncomingAttachmentFactory)2 WSS4JAttachment (com.helger.phase4.attachment.WSS4JAttachment)2 AS4ClientPullRequestMessage (com.helger.phase4.client.AS4ClientPullRequestMessage)2 AS4ClientSentMessage (com.helger.phase4.client.AS4ClientSentMessage)2