Search in sources :

Example 36 with AS2Exception

use of com.helger.as2lib.exception.AS2Exception in project as2-lib by phax.

the class AsynchMDNSenderModule method handle.

public void handle(@Nonnull final String sAction, @Nonnull final IMessage aBaseMsg, @Nullable final Map<String, Object> aOptions) throws AS2Exception {
    try (final AS2ResourceHelper aResHelper = new AS2ResourceHelper()) {
        final AS2Message aMsg = (AS2Message) aBaseMsg;
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Async MDN submitted" + aMsg.getLoggingText());
        final DispositionType aDisposition = DispositionType.createSuccess();
        final int nRetries = getRetryCount(aMsg.partnership(), aOptions);
        try (final IHTTPOutgoingDumper aOutgoingDumper = getHttpOutgoingDumper(aMsg)) {
            _sendViaHTTP(aMsg, aDisposition, aOutgoingDumper, aResHelper);
        } catch (final AS2HttpResponseException ex) {
            if (LOGGER.isErrorEnabled())
                LOGGER.error("Http Response Error " + ex.getMessage());
            // Resend if the HTTP Response has an error code
            ex.terminate();
            if (!doResend(IProcessorSenderModule.DO_SEND_ASYNC_MDN, aMsg, ex, nRetries))
                throw ex;
        } catch (final IOException ex) {
            // Resend if a network error occurs during transmission
            final AS2Exception wioe = WrappedAS2Exception.wrap(ex).setSourceMsg(aMsg).terminate();
            if (!doResend(IProcessorSenderModule.DO_SEND_ASYNC_MDN, aMsg, wioe, nRetries))
                throw wioe;
        } catch (final Exception ex) {
            // Propagate error if it can't be handled by a resend
            throw WrappedAS2Exception.wrap(ex);
        }
    } finally {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Async MDN message sent");
    }
}
Also used : AS2ResourceHelper(com.helger.as2lib.util.AS2ResourceHelper) DispositionType(com.helger.as2lib.disposition.DispositionType) AS2Message(com.helger.as2lib.message.AS2Message) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) IHTTPOutgoingDumper(com.helger.as2lib.util.dump.IHTTPOutgoingDumper) IOException(java.io.IOException) MessagingException(javax.mail.MessagingException) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) IOException(java.io.IOException) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException)

Example 37 with AS2Exception

use of com.helger.as2lib.exception.AS2Exception in project as2-lib by phax.

the class MDNFileModule method handle.

public void handle(@Nonnull final String sAction, @Nonnull final IMessage aMsg, @Nullable final Map<String, Object> aOptions) throws AS2Exception {
    // store mdn data
    if (aMsg.getMDN() == null)
        throw new AS2Exception("Message has no MDN");
    try {
        final File aMdnFile = getFile(aMsg, getAttributeAsStringRequired(ATTR_FILENAME));
        final InputStream aIS = getMDNStream(aMsg.getMDN());
        store(aMdnFile, aIS);
        LOGGER.info("stored MDN to " + aMdnFile.getAbsolutePath());
    } catch (final IOException ex) {
        throw WrappedAS2Exception.wrap(ex);
    }
}
Also used : AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) NonBlockingByteArrayInputStream(com.helger.commons.io.stream.NonBlockingByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) File(java.io.File)

Example 38 with AS2Exception

use of com.helger.as2lib.exception.AS2Exception in project as2-lib by phax.

the class InMemoryResenderModule method resendItem.

protected void resendItem(@Nonnull final ResendItem aItem) throws AS2Exception {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Resending item");
    IMessage aMsg = null;
    try {
        final String sResendAction = aItem.getResendAction();
        final String sRemainingRetries = Integer.toString(aItem.getRetries() - 1);
        aMsg = aItem.getMessage();
        // Transmit the message
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Loaded message for resend" + aMsg.getLoggingText());
        final ICommonsMap<String, Object> aOptions = new CommonsHashMap<>();
        aOptions.put(IProcessorResenderModule.OPTION_RETRIES, sRemainingRetries);
        getSession().getMessageProcessor().handle(sResendAction, aMsg, aOptions);
        // Finally remove from list
        m_aRWLock.writeLockedBoolean(() -> m_aItems.remove(aItem));
    } catch (final AS2Exception ex) {
        throw ex.setSourceMsg(aMsg);
    }
}
Also used : AS2Exception(com.helger.as2lib.exception.AS2Exception) IMessage(com.helger.as2lib.message.IMessage) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap)

Example 39 with AS2Exception

use of com.helger.as2lib.exception.AS2Exception in project as2-lib by phax.

the class AS2SenderModule method receiveSyncMDN.

/**
 * @param aMsg
 *        AS2Message
 * @param aHttpClient
 *        URLConnection
 * @param aOriginalMIC
 *        mic value from original msg
 * @param aIncomingDumper
 *        Incoming dumper. May be <code>null</code>.
 * @param aResHelper
 *        Resource helper
 * @throws AS2Exception
 *         in case of an error
 * @throws IOException
 *         in case of an IO error
 */
protected void receiveSyncMDN(@Nonnull final AS2Message aMsg, @Nonnull final AS2HttpClient aHttpClient, @Nonnull final MIC aOriginalMIC, @Nullable final IHTTPIncomingDumper aIncomingDumper, @Nonnull final AS2ResourceHelper aResHelper) throws AS2Exception, IOException {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Receiving synchronous MDN for message" + aMsg.getLoggingText());
    try {
        // Create a MessageMDN and copy HTTP headers
        final IMessageMDN aMDN = new AS2MessageMDN(aMsg);
        // Bug in ph-commons 9.1.3 in addAllHeaders!
        aMDN.headers().addAllHeaders(aHttpClient.getResponseHeaderFields());
        // Receive the MDN data
        final InputStream aConnIS = aHttpClient.getInputStream();
        final NonBlockingByteArrayOutputStream aMDNStream = new NonBlockingByteArrayOutputStream();
        // Retrieve the whole MDN content
        StreamHelper.copyByteStream().from(aConnIS).closeFrom(true).to(aMDNStream).closeTo(true).limit(StringParser.parseLong(aMDN.getHeader(CHttpHeader.CONTENT_LENGTH), -1)).build();
        // Dump collected message
        if (aIncomingDumper != null)
            aIncomingDumper.dumpIncomingRequest(aMDN.headers().getAllHeaderLines(true), aMDNStream.getBufferOrCopy(), aMDN);
        if (LOGGER.isTraceEnabled()) {
            // Debug print the whole MDN stream
            LOGGER.trace("Retrieved MDN stream data:\n" + aMDNStream.getAsString(StandardCharsets.ISO_8859_1));
        }
        final MimeBodyPart aPart = new MimeBodyPart(AS2HttpHelper.getAsInternetHeaders(aMDN.headers()), aMDNStream.getBufferOrCopy());
        aMDN.setData(aPart);
        // get the MDN partnership info
        aMDN.partnership().setSenderAS2ID(aMDN.getHeader(CHttpHeader.AS2_FROM));
        aMDN.partnership().setReceiverAS2ID(aMDN.getHeader(CHttpHeader.AS2_TO));
        // Set the appropriate key store aliases
        aMDN.partnership().setSenderX509Alias(aMsg.partnership().getReceiverX509Alias());
        aMDN.partnership().setReceiverX509Alias(aMsg.partnership().getSenderX509Alias());
        // Update the partnership
        getSession().getPartnershipFactory().updatePartnership(aMDN, false);
        final ICertificateFactory aCertFactory = getSession().getCertificateFactory();
        final X509Certificate aSenderCert = aCertFactory.getCertificate(aMDN, ECertificatePartnershipType.SENDER);
        boolean bUseCertificateInBodyPart;
        final ETriState eUseCertificateInBodyPart = aMsg.partnership().getVerifyUseCertificateInBodyPart();
        if (eUseCertificateInBodyPart.isDefined()) {
            // Use per partnership
            bUseCertificateInBodyPart = eUseCertificateInBodyPart.getAsBooleanValue();
        } else {
            // Use global value
            bUseCertificateInBodyPart = getSession().isCryptoVerifyUseCertificateInBodyPart();
        }
        AS2Helper.parseMDN(aMsg, aSenderCert, bUseCertificateInBodyPart, m_aVerificationCertificateConsumer, aResHelper);
        try {
            getSession().getMessageProcessor().handle(IProcessorStorageModule.DO_STOREMDN, aMsg, null);
        } catch (final AS2ComponentNotFoundException | AS2NoModuleException ex) {
        // No message processor found
        // Or no module found in message processor
        }
        final String sDisposition = aMDN.attrs().getAsString(AS2MessageMDN.MDNA_DISPOSITION);
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Received synchronous AS2 MDN [" + sDisposition + "]" + aMsg.getLoggingText());
        // Asynch MDN 2007-03-12
        // Verify if the original mic is equal to the mic in returned MDN
        final String sReturnMIC = aMDN.attrs().getAsString(AS2MessageMDN.MDNA_MIC);
        final MIC aReturnMIC = MIC.parse(sReturnMIC);
        // Catch ReturnMIC == null in case the attribute is simply missing
        final boolean bMICMatch = aOriginalMIC != null && aReturnMIC != null && aReturnMIC.equals(aOriginalMIC);
        if (bMICMatch) {
            // MIC was matched - all good
            m_aMICMatchingHandler.onMICMatch(aMsg, sReturnMIC);
        } else {
            // file was sent completely but the returned mic was not matched,
            m_aMICMatchingHandler.onMICMismatch(aMsg, aOriginalMIC == null ? null : aOriginalMIC.getAsAS2String(), sReturnMIC);
        }
        if (m_aIncomingMDNCallback != null)
            m_aIncomingMDNCallback.onIncomingMDN(true, aMDN, aMDN.getHeader(CHttpHeader.AS2_FROM), aMDN.getHeader(CHttpHeader.AS2_TO), sDisposition, aMDN.attrs().getAsString(AS2MessageMDN.MDNA_MIC), aMDN.attrs().getAsString(AS2MessageMDN.MDNA_ORIG_MESSAGEID), aMDN.attrs().getAsBoolean(AS2Message.ATTRIBUTE_RECEIVED_SIGNED, false), bMICMatch);
        DispositionType.createFromString(sDisposition).validate(aMsg, aMDN.getText());
    } catch (final IOException ex) {
        throw ex;
    } catch (final Exception ex) {
        throw WrappedAS2Exception.wrap(ex).setSourceMsg(aMsg);
    }
}
Also used : AS2MessageMDN(com.helger.as2lib.message.AS2MessageMDN) ETriState(com.helger.commons.state.ETriState) InputStream(java.io.InputStream) MIC(com.helger.as2lib.crypto.MIC) NonBlockingByteArrayOutputStream(com.helger.commons.io.stream.NonBlockingByteArrayOutputStream) ICertificateFactory(com.helger.as2lib.cert.ICertificateFactory) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) MessagingException(javax.mail.MessagingException) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) AS2DispositionException(com.helger.as2lib.disposition.AS2DispositionException) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) IOException(java.io.IOException) AS2InvalidParameterException(com.helger.as2lib.params.AS2InvalidParameterException) SMIMEException(org.bouncycastle.mail.smime.SMIMEException) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException) AS2NoModuleException(com.helger.as2lib.processor.AS2NoModuleException) AS2ComponentNotFoundException(com.helger.as2lib.session.AS2ComponentNotFoundException) IMessageMDN(com.helger.as2lib.message.IMessageMDN) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 40 with AS2Exception

use of com.helger.as2lib.exception.AS2Exception in project as2-lib by phax.

the class AS2XMLHelper method createComponent.

@Nonnull
public static <T extends IDynamicComponent> T createComponent(@Nonnull final IMicroElement aElement, @Nonnull final Class<T> aClass, @Nonnull final IAS2Session aSession, @Nullable final String sBaseDirectory) throws AS2Exception {
    ValueEnforcer.notNull(aElement, "Element");
    ValueEnforcer.notNull(aClass, "Class");
    ValueEnforcer.notNull(aSession, "Session");
    // Read 'classname' attribute
    final String sClassName = aElement.getAttributeValue("classname");
    if (sClassName == null)
        throw new AS2Exception("Missing 'classname' attribute");
    try {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Trying to instantiate '" + sClassName + "' as a " + aClass);
        // Instantiate class
        final T aObj = GenericReflection.newInstance(sClassName, aClass);
        if (aObj == null)
            throw new AS2Exception("Failed to instantiate '" + sClassName + "' as " + aClass.getName());
        // Read all parameters
        final StringMap aParameters = AS2XMLHelper.getAllAttrsWithLowercaseName(aElement);
        if (sBaseDirectory != null) {
            // Replace %home% with session base directory
            _updateDirectories(aParameters, sBaseDirectory);
        }
        // Init component
        aObj.initDynamicComponent(aSession, aParameters);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Finished initializing " + aObj);
        return aObj;
    } catch (final AS2Exception ex) {
        throw ex;
    } catch (final Exception ex) {
        throw new AS2Exception("Error creating component: " + sClassName, ex);
    }
}
Also used : StringMap(com.helger.commons.collection.attr.StringMap) AS2Exception(com.helger.as2lib.exception.AS2Exception) AS2Exception(com.helger.as2lib.exception.AS2Exception) Nonnull(javax.annotation.Nonnull)

Aggregations

AS2Exception (com.helger.as2lib.exception.AS2Exception)42 WrappedAS2Exception (com.helger.as2lib.exception.WrappedAS2Exception)23 IOException (java.io.IOException)16 IMicroElement (com.helger.xml.microdom.IMicroElement)8 Nonnull (javax.annotation.Nonnull)8 AS2DispositionException (com.helger.as2lib.disposition.AS2DispositionException)7 AS2NoModuleException (com.helger.as2lib.processor.AS2NoModuleException)7 File (java.io.File)7 MimeBodyPart (javax.mail.internet.MimeBodyPart)7 AS2ComponentNotFoundException (com.helger.as2lib.session.AS2ComponentNotFoundException)6 X509Certificate (java.security.cert.X509Certificate)6 MessagingException (javax.mail.MessagingException)6 ICertificateFactory (com.helger.as2lib.cert.ICertificateFactory)5 IMicroDocument (com.helger.xml.microdom.IMicroDocument)5 InputStream (java.io.InputStream)5 SMIMEException (org.bouncycastle.mail.smime.SMIMEException)5 AS2InvalidParameterException (com.helger.as2lib.params.AS2InvalidParameterException)4 Partnership (com.helger.as2lib.partner.Partnership)4 AS2ProcessorException (com.helger.as2lib.processor.AS2ProcessorException)4 ETriState (com.helger.commons.state.ETriState)4