Search in sources :

Example 1 with HttpRetrySettings

use of com.helger.phase4.http.HttpRetrySettings in project phase4 by phax.

the class MainPhase4PeppolSenderQvaliaLargeFile method main.

public static void main(final String[] args) {
    WebScopeManager.onGlobalBegin(MockServletContext.create());
    // Dump (for debugging purpose only)
    AS4DumpManager.setIncomingDumper(new AS4IncomingDumperFileBased());
    AS4DumpManager.setOutgoingDumper(new AS4OutgoingDumperFileBased());
    try {
        final Element aPayloadElement = DOMReader.readXMLDOM(new File("src/test/resources/examples/large-files/base-example-large-16m.xml")).getDocumentElement();
        if (aPayloadElement == null)
            throw new IllegalStateException("Failed to read XML file to be send");
        // Start configuring here
        final IParticipantIdentifier aReceiverID = Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("0007:5567321707");
        final IAS4ClientBuildMessageCallback aBuildMessageCallback = new IAS4ClientBuildMessageCallback() {

            public void onAS4Message(final AbstractAS4Message<?> aMsg) {
                final AS4UserMessage aUserMsg = (AS4UserMessage) aMsg;
                LOGGER.info("Sending out AS4 message with message ID '" + aUserMsg.getEbms3UserMessage().getMessageInfo().getMessageId() + "'");
            }
        };
        // Invalid certificate is valid until 2029
        final IAS4CryptoFactory cf = AS4CryptoFactoryProperties.getDefaultInstance();
        final ESimpleUserMessageSendResult eResult;
        eResult = Phase4PeppolSender.builder().httpRetrySettings(new HttpRetrySettings().setMaxRetries(0)).cryptoFactory(cf).documentTypeID(Phase4PeppolSender.IF.createDocumentTypeIdentifierWithDefaultScheme("urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice##urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0::2.1")).processID(Phase4PeppolSender.IF.createProcessIdentifierWithDefaultScheme("urn:fdc:peppol.eu:2017:poacc:billing:01:1.0")).senderParticipantID(Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("9915:phase4-test-sender")).receiverParticipantID(aReceiverID).senderPartyID("POP000306").payload(aPayloadElement).smpClient(new SMPClientReadOnly(Phase4PeppolSender.URL_PROVIDER, aReceiverID, ESML.DIGIT_TEST)).validationConfiguration(PeppolValidation3_13_0.VID_OPENPEPPOL_INVOICE_V3, new Phase4PeppolValidatonResultHandler()).compressPayload(false).buildMessageCallback(aBuildMessageCallback).sendMessageAndCheckForReceipt();
        LOGGER.info("Peppol send result: " + eResult);
    } catch (final Exception ex) {
        LOGGER.error("Error sending Peppol message via AS4", ex);
    } finally {
        WebScopeManager.onGlobalEnd();
    }
}
Also used : IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) IAS4CryptoFactory(com.helger.phase4.crypto.IAS4CryptoFactory) SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) Element(org.w3c.dom.Element) AS4UserMessage(com.helger.phase4.messaging.domain.AS4UserMessage) HttpRetrySettings(com.helger.phase4.http.HttpRetrySettings) AbstractAS4Message(com.helger.phase4.messaging.domain.AbstractAS4Message) ESimpleUserMessageSendResult(com.helger.phase4.sender.AbstractAS4UserMessageBuilder.ESimpleUserMessageSendResult) AS4IncomingDumperFileBased(com.helger.phase4.dump.AS4IncomingDumperFileBased) File(java.io.File) AS4OutgoingDumperFileBased(com.helger.phase4.dump.AS4OutgoingDumperFileBased) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 2 with HttpRetrySettings

use of com.helger.phase4.http.HttpRetrySettings in project phase4 by phax.

the class MainPhase4PeppolSenderQvaliaUBL method main.

public static void main(final String[] args) {
    WebScopeManager.onGlobalBegin(MockServletContext.create());
    // Dump (for debugging purpose only)
    AS4DumpManager.setIncomingDumper(new AS4IncomingDumperFileBased());
    AS4DumpManager.setOutgoingDumper(new AS4OutgoingDumperFileBased());
    try {
        final Element aPayloadElement = DOMReader.readXMLDOM(new File("src/test/resources/examples/example-ubl-en-qvalia.xml")).getDocumentElement();
        if (aPayloadElement == null)
            throw new IllegalStateException("Failed to read XML file to be send");
        // Start configuring here
        final IParticipantIdentifier aReceiverID = Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("0007:5567321707");
        final IAS4ClientBuildMessageCallback aBuildMessageCallback = new IAS4ClientBuildMessageCallback() {

            public void onAS4Message(final AbstractAS4Message<?> aMsg) {
                final AS4UserMessage aUserMsg = (AS4UserMessage) aMsg;
                LOGGER.info("Sending out AS4 message with message ID '" + aUserMsg.getEbms3UserMessage().getMessageInfo().getMessageId() + "'");
                LOGGER.info("Sending out AS4 message with conversation ID '" + aUserMsg.getEbms3UserMessage().getCollaborationInfo().getConversationId() + "'");
            }
        };
        // Add EN16931 rulesets
        final IValidationExecutorSetRegistry<IValidationSourceXML> aVESRegistry = Phase4PeppolValidation.createDefaultRegistry();
        EN16931Validation.initEN16931(aVESRegistry);
        // Invalid certificate is valid until 2029
        final IAS4CryptoFactory cf = AS4CryptoFactoryProperties.getDefaultInstance();
        final ESimpleUserMessageSendResult eResult;
        eResult = Phase4PeppolSender.builder().httpRetrySettings(new HttpRetrySettings().setMaxRetries(0)).cryptoFactory(cf).documentTypeID(Phase4PeppolSender.IF.createDocumentTypeIdentifierWithDefaultScheme("urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice##urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0::2.1")).processID(Phase4PeppolSender.IF.createProcessIdentifierWithDefaultScheme("urn:fdc:peppol.eu:2017:poacc:billing:01:1.0")).senderParticipantID(Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("9915:phase4-test-sender")).receiverParticipantID(aReceiverID).senderPartyID("POP000306").payload(aPayloadElement).smpClient(new SMPClientReadOnly(Phase4PeppolSender.URL_PROVIDER, aReceiverID, ESML.DIGIT_TEST)).rawResponseConsumer(new AS4RawResponseConsumerWriteToFile()).validationRegistry(aVESRegistry).validationConfiguration(EN16931Validation.VID_UBL_INVOICE_137, new Phase4PeppolValidatonResultHandler()).buildMessageCallback(aBuildMessageCallback).sendMessageAndCheckForReceipt();
        LOGGER.info("Peppol send result: " + eResult);
    } catch (final Exception ex) {
        LOGGER.error("Error sending Peppol message via AS4", ex);
    } finally {
        WebScopeManager.onGlobalEnd();
    }
}
Also used : IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) IAS4CryptoFactory(com.helger.phase4.crypto.IAS4CryptoFactory) SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) Element(org.w3c.dom.Element) IValidationSourceXML(com.helger.phive.engine.source.IValidationSourceXML) AS4UserMessage(com.helger.phase4.messaging.domain.AS4UserMessage) HttpRetrySettings(com.helger.phase4.http.HttpRetrySettings) AbstractAS4Message(com.helger.phase4.messaging.domain.AbstractAS4Message) ESimpleUserMessageSendResult(com.helger.phase4.sender.AbstractAS4UserMessageBuilder.ESimpleUserMessageSendResult) AS4IncomingDumperFileBased(com.helger.phase4.dump.AS4IncomingDumperFileBased) AS4RawResponseConsumerWriteToFile(com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile) AS4RawResponseConsumerWriteToFile(com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile) File(java.io.File) AS4OutgoingDumperFileBased(com.helger.phase4.dump.AS4OutgoingDumperFileBased) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 3 with HttpRetrySettings

use of com.helger.phase4.http.HttpRetrySettings 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 4 with HttpRetrySettings

use of com.helger.phase4.http.HttpRetrySettings in project phase4 by phax.

the class MainPhase4PeppolSenderQvalia method main.

public static void main(final String[] args) {
    WebScopeManager.onGlobalBegin(MockServletContext.create());
    // Dump (for debugging purpose only)
    AS4DumpManager.setIncomingDumper(new AS4IncomingDumperFileBased());
    AS4DumpManager.setOutgoingDumper(new AS4OutgoingDumperFileBased());
    try {
        final Element aPayloadElement = DOMReader.readXMLDOM(new File("src/test/resources/examples/base-example.xml")).getDocumentElement();
        if (aPayloadElement == null)
            throw new IllegalStateException("Failed to read XML file to be send");
        // Start configuring here
        final IParticipantIdentifier aReceiverID = Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("0007:5567321707");
        final IAS4ClientBuildMessageCallback aBuildMessageCallback = new IAS4ClientBuildMessageCallback() {

            public void onAS4Message(final AbstractAS4Message<?> aMsg) {
                final AS4UserMessage aUserMsg = (AS4UserMessage) aMsg;
                LOGGER.info("Sending out AS4 message with message ID '" + aUserMsg.getEbms3UserMessage().getMessageInfo().getMessageId() + "'");
                LOGGER.info("Sending out AS4 message with conversation ID '" + aUserMsg.getEbms3UserMessage().getCollaborationInfo().getConversationId() + "'");
            }
        };
        // Invalid certificate is valid until 2029
        final IAS4CryptoFactory cf = true ? AS4CryptoFactoryProperties.getDefaultInstance() : new AS4CryptoFactoryInMemoryKeyStore(KeyStoreHelper.loadKeyStoreDirect(EKeyStoreType.JKS, "invalid-keystore-pw-peppol.jks", "peppol"), "1", "peppol", KeyStoreHelper.loadKeyStore(PeppolKeyStoreHelper.TRUSTSTORE_TYPE, PeppolKeyStoreHelper.Config2018.TRUSTSTORE_PRODUCTION_CLASSPATH, PeppolKeyStoreHelper.TRUSTSTORE_PASSWORD).getKeyStore());
        final ESimpleUserMessageSendResult eResult;
        eResult = Phase4PeppolSender.builder().httpRetrySettings(new HttpRetrySettings().setMaxRetries(0)).cryptoFactory(cf).documentTypeID(Phase4PeppolSender.IF.createDocumentTypeIdentifierWithDefaultScheme("urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice##urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0::2.1")).processID(Phase4PeppolSender.IF.createProcessIdentifierWithDefaultScheme("urn:fdc:peppol.eu:2017:poacc:billing:01:1.0")).senderParticipantID(Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("9915:phase4-test-sender")).receiverParticipantID(aReceiverID).senderPartyID("POP000306").payload(aPayloadElement).smpClient(new SMPClientReadOnly(Phase4PeppolSender.URL_PROVIDER, aReceiverID, ESML.DIGIT_TEST)).rawResponseConsumer(new AS4RawResponseConsumerWriteToFile()).validationConfiguration(PeppolValidation3_13_0.VID_OPENPEPPOL_INVOICE_V3, new Phase4PeppolValidatonResultHandler()).buildMessageCallback(aBuildMessageCallback).sendMessageAndCheckForReceipt();
        LOGGER.info("Peppol send result: " + eResult);
    } catch (final Exception ex) {
        LOGGER.error("Error sending Peppol message via AS4", ex);
    } finally {
        WebScopeManager.onGlobalEnd();
    }
}
Also used : IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) IAS4CryptoFactory(com.helger.phase4.crypto.IAS4CryptoFactory) SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) Element(org.w3c.dom.Element) AS4CryptoFactoryInMemoryKeyStore(com.helger.phase4.crypto.AS4CryptoFactoryInMemoryKeyStore) AS4UserMessage(com.helger.phase4.messaging.domain.AS4UserMessage) HttpRetrySettings(com.helger.phase4.http.HttpRetrySettings) AbstractAS4Message(com.helger.phase4.messaging.domain.AbstractAS4Message) ESimpleUserMessageSendResult(com.helger.phase4.sender.AbstractAS4UserMessageBuilder.ESimpleUserMessageSendResult) AS4IncomingDumperFileBased(com.helger.phase4.dump.AS4IncomingDumperFileBased) AS4RawResponseConsumerWriteToFile(com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile) AS4RawResponseConsumerWriteToFile(com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile) File(java.io.File) AS4OutgoingDumperFileBased(com.helger.phase4.dump.AS4OutgoingDumperFileBased) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Example 5 with HttpRetrySettings

use of com.helger.phase4.http.HttpRetrySettings in project phase4 by phax.

the class MainPhase4PeppolSenderQvaliaCII method main.

public static void main(final String[] args) {
    WebScopeManager.onGlobalBegin(MockServletContext.create());
    // Dump (for debugging purpose only)
    AS4DumpManager.setIncomingDumper(new AS4IncomingDumperFileBased());
    AS4DumpManager.setOutgoingDumper(new AS4OutgoingDumperFileBased());
    try {
        final Element aPayloadElement = DOMReader.readXMLDOM(new File("src/test/resources/examples/cii/cii-en-qvalia.xml")).getDocumentElement();
        if (aPayloadElement == null)
            throw new IllegalStateException("Failed to read XML file to be send");
        // Start configuring here
        final IParticipantIdentifier aReceiverID = Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("0007:5567321707");
        // Add EN16931 rulesets
        final IValidationExecutorSetRegistry<IValidationSourceXML> aVESRegistry = Phase4PeppolValidation.createDefaultRegistry();
        EN16931Validation.initEN16931(aVESRegistry);
        final ESimpleUserMessageSendResult eResult;
        eResult = Phase4PeppolSender.builder().httpRetrySettings(new HttpRetrySettings().setMaxRetries(0)).documentTypeID(Phase4PeppolSender.IF.createDocumentTypeIdentifierWithDefaultScheme("urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100::CrossIndustryInvoice##urn:cen.eu:en16931:2017::D16B")).processID(Phase4PeppolSender.IF.createProcessIdentifierWithDefaultScheme("urn:fdc:peppol.eu:poacc:en16931:any")).senderParticipantID(Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("9915:phase4-test-sender")).receiverParticipantID(aReceiverID).senderPartyID("POP000306").payload(aPayloadElement).smpClient(new SMPClientReadOnly(Phase4PeppolSender.URL_PROVIDER, aReceiverID, ESML.DIGIT_TEST)).rawResponseConsumer(new AS4RawResponseConsumerWriteToFile()).validationRegistry(aVESRegistry).validationConfiguration(EN16931Validation.VID_CII_137, new Phase4PeppolValidatonResultHandler()).sendMessageAndCheckForReceipt();
        LOGGER.info("Peppol send result: " + eResult);
    } catch (final Exception ex) {
        LOGGER.error("Error sending Peppol message via AS4", ex);
    } finally {
        WebScopeManager.onGlobalEnd();
    }
}
Also used : SMPClientReadOnly(com.helger.smpclient.peppol.SMPClientReadOnly) Element(org.w3c.dom.Element) IValidationSourceXML(com.helger.phive.engine.source.IValidationSourceXML) HttpRetrySettings(com.helger.phase4.http.HttpRetrySettings) ESimpleUserMessageSendResult(com.helger.phase4.sender.AbstractAS4UserMessageBuilder.ESimpleUserMessageSendResult) AS4IncomingDumperFileBased(com.helger.phase4.dump.AS4IncomingDumperFileBased) AS4RawResponseConsumerWriteToFile(com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile) AS4RawResponseConsumerWriteToFile(com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile) File(java.io.File) AS4OutgoingDumperFileBased(com.helger.phase4.dump.AS4OutgoingDumperFileBased) IParticipantIdentifier(com.helger.peppolid.IParticipantIdentifier)

Aggregations

HttpRetrySettings (com.helger.phase4.http.HttpRetrySettings)7 AS4IncomingDumperFileBased (com.helger.phase4.dump.AS4IncomingDumperFileBased)6 AS4OutgoingDumperFileBased (com.helger.phase4.dump.AS4OutgoingDumperFileBased)6 AS4UserMessage (com.helger.phase4.messaging.domain.AS4UserMessage)6 ESimpleUserMessageSendResult (com.helger.phase4.sender.AbstractAS4UserMessageBuilder.ESimpleUserMessageSendResult)6 File (java.io.File)6 IParticipantIdentifier (com.helger.peppolid.IParticipantIdentifier)5 IAS4ClientBuildMessageCallback (com.helger.phase4.client.IAS4ClientBuildMessageCallback)5 AbstractAS4Message (com.helger.phase4.messaging.domain.AbstractAS4Message)5 Element (org.w3c.dom.Element)5 IAS4CryptoFactory (com.helger.phase4.crypto.IAS4CryptoFactory)4 SMPClientReadOnly (com.helger.smpclient.peppol.SMPClientReadOnly)4 AS4RawResponseConsumerWriteToFile (com.helger.phase4.dump.AS4RawResponseConsumerWriteToFile)3 IValidationSourceXML (com.helger.phive.engine.source.IValidationSourceXML)2 IOException (java.io.IOException)2 Nonnull (javax.annotation.Nonnull)2 HttpEntity (org.apache.http.HttpEntity)2 Document (org.w3c.dom.Document)2 CommonsArrayList (com.helger.commons.collection.impl.CommonsArrayList)1 ICommonsList (com.helger.commons.collection.impl.ICommonsList)1