Search in sources :

Example 16 with AS2Exception

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

the class AS2SenderModule method _sendViaHTTP.

private void _sendViaHTTP(@Nonnull final AS2Message aMsg, @Nonnull final MimeBodyPart aSecuredMimePart, @Nullable final MIC aMIC, @Nullable final EContentTransferEncoding eCTE, @Nullable final IHTTPOutgoingDumper aOutgoingDumper, @Nullable final IHTTPIncomingDumper aIncomingDumper, @Nonnull final AS2ResourceHelper aResHelper) throws AS2Exception, IOException, MessagingException {
    final Partnership aPartnership = aMsg.partnership();
    // Create the HTTP connection
    final String sUrl = aPartnership.getAS2URL();
    final EHttpMethod eRequestMethod = EHttpMethod.POST;
    // decide on the connection type to use according to the MimeBodyPart:
    // If it contains the data, (and no DataHandler), then use HttpUrlClient,
    // otherwise, use HttpClient
    final AS2HttpClient aConn = getHttpClient(sUrl, eRequestMethod, getSession().getHttpProxy());
    try {
        if (aOutgoingDumper != null)
            aOutgoingDumper.start(sUrl, aMsg);
        if (LOGGER.isInfoEnabled())
            LOGGER.info("Connecting to " + sUrl + aMsg.getLoggingText());
        final boolean bQuoteHeaderValues = isQuoteHeaderValues();
        updateHttpHeaders(new AS2HttpHeaderSetter(aConn, aOutgoingDumper, bQuoteHeaderValues), aMsg);
        if (aOutgoingDumper != null)
            aOutgoingDumper.finishedHeaders();
        aMsg.attrs().putIn(CNetAttribute.MA_DESTINATION_IP, aConn.getURL().getHost());
        aMsg.attrs().putIn(CNetAttribute.MA_DESTINATION_PORT, aConn.getURL().getPort());
        final InputStream aMsgIS = aSecuredMimePart.getInputStream();
        // Transfer the data
        final StopWatch aSW = StopWatch.createdStarted();
        final long nBytes = aConn.send(aMsgIS, eCTE, aOutgoingDumper, aResHelper);
        aSW.stop();
        if (LOGGER.isInfoEnabled())
            LOGGER.info("AS2 Message transferred " + AS2IOHelper.getTransferRate(nBytes, aSW) + aMsg.getLoggingText());
        if (aOutgoingDumper != null)
            aOutgoingDumper.finishedPayload();
        final int nHttpResponseCode = aConn.getResponseCode();
        if (getOutgoingHttpCallback() != null)
            getOutgoingHttpCallback().onOutgoingHttpMessage(true, aMsg.getAS2From(), aMsg.getAS2To(), aMsg.getMessageID(), aMIC == null ? null : aMIC.getClone(), eCTE, sUrl, nHttpResponseCode);
        // Check the HTTP Response code
        if (AS2HttpClient.isErrorResponseCode(nHttpResponseCode)) {
            if (LOGGER.isErrorEnabled())
                LOGGER.error("Error URL '" + sUrl + "' - HTTP " + nHttpResponseCode + " " + aConn.getResponseMessage() + " " + aMsg.getLoggingText());
            throw new AS2HttpResponseException(sUrl, nHttpResponseCode, aConn.getResponseMessage());
        }
        // Receive an MDN
        try {
            // Receive an MDN
            if (aMsg.isRequestingMDN()) {
                // Check if the AsyncMDN is required
                if (aPartnership.getAS2ReceiptDeliveryOption() == null) {
                    // Note: If an MDN is requested, a MIC is present
                    assert aMIC != null;
                    receiveSyncMDN(aMsg, aConn, aMIC, aIncomingDumper, aResHelper);
                    if (LOGGER.isInfoEnabled())
                        LOGGER.info("message sent" + aMsg.getLoggingText());
                }
            }
        } catch (final AS2DispositionException ex) {
            // was not successful
            throw ex;
        } catch (final AS2Exception ex) {
            // Don't re-send or fail, just log an error if one occurs while
            // receiving the MDN
            onReceivedMDNError(aMsg, ex);
        }
    } finally {
        // Closes all resources
        aConn.disconnect();
    }
}
Also used : InputStream(java.io.InputStream) StopWatch(com.helger.commons.timing.StopWatch) AS2DispositionException(com.helger.as2lib.disposition.AS2DispositionException) AS2HttpHeaderSetter(com.helger.as2lib.util.http.AS2HttpHeaderSetter) Partnership(com.helger.as2lib.partner.Partnership) EHttpMethod(com.helger.commons.http.EHttpMethod) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) AS2HttpClient(com.helger.as2lib.util.http.AS2HttpClient)

Example 17 with AS2Exception

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

the class MessageFileModule method handle.

public void handle(@Nonnull final String sAction, @Nonnull final IMessage aMsg, @Nullable final Map<String, Object> aOptions) throws AS2Exception {
    // store message content
    try {
        final File aMsgFile = getFile(aMsg, getAttributeAsStringRequired(ATTR_FILENAME));
        try (final InputStream aIS = aMsg.getData().getInputStream()) {
            store(aMsgFile, aIS);
        }
        aMsg.attrs().put(MessageParameters.ATTR_STORED_FILE_NAME, aMsgFile.getAbsolutePath());
        LOGGER.info("stored message to " + aMsgFile.getAbsolutePath() + aMsg.getLoggingText());
    } catch (final AS2DispositionException ex) {
        // Re-throw "as is"
        throw ex;
    } catch (final Exception ex) {
        throw AS2DispositionException.wrap(ex, () -> DispositionType.createError("error-storing-transaction"), () -> AbstractActiveNetModule.DISP_STORAGE_FAILED);
    }
    // Store message headers and attributes
    final String sHeaderFilename = getHeaderFilename();
    if (sHeaderFilename != null) {
        try {
            final File aHeaderFile = getFile(aMsg, sHeaderFilename);
            try (final InputStream aIS = getHeaderStream(aMsg, getCharset())) {
                store(aHeaderFile, aIS);
            }
            LOGGER.info("stored headers to " + aHeaderFile.getAbsolutePath() + aMsg.getLoggingText());
        } catch (final IOException ex) {
            throw WrappedAS2Exception.wrap(ex);
        }
    }
}
Also used : AS2DispositionException(com.helger.as2lib.disposition.AS2DispositionException) StringInputStream(com.helger.commons.io.stream.StringInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) File(java.io.File) AS2DispositionException(com.helger.as2lib.disposition.AS2DispositionException) IOException(java.io.IOException) AS2InvalidParameterException(com.helger.as2lib.params.AS2InvalidParameterException) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception)

Example 18 with AS2Exception

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

the class AS2HttpClient method getResponseHeaderFields.

@Nonnull
@ReturnsMutableCopy
public HttpHeaderMap getResponseHeaderFields() throws AS2Exception {
    // message was not sent yet, not response
    if (m_aCloseableHttpResponse == null)
        throw new AS2Exception("No response as message was yet sent");
    final Header[] aHeaders = m_aCloseableHttpResponse.getAllHeaders();
    final HttpHeaderMap ret = new HttpHeaderMap();
    for (final Header aHeader : aHeaders) ret.addHeader(aHeader.getName(), aHeader.getValue());
    return ret;
}
Also used : HttpHeaderMap(com.helger.commons.http.HttpHeaderMap) Header(org.apache.http.Header) AS2Exception(com.helger.as2lib.exception.AS2Exception) ReturnsMutableCopy(com.helger.commons.annotation.ReturnsMutableCopy) Nonnull(javax.annotation.Nonnull)

Example 19 with AS2Exception

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

the class DirectoryResenderModule method resendFile.

protected void resendFile(@Nonnull final File aFile) throws AS2Exception {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Processing " + aFile.getAbsolutePath());
    final CompositeParameters aParams = new CompositeParameters(false).add("date", new DateParameters());
    IMessage aMsg = null;
    try {
        try {
            final String sResendAction;
            String sRetries;
            try (final FileInputStream aFIS = new FileInputStream(aFile);
                final ObjectInputStream aOIS = new ObjectInputStream(aFIS)) {
                sResendAction = (String) aOIS.readObject();
                sRetries = (String) aOIS.readObject();
                aMsg = (IMessage) aOIS.readObject();
            }
            // Decrement retries
            sRetries = Integer.toString(Integer.parseInt(sRetries) - 1);
            // 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, sRetries);
            getSession().getMessageProcessor().handle(sResendAction, aMsg, aOptions);
            if (AS2IOHelper.getFileOperationManager().deleteFile(aFile).isFailure()) {
                // again
                throw new AS2Exception("File was successfully sent but not deleted: " + aFile.getAbsolutePath());
            }
            if (LOGGER.isInfoEnabled())
                LOGGER.info("deleted " + aFile.getAbsolutePath() + aMsg.getLoggingText());
        } catch (final IOException | ClassNotFoundException ex) {
            // caught 3 lines below
            throw WrappedAS2Exception.wrap(ex);
        }
    } catch (final AS2Exception ex) {
        ex.terminate(aFile, aMsg);
        final String sErrorDirectory = aParams.format(getAttributeAsStringRequired(ATTR_ERROR_DIRECTORY));
        // Use the source name as the default
        final String sErrorFilename = StringHelper.getNotEmpty(aParams.format(attrs().getAsString(ATTR_STORED_ERROR_FILENAME)), aFile.getName());
        AS2IOHelper.handleError(aFile, sErrorDirectory, sErrorFilename);
    }
}
Also used : IMessage(com.helger.as2lib.message.IMessage) DateParameters(com.helger.as2lib.params.DateParameters) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) CompositeParameters(com.helger.as2lib.params.CompositeParameters) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) CommonsHashMap(com.helger.commons.collection.impl.CommonsHashMap) ObjectInputStream(java.io.ObjectInputStream)

Example 20 with AS2Exception

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

the class AbstractDirectoryPollingModule method processFile.

protected void processFile(@Nonnull final File aFile) throws AS2Exception {
    LOGGER.info("processing " + aFile.getAbsolutePath());
    final IMessage aMsg = createMessage();
    aMsg.attrs().putIn(CFileAttribute.MA_FILEPATH, aFile.getAbsolutePath());
    aMsg.attrs().putIn(CFileAttribute.MA_FILENAME, aFile.getName());
    /*
     * asynch mdn logic 2007-03-12 save the file name into message object, it
     * will be stored into pending information file
     */
    aMsg.attrs().putIn(CFileAttribute.MA_PENDING_FILENAME, aFile.getName());
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("AS2Message was created");
    final CompositeParameters aParams = new CompositeParameters(false).add("date", new DateParameters()).add("msg", new MessageParameters(aMsg));
    try {
        updateMessage(aMsg, aFile);
        LOGGER.info("file assigned to message " + aFile.getAbsolutePath() + aMsg.getLoggingText());
        if (aMsg.getData() == null)
            throw new AS2InvalidMessageException("No Data");
        // Transmit the message - requires a module installed that implements the
        // "send" action (like com.helger.as2lib.processor.sender.AS2SenderModule)
        getSession().getMessageProcessor().handle(IProcessorSenderModule.DO_SEND, aMsg, null);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("AS2Message was successfully handled my the MessageProcessor");
        /*
       * asynch mdn logic 2007-03-12 If the return status is pending in msg's
       * attribute "status" then copy the transmitted file to pending folder and
       * wait for the receiver to make another HTTP call to post AsyncMDN
       */
        if (CFileAttribute.MA_STATUS_PENDING.equals(aMsg.attrs().getAsString(CFileAttribute.MA_STATUS))) {
            // Copy the file to the pending folder
            final String sFolderName = AS2IOHelper.getSafeFileAndFolderName(aMsg.partnership().getAttribute(CFileAttribute.MA_STATUS_PENDING));
            final String sFilename = FilenameHelper.getAsSecureValidASCIIFilename(aMsg.attrs().getAsString(CFileAttribute.MA_PENDING_FILENAME));
            final File aPendingFile = new File(sFolderName, sFilename);
            final FileIOError aIOErr = AS2IOHelper.getFileOperationManager().copyFile(aFile, aPendingFile);
            if (aIOErr.isFailure())
                throw new AS2Exception("File was successfully sent but not copied to pending folder: " + aPendingFile + " - " + aIOErr.toString());
            LOGGER.info("Copied '" + aFile.getAbsolutePath() + "' to pending folder '" + aPendingFile.getAbsolutePath() + "'" + aMsg.getLoggingText());
        }
        if (attrs().containsKey(ATTR_SENT_DIRECTORY)) {
            // If the Sent Directory option is set, move the transmitted file to
            // the sent directory
            File aSentFile = null;
            try {
                final String sSentDirectory = AS2IOHelper.getSafeFileAndFolderName(aParams.format(attrs().getAsString(ATTR_SENT_DIRECTORY)));
                // Default to the original filename
                final String sSentFilename = StringHelper.getNotEmpty(FilenameHelper.getAsSecureValidASCIIFilename(aParams.format(attrs().getAsString(ATTR_STORED_SENT_FILENAME))), aFile.getName());
                aSentFile = new File(AS2IOHelper.getDirectoryFile(sSentDirectory), sSentFilename);
                aSentFile = AS2IOHelper.moveFile(aFile, aSentFile, false, true);
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("Moved '" + aFile.getAbsolutePath() + "' to '" + aSentFile.getAbsolutePath() + "'" + aMsg.getLoggingText());
            } catch (final IOException ex) {
                new AS2Exception("File was successfully sent but not moved to sent folder: '" + aSentFile.getAbsolutePath() + "'", ex).terminate();
            }
        } else {
            // The "Sent Directory" option was not set - so delete the file
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Trying to delete file " + aFile.getAbsolutePath());
            if (AS2IOHelper.getFileOperationManager().deleteFileIfExisting(aFile).isFailure()) {
                // Delete the file if a sent directory isn't set
                throw new AS2Exception("File was successfully sent but not deleted: '" + aFile.getAbsolutePath() + "'");
            }
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Deleted file '" + aFile.getAbsolutePath() + "'" + aMsg.getLoggingText());
        }
    } catch (final AS2Exception ex) {
        ex.terminate(aFile, aMsg);
        final String sErrorDirectory = AS2IOHelper.getSafeFileAndFolderName(aParams.format(getAttributeAsStringRequired(ATTR_ERROR_DIRECTORY)));
        // Use the source name as the default
        final String sErrorFilename = StringHelper.getNotEmpty(FilenameHelper.getAsSecureValidASCIIFilename(aParams.format(attrs().getAsString(ATTR_STORED_ERROR_FILENAME))), aFile.getName());
        AS2IOHelper.handleError(aFile, sErrorDirectory, sErrorFilename);
    }
}
Also used : CompositeParameters(com.helger.as2lib.params.CompositeParameters) FileIOError(com.helger.commons.io.file.FileIOError) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) IMessage(com.helger.as2lib.message.IMessage) MessageParameters(com.helger.as2lib.params.MessageParameters) DateParameters(com.helger.as2lib.params.DateParameters) IOException(java.io.IOException) File(java.io.File)

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