Search in sources :

Example 31 with AS2Exception

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

the class DispositionOptions method createFromString.

/**
 * Parse Strings like <code>signed-receipt-protocol=optional, pkcs7-signature;
 * signed-receipt-micalg=optional, sha1</code>
 *
 * @param sOptions
 *        The string to parse. May be <code>null</code> in which case an empty
 *        object will be returned.
 * @return Never <code>null</code>.
 * @throws AS2Exception
 *         In the very unlikely case of a programming error in
 *         {@link StringTokenizer}.
 */
@Nonnull
public static DispositionOptions createFromString(@Nullable final String sOptions) throws AS2Exception {
    final DispositionOptions ret = new DispositionOptions();
    if (StringHelper.hasTextAfterTrim(sOptions)) {
        try {
            // Split options into parameters by ";"
            for (final String sParameter : StringHelper.getExplodedArray(';', sOptions.trim())) {
                // Split parameter into name and value by "="
                final String[] aParts = StringHelper.getExplodedArray('=', sParameter.trim(), 2);
                if (aParts.length == 2) {
                    final String sAttribute = aParts[0].trim();
                    // Split the value into importance and the main values by ","
                    final String[] aValues = StringHelper.getExplodedArray(',', aParts[1].trim(), 2);
                    if (aValues.length == 2) {
                        if (sAttribute.equalsIgnoreCase(SIGNED_RECEIPT_PROTOCOL)) {
                            ret.setProtocolImportance(aValues[0].trim());
                            ret.setProtocol(aValues[1].trim());
                        } else if (sAttribute.equalsIgnoreCase(SIGNED_RECEIPT_MICALG)) {
                            ret.setMICAlgImportance(aValues[0].trim());
                            ret.setMICAlg(aValues[1].trim());
                        } else {
                            if (LOGGER.isWarnEnabled())
                                LOGGER.warn("Unsupported disposition attribute '" + sAttribute + "' with value '" + aParts[1].trim() + "' found!");
                        }
                    } else {
                        if (LOGGER.isWarnEnabled())
                            LOGGER.warn("Failed to split disposition options parameter '" + sParameter + "' value '" + aParts[1].trim() + "' into importance and values");
                    }
                } else {
                    if (LOGGER.isWarnEnabled())
                        LOGGER.warn("Failed to split disposition options parameter '" + sParameter + "' into attribute and values");
                }
            }
        } catch (final NoSuchElementException ex) {
            throw new AS2Exception("Invalid disposition options format: " + sOptions);
        }
    }
    return ret;
}
Also used : AS2Exception(com.helger.as2lib.exception.AS2Exception) NoSuchElementException(java.util.NoSuchElementException) Nonnull(javax.annotation.Nonnull)

Example 32 with AS2Exception

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

the class DispositionType method createFromString.

@Nonnull
public static DispositionType createFromString(@Nullable final String sDisposition) throws AS2Exception {
    if (StringHelper.hasNoText(sDisposition))
        throw new AS2Exception("Disposition type is empty");
    try {
        final StringTokenizer aDispTokens = new StringTokenizer(sDisposition, "/;:", false);
        final String sAction = aDispTokens.nextToken().toLowerCase(Locale.US);
        final String sMDNAction = aDispTokens.nextToken().toLowerCase(Locale.US);
        final String sStatus = aDispTokens.nextToken().trim().toLowerCase(Locale.US);
        String sStatusModifier = null;
        String sStatusDescription = null;
        if (aDispTokens.hasMoreTokens()) {
            sStatusModifier = aDispTokens.nextToken().trim().toLowerCase(Locale.US);
            if (aDispTokens.hasMoreTokens())
                sStatusDescription = aDispTokens.nextToken().trim().toLowerCase(Locale.US);
        }
        return new DispositionType(sAction, sMDNAction, sStatus, sStatusModifier, sStatusDescription);
    } catch (final NoSuchElementException ex) {
        throw new AS2Exception("Invalid disposition type format '" + sDisposition + "'", ex);
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) AS2Exception(com.helger.as2lib.exception.AS2Exception) NoSuchElementException(java.util.NoSuchElementException) Nonnull(javax.annotation.Nonnull)

Example 33 with AS2Exception

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

the class XMLPartnershipFactory method loadPartnerIDs.

protected void loadPartnerIDs(@Nonnull final IMicroElement ePartnership, @Nonnull final IPartnerMap aAllPartners, @Nonnull final Partnership aPartnership, final boolean bIsSender) throws AS2Exception {
    final String sPartnerType = bIsSender ? "sender" : "receiver";
    final IMicroElement ePartner = ePartnership.getFirstChildElement(sPartnerType);
    if (ePartner == null)
        throw new AS2Exception("Partnership '" + aPartnership.getName() + "' is missing '" + sPartnerType + "' child element");
    final IStringMap aPartnerAttrs = AS2XMLHelper.getAllAttrsWithLowercaseName(ePartner);
    // check for a partner name, and look up in partners list if one is found
    final String sPartnerName = aPartnerAttrs.getAsString(ATTR_PARTNER_NAME);
    if (sPartnerName != null) {
        // Resolve name from existing partners
        final IPartner aPartner = aAllPartners.getPartnerOfName(sPartnerName);
        if (aPartner == null) {
            throw new AS2Exception("Partnership '" + aPartnership.getName() + "' has a non-existing " + sPartnerType + " partner: '" + sPartnerName + "'");
        }
        // Set all attributes from the stored partner
        if (bIsSender)
            aPartnership.addSenderIDs(aPartner.getAllAttributes());
        else
            aPartnership.addReceiverIDs(aPartner.getAllAttributes());
    }
    // the ones present in the partner element
    if (bIsSender)
        aPartnership.addSenderIDs(aPartnerAttrs);
    else
        aPartnership.addReceiverIDs(aPartnerAttrs);
}
Also used : AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) IMicroElement(com.helger.xml.microdom.IMicroElement) IStringMap(com.helger.commons.collection.attr.IStringMap)

Example 34 with AS2Exception

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

the class AS2SenderModule method handle.

public void handle(@Nonnull final String sAction, @Nonnull final IMessage aBaseMsg, @Nullable final Map<String, Object> aOptions) throws AS2Exception {
    final AS2Message aMsg = (AS2Message) aBaseMsg;
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Submitting message" + aMsg.getLoggingText());
    // verify all required information is present for sending
    checkRequired(aMsg);
    final int nRetries = getRetryCount(aMsg.partnership(), aOptions);
    try (final AS2ResourceHelper aResHelper = new AS2ResourceHelper()) {
        // Get Content-Transfer-Encoding to use
        final String sContentTransferEncoding = aMsg.partnership().getContentTransferEncodingSend(EContentTransferEncoding.AS2_DEFAULT.getID());
        final EContentTransferEncoding eCTE = EContentTransferEncoding.getFromIDCaseInsensitiveOrDefault(sContentTransferEncoding, EContentTransferEncoding.AS2_DEFAULT);
        // compress and/or sign and/or encrypt the message if needed
        final MimeBodyPart aSecuredData = secure(aMsg, eCTE);
        // Calculate MIC after compress/sign/crypt was handled, because the
        // message data might change if compression before signing is active.
        final MIC aMIC;
        if (aMsg.isRequestingMDN())
            aMIC = calculateAndStoreMIC(aMsg);
        else
            aMIC = null;
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Setting message content type to '" + aSecuredData.getContentType() + "'");
        aMsg.setContentType(aSecuredData.getContentType());
        try (final IHTTPOutgoingDumper aOutgoingDumper = getHttpOutgoingDumper(aMsg)) {
            final IHTTPIncomingDumper aIncomingDumper = getEffectiveHttpIncomingDumper();
            // Use no CTE, because it was set on all MIME parts
            _sendViaHTTP(aMsg, aSecuredData, aMIC, true ? null : eCTE, aOutgoingDumper, aIncomingDumper, aResHelper);
        }
    } catch (final AS2HttpResponseException ex) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error("Http Response Error " + ex.getMessage());
        ex.terminate(aMsg);
        if (!doResend(IProcessorSenderModule.DO_SEND, aMsg, ex, nRetries))
            throw ex;
    } catch (final IOException ex) {
        // Re-send if a network error occurs during transmission
        final AS2Exception wioe = WrappedAS2Exception.wrap(ex).setSourceMsg(aMsg).terminate();
        if (!doResend(IProcessorSenderModule.DO_SEND, aMsg, wioe, nRetries))
            throw wioe;
    } catch (final Exception ex) {
        // Propagate error if it can't be handled by a re-send
        throw WrappedAS2Exception.wrap(ex);
    }
}
Also used : EContentTransferEncoding(com.helger.mail.cte.EContentTransferEncoding) MIC(com.helger.as2lib.crypto.MIC) IHTTPOutgoingDumper(com.helger.as2lib.util.dump.IHTTPOutgoingDumper) IOException(java.io.IOException) 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) IHTTPIncomingDumper(com.helger.as2lib.util.dump.IHTTPIncomingDumper) AS2ResourceHelper(com.helger.as2lib.util.AS2ResourceHelper) AS2Message(com.helger.as2lib.message.AS2Message) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 35 with AS2Exception

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

the class AbstractHttpSenderModule method getHttpClient.

/**
 * Generate a HttpClient connection. It works with streams and avoids holding
 * whole message in memory. note that bOutput, bInput, and bUseCaches are not
 * supported
 *
 * @param sUrl
 *        URL to connect to
 * @param eRequestMethod
 *        HTTP Request method to use. May not be <code>null</code>.
 * @param aProxy
 *        Optional proxy to use. May be <code>null</code>.
 * @return a {@link AS2HttpClient} object to work with
 * @throws AS2Exception
 *         If something goes wrong
 */
@Nonnull
public AS2HttpClient getHttpClient(@Nonnull @Nonempty final String sUrl, @Nonnull final EHttpMethod eRequestMethod, @Nullable final Proxy aProxy) throws AS2Exception {
    ValueEnforcer.notEmpty(sUrl, "URL");
    final SSLContext aSSLCtx;
    final HostnameVerifier aHV;
    if (isUseSSL(sUrl)) {
        // Create SSL context and HostnameVerifier
        try {
            aSSLCtx = createSSLContext();
        } catch (final GeneralSecurityException ex) {
            throw new AS2Exception("Error creating SSL Context", ex);
        }
        aHV = createHostnameVerifier();
    } else {
        aSSLCtx = null;
        aHV = null;
    }
    final int nConnectTimeoutMS = getConnectionTimeoutMilliseconds();
    final int nReadTimeoutMS = getReadTimeoutMilliseconds();
    return new AS2HttpClient(sUrl, nConnectTimeoutMS, nReadTimeoutMS, eRequestMethod, aProxy, aSSLCtx, aHV);
}
Also used : AS2Exception(com.helger.as2lib.exception.AS2Exception) GeneralSecurityException(java.security.GeneralSecurityException) SSLContext(javax.net.ssl.SSLContext) HostnameVerifier(javax.net.ssl.HostnameVerifier) AS2HttpClient(com.helger.as2lib.util.http.AS2HttpClient) 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