Search in sources :

Example 6 with HttpRetrySettings

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

the class MainPhase4PeppolSenderQvaliaConstantReceiver 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() + "'");
            }
        };
        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).receiverEndpointDetails(CertificateHelper.convertStringToCertficate("-----BEGIN CERTI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htodHRwOi8vcGtpLW9jc3Auc3ltYXV0aC5jb20wHwYD VR0jBBgwFoAUa29LtvE3uis8fxjNuiuyuXwqN+swLQYKYIZIAYb4RQEQAwQfMB0G E2CGSAGG+EUBEAECAwEBgamQ4QMWBjk1NzYwODA5BgpghkgBhvhFARAFBCswKQIB ABYkYUhSMGNITTZMeTl3YTJrdGNtRXVjM2x0WVhWMGFDNWpiMjA9MA0GCSqGSIb3 DQEBCwUAA4ICAQAAZNS3JzZn5rOcWKtYe+6Eh7nao8FQaMTXtKPOPWat00GUZwYX mqy2tyRTGzKWf+dByiGhfC0IdNlhHZJ7fH0TdXabFX9MaySm25TUJsaAX5eUTVMM C4XZJEX9ngie2NHTPqJsJPS/7utRONizjFa3PbI4STRt8SQNA3L/yxrf3H/Qujnd F5L6KTdIRU0pP+4qs4qbcbGcEzaZieOyNoSP2r1z3MIn+JVOHQetOrPkXKpuwFcD bdzaFLnZqiPRkI3ibpsml5fFLWwE9QTn+PcORZXvURlT0Ndm88FvDQWzAZ8y/f32 Fj0dCIFk+ACSwQnZsdVIcSzkDRYzQtxOmQW282rMO3TCgrKCztHQ/so+t7Mg4Qf+ wN/DmyZAdjhuzqnyX3mOxxbvFTqveatVL5PGMIbjhzWmrEztMgwdSB5DsS6OeaBL H3MohqqDECtiD5/U5FziHTDqSr6LIljz7zLK/7aK9I/h0xuoqzQGCqhn5mrB+ube L7SFxT6nM5pw5ZPvqIS0h4lOTWCq5Y5j2aXmo23trDfMoWqRncOlX18cnAThlnT2 RydPPOVrcFk4JehM2oRgm3ldo+Pj4lhQQ5WnBdX9o7yvnZhn96KyVqiMU25TDf6M JNLrljdeiEAl3pNsqzXSJ7nREhWzVI2IWe+NXEOUN3z7PgeKH0sh2KdS7g==" + "-----END CERTIFICATE-----\r\n" + ""), "https://peppol-ap-test.qvalia.com/peppol/as4").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) 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 7 with HttpRetrySettings

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

the class MainCEFeInvoicingConnectivityTest 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 WebScoped w = new WebScoped()) {
        // Read a UBL Invoice
        final byte[] aPayloadBytes = SimpleFileIO.getAllFileBytes(new File("src/test/resources/examples/base-example.xml"));
        if (aPayloadBytes == null)
            throw new IllegalStateException();
        final IAS4ClientBuildMessageCallback x1 = 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() + "'");
            }

            public void onSoapDocument(@Nonnull final Document aDoc) {
                if (false)
                    LOGGER.info("SOAP Document:\n" + XMLWriter.getNodeAsString(aDoc, new XMLWriterSettings().setIndent(EXMLSerializeIndent.INDENT_AND_ALIGN)));
            }
        };
        // TODO The message ID to use in the UI
        final String sAS4MessageID = "36999089-662a-441f-95fd-470bec2b538e-100@phase4";
        final ESimpleUserMessageSendResult eRes = Phase4CEFSender.builder().cryptoFactory(CF).httpRetrySettings(new HttpRetrySettings().setMaxRetries(0)).action("TC1Leg1").service("tc1", "bdx:noprocess").senderParticipantID(new SimpleParticipantIdentifier("connectivity-partid-qns", YOUR_ID)).receiverParticipantID(new SimpleParticipantIdentifier("connectivity-partid-qns", "domibus-gitb")).fromPartyIDType("urn:oasis:names:tc:ebcore:partyid-type:unregistered").fromPartyID(YOUR_ID).fromRole(CAS4.DEFAULT_INITIATOR_URL).toPartyIDType("urn:oasis:names:tc:ebcore:partyid-type:unregistered").toPartyID("domibus-gitb").toRole(CAS4.DEFAULT_RESPONDER_URL).messageID(sAS4MessageID).payload(Phase4OutgoingAttachment.builder().data(aPayloadBytes).filename("businessContentPayload").compressionGZIP().mimeType(CMimeType.TEXT_XML).contentID("message").build()).buildMessageCallback(x1).endpointDetailProvider(new AS4EndpointDetailProviderConstant(CertificateHelper.convertStringToCertficateOrNull("-----BEGIN CERTIFICATE-----\r\n" + "MIIDOzCCAiOgAwIBAgIJAKbwaKpEwNTKMA0GCSqGSIb3DQEBCwUAMDQxDTALBgNV\r\n" + "BAoMBEdJVEIxDTALBgNVBAsMBEdJVEIxFDASBgNVBAMMC2dpdGItZW5naW5lMB4X\r\n" + "DTE0MTIyNDEzMjIzNFoXDTI0MTIyMTEzMjIzNFowNDENMAsGA1UECgwER0lUQjEN\r\n" + "MAsGA1UECwwER0lUQjEUMBIGA1UEAwwLZ2l0Yi1lbmdpbmUwggEiMA0GCSqGSIb3\r\n" + "DQEBAQUAA4IBDwAwggEKAoIBAQCpNuRRMhpd2SvNKsZe/WTxm4zuX2Zc5by3zGcm\r\n" + "uzwePdMCnCXk2FAUH67qS9r5VBa4USfiB7l1piyLrNwYWGRDo5OeWIz6Q821/1v7\r\n" + "UHq7FfB0LFPcJ+mOwrDqS+VL0MjcSW4pocJHrpFwObWHTY/R4WmW2xwGOKVh0OUL\r\n" + "UhqQsHDnDhCzFaEWhS8n1lUw3GRipwKLyYvXK8XgLceEmh+j0+cdmIj4a1L4oza/\r\n" + "UgBnCqSob+vowgClyZnGVihE9K8eLLwCSLlIiD+bXWf0VJPLXBNLdNIkRRC0QO0j\r\n" + "T9TuE5TF3SknkA5D0NFp023Alz7jieI0D6JE78QyNQN6y6QRAgMBAAGjUDBOMB0G\r\n" + "A1UdDgQWBBQpAkry20hAcvlw+4poxQC8TI+EgTAfBgNVHSMEGDAWgBQpAkry20hA\r\n" + "cvlw+4poxQC8TI+EgTAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQBS\r\n" + "dfmT3E9uvhiEgVefdwXkkxqlXLQQxfjaqVRVzPTHLqdVs/nBK+iQNhqg+6eLcaGQ\r\n" + "yyDy88vwQ85rqwOFbZd05esIFXYl0pgl1pVsb7HmMNmKT3UPay3HDlHX45ZoexDU\r\n" + "pza4OcrauEM8Yg/5i9dCIPC1GiHebJpYusMVfP78b+5DAyARrHtcb0EJ8rOLxHh6\r\n" + "K2S4EHI6sqQkGHEt1z4m66LyK+vnkLGaq3y6MWEufh78eICDyyVz0DhdIhr18ZHX\r\n" + "dpcsH2VOkE36KnWSo0spEXa6ZtP8MqQ60kJgBt4XcuArKfjIGC6vB6dE0NzXngBD\r\n" + "PHgMfmHJW018/6eN/f0q\r\n" + "-----END CERTIFICATE-----"), "https://www.itb.ec.europa.eu/cef/domibus/services/msh")).sendMessageAndCheckForReceipt();
        LOGGER.info("Sending AS4 message to CEF with result " + eRes);
    } finally {
        WebScopeManager.onGlobalEnd();
    }
}
Also used : WebScoped(com.helger.web.scope.mgr.WebScoped) IAS4ClientBuildMessageCallback(com.helger.phase4.client.IAS4ClientBuildMessageCallback) XMLWriterSettings(com.helger.xml.serialize.write.XMLWriterSettings) Nonnull(javax.annotation.Nonnull) Document(org.w3c.dom.Document) AS4UserMessage(com.helger.phase4.messaging.domain.AS4UserMessage) SimpleParticipantIdentifier(com.helger.peppolid.simple.participant.SimpleParticipantIdentifier) 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) AS4EndpointDetailProviderConstant(com.helger.phase4.dynamicdiscovery.AS4EndpointDetailProviderConstant) File(java.io.File) AS4OutgoingDumperFileBased(com.helger.phase4.dump.AS4OutgoingDumperFileBased)

Example 8 with HttpRetrySettings

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

the class BasicHttpPoster method sendGenericMessageWithRetries.

@Nonnull
public <T> T sendGenericMessageWithRetries(@Nonnull final String sURL, @Nullable final HttpHeaderMap aCustomHttpHeaders, @Nonnull final HttpEntity aHttpEntity, @Nonnull final String sMessageID, @Nonnull final HttpRetrySettings aRetrySettings, @Nonnull final ResponseHandler<? extends T> aResponseHandler, @Nullable final IAS4OutgoingDumper aOutgoingDumper, @Nullable final IAS4RetryCallback aRetryCallback) throws IOException {
    // Parameter or global one - may still be null
    final IAS4OutgoingDumper aRealOutgoingDumper = aOutgoingDumper != null ? aOutgoingDumper : AS4DumpManager.getOutgoingDumper();
    // This class holds the effective OutputStream to which the dump is written
    final Wrapper<OutputStream> aDumpOSHolder = new Wrapper<>();
    try {
        if (aRetrySettings.isRetryEnabled()) {
            // Send with retry
            if (!aHttpEntity.isRepeatable())
                throw new IllegalStateException("If retry is enabled, a repeatable entity must be provided");
            final int nMaxRetries = aRetrySettings.getMaxRetries();
            final int nMaxTries = 1 + nMaxRetries;
            Duration aDurationBeforeRetry = aRetrySettings.getDurationBeforeRetry();
            for (int nTry = 0; nTry < nMaxTries; nTry++) {
                if (nTry > 0)
                    LOGGER.info("Retry #" + nTry + "/" + nMaxRetries + " for sending message with ID '" + sMessageID + "'");
                try {
                    // Create a new one every time (for new filename, new timestamp,
                    // etc.)
                    final HttpEntity aDumpingEntity = createDumpingHttpEntity(aRealOutgoingDumper, aHttpEntity, sMessageID, aCustomHttpHeaders, nTry, aDumpOSHolder);
                    // Dump only for the first try - the remaining tries
                    return sendGenericMessage(sURL, aCustomHttpHeaders, aDumpingEntity, aResponseHandler);
                } catch (final IOException ex) {
                    // Last try? -> propagate exception
                    if (nTry == nMaxTries - 1)
                        throw ex;
                    // After the first retry, increase the waiting time
                    if (nTry > 1)
                        aDurationBeforeRetry = HttpRetrySettings.getIncreased(aDurationBeforeRetry, aRetrySettings.getRetryIncreaseFactor());
                    if (aRetryCallback != null)
                        if (aRetryCallback.onBeforeRetry(sMessageID, sURL, nTry, nMaxTries, aDurationBeforeRetry.toMillis(), ex).isBreak()) {
                            // Explicitly interrupt retry
                            LOGGER.warn("Error sending message '" + sMessageID + "' to '" + sURL + ": " + ex.getClass().getSimpleName() + " - " + ex.getMessage() + " - retrying was explicitly stopped by the RetryCallback");
                            // Propagate Exception as if it would be the last retry
                            throw ex;
                        }
                    LOGGER.warn("Error sending message '" + sMessageID + "' to '" + sURL + "': " + ex.getClass().getSimpleName() + " - " + ex.getMessage() + " - waiting " + aDurationBeforeRetry.toMillis() + " ms, than retrying");
                    // Sleep and try again afterwards
                    ThreadHelper.sleep(aDurationBeforeRetry.toMillis());
                } finally {
                    // Flush and close the dump output stream (if any)
                    StreamHelper.close(aDumpOSHolder.get());
                }
            }
            throw new IllegalStateException("Should never be reached (after maximum of " + nMaxTries + " tries)!");
        }
        // else non retry
        {
            final HttpEntity aDumpingEntity = createDumpingHttpEntity(aRealOutgoingDumper, aHttpEntity, sMessageID, aCustomHttpHeaders, 0, aDumpOSHolder);
            try {
                // Send without retry
                return sendGenericMessage(sURL, aCustomHttpHeaders, aDumpingEntity, aResponseHandler);
            } finally {
                // Close the dump output stream (if any)
                StreamHelper.close(aDumpOSHolder.get());
            }
        }
    } finally {
        // Add the possibility to close open resources
        if (aRealOutgoingDumper != null && aDumpOSHolder.isSet())
            try {
                aRealOutgoingDumper.onEndRequest(EAS4MessageMode.REQUEST, null, null, sMessageID);
            } catch (final Exception ex) {
                LOGGER.error("OutgoingDumper.onEndRequest failed. Dumper=" + aRealOutgoingDumper + "; MessageID=" + sMessageID, ex);
            }
    }
}
Also used : IAS4OutgoingDumper(com.helger.phase4.dump.IAS4OutgoingDumper) HttpEntityWrapper(org.apache.http.entity.HttpEntityWrapper) Wrapper(com.helger.commons.wrapper.Wrapper) HttpEntity(org.apache.http.HttpEntity) MultiOutputStream(com.helger.phase4.util.MultiOutputStream) OutputStream(java.io.OutputStream) Duration(java.time.Duration) IOException(java.io.IOException) IOException(java.io.IOException) Nonnull(javax.annotation.Nonnull)

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