Search in sources :

Example 1 with MessageParameters

use of com.helger.as2lib.params.MessageParameters in project as2-lib by phax.

the class AS2Message method generateMessageID.

@Override
@Nonnull
@Nonempty
public String generateMessageID() {
    final CompositeParameters aParams = new CompositeParameters(false).add("date", new DateParameters()).add("msg", new MessageParameters(this)).add("rand", new RandomParameters());
    final String sIDFormat = partnership().getMessageIDFormat(DEFAULT_ID_FORMAT);
    final StringBuilder aSB = new StringBuilder();
    aSB.append('<');
    try {
        aSB.append(aParams.format(sIDFormat));
    } catch (final AS2InvalidParameterException ex) {
        // useless, but what to do?
        aSB.append(sIDFormat);
    }
    aSB.append('>');
    return aSB.toString();
}
Also used : CompositeParameters(com.helger.as2lib.params.CompositeParameters) AS2InvalidParameterException(com.helger.as2lib.params.AS2InvalidParameterException) MessageParameters(com.helger.as2lib.params.MessageParameters) DateParameters(com.helger.as2lib.params.DateParameters) RandomParameters(com.helger.as2lib.params.RandomParameters) Nonnull(javax.annotation.Nonnull) Nonempty(com.helger.commons.annotation.Nonempty)

Example 2 with MessageParameters

use of com.helger.as2lib.params.MessageParameters in project as2-lib by phax.

the class MongoDBPartnershipFactory method updatePartnership.

@Override
public void updatePartnership(final IMessage aMsg, final boolean bOverwrite) throws AS2Exception {
    // Fill in any available partnership information
    final Partnership aPartnership = getPartnership(aMsg.partnership());
    m_aLogger.debug("Updating partnership {}", aPartnership);
    // Update partnership data of message with the stored ones
    aMsg.partnership().copyFrom(aPartnership);
    // Set attributes
    if (bOverwrite) {
        final String sSubject = aPartnership.getAttribute(CPartnershipIDs.PA_SUBJECT);
        if (sSubject != null) {
            aMsg.setSubject(new MessageParameters(aMsg).format(sSubject));
        }
    }
}
Also used : Partnership(com.helger.as2lib.partner.Partnership) MessageParameters(com.helger.as2lib.params.MessageParameters)

Example 3 with MessageParameters

use of com.helger.as2lib.params.MessageParameters in project as2-lib by phax.

the class AS2Helper method createMDN.

/**
 * Create a new MDN
 *
 * @param aSession
 *        AS2 session to be used. May not be <code>null</code>.
 * @param aMsg
 *        The source AS2 message for which the MDN is to be created. May not
 *        be <code>null</code>.
 * @param aDisposition
 *        The disposition - either success or error. May not be
 *        <code>null</code>.
 * @param sText
 *        The text to be send. May not be <code>null</code>.
 * @return The created MDN object which is already attached to the passed
 *         source AS2 message.
 * @throws Exception
 *         In case of an error
 */
@Nonnull
public static IMessageMDN createMDN(@Nonnull final IAS2Session aSession, @Nonnull final AS2Message aMsg, @Nonnull final DispositionType aDisposition, @Nonnull final String sText) throws Exception {
    ValueEnforcer.notNull(aSession, "AS2Session");
    ValueEnforcer.notNull(aMsg, "AS2Message");
    ValueEnforcer.notNull(aDisposition, "Disposition");
    ValueEnforcer.notNull(sText, "Text");
    final Partnership aPartnership = aMsg.partnership();
    final AS2MessageMDN aMDN = new AS2MessageMDN(aMsg);
    aMDN.headers().setHeader(CHttpHeader.AS2_VERSION, aSession.getAS2VersionID());
    aMDN.headers().setHeader(CHttpHeader.DATE, AS2DateHelper.getFormattedDateNow(CAS2Header.DEFAULT_DATE_FORMAT));
    aMDN.headers().setHeader(CHttpHeader.SERVER, CAS2Info.NAME_VERSION);
    aMDN.headers().setHeader(CHttpHeader.MIME_VERSION, CAS2Header.DEFAULT_MIME_VERSION);
    aMDN.headers().setHeader(CHttpHeader.AS2_FROM, aPartnership.getReceiverAS2ID());
    aMDN.headers().setHeader(CHttpHeader.AS2_TO, aPartnership.getSenderAS2ID());
    // 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(aPartnership.getReceiverX509Alias());
    aMDN.partnership().setReceiverX509Alias(aPartnership.getSenderX509Alias());
    // Update the partnership
    try {
        aSession.getPartnershipFactory().updatePartnership(aMDN, true);
    } catch (final AS2PartnershipNotFoundException ex) {
    // This would block sending an MDN in case a PartnershipNotFoundException
    // was the reason for sending the MDN :)
    }
    aMDN.headers().setHeader(CHttpHeader.FROM, aPartnership.getReceiverEmail());
    final String sSubject = aMDN.partnership().getMDNSubject();
    if (sSubject != null) {
        aMDN.headers().setHeader(CHttpHeader.SUBJECT, new MessageParameters(aMsg).format(sSubject));
    } else {
        aMDN.headers().setHeader(CHttpHeader.SUBJECT, "Your Requested MDN Response");
    }
    // Content-Transfer-Encoding for outgoing MDNs
    final String sCTE = aPartnership.getContentTransferEncodingSend(EContentTransferEncoding.AS2_DEFAULT.getID());
    aMDN.headers().addHeader(CHttpHeader.CONTENT_TRANSFER_ENCODING, sCTE);
    aMDN.setText(new MessageParameters(aMsg).format(sText));
    aMDN.attrs().putIn(AS2MessageMDN.MDNA_REPORTING_UA, CAS2Info.NAME_VERSION + "@" + aMsg.attrs().getAsString(CNetAttribute.MA_DESTINATION_IP) + ":" + aMsg.attrs().getAsString(CNetAttribute.MA_DESTINATION_PORT));
    aMDN.attrs().putIn(AS2MessageMDN.MDNA_ORIG_RECIPIENT, "rfc822; " + aMsg.getHeader(CHttpHeader.AS2_TO));
    aMDN.attrs().putIn(AS2MessageMDN.MDNA_FINAL_RECIPIENT, "rfc822; " + aPartnership.getReceiverAS2ID());
    aMDN.attrs().putIn(AS2MessageMDN.MDNA_ORIG_MESSAGEID, aMsg.getHeader(CHttpHeader.MESSAGE_ID));
    aMDN.attrs().putIn(AS2MessageMDN.MDNA_DISPOSITION, aDisposition.getAsString());
    final String sDispositionOptions = aMsg.getHeader(CHttpHeader.DISPOSITION_NOTIFICATION_OPTIONS);
    final DispositionOptions aDispositionOptions = DispositionOptions.createFromString(sDispositionOptions);
    ECryptoAlgorithmSign eSigningAlgorithm = aDispositionOptions.getFirstMICAlg();
    if (eSigningAlgorithm == null) {
        // Try from partnership (#93)
        final String sSigningAlgorithm = aPartnership.getSigningAlgorithm();
        eSigningAlgorithm = ECryptoAlgorithmSign.getFromIDOrNull(sSigningAlgorithm);
        if (eSigningAlgorithm == null) {
            if (LOGGER.isWarnEnabled())
                LOGGER.warn("The partnership signing algorithm name '" + sSigningAlgorithm + "' is unknown.");
        }
    }
    MIC aMIC = null;
    if (eSigningAlgorithm != null) {
        // If the source message was signed or encrypted, include the headers -
        // see message sending for details
        final boolean bIncludeHeadersInMIC = aPartnership.getSigningAlgorithm() != null || aPartnership.getEncryptAlgorithm() != null || aPartnership.getCompressionType() != null;
        aMIC = getCryptoHelper().calculateMIC(aMsg.getData(), eSigningAlgorithm, bIncludeHeadersInMIC);
    }
    if (aMIC != null)
        aMDN.attrs().putIn(AS2MessageMDN.MDNA_MIC, aMIC.getAsAS2String());
    boolean bSignMDN = false;
    boolean bIncludeCertificateInSignedContent = false;
    if (aDispositionOptions.getProtocol() != null) {
        if (aDispositionOptions.isProtocolRequired() || aDispositionOptions.hasMICAlg()) {
            // Sign if required or if optional and a MIC algorithm is present
            bSignMDN = true;
            // Include certificate in signed content?
            final ETriState eIncludeCertificateInSignedContent = aPartnership.getIncludeCertificateInSignedContent();
            if (eIncludeCertificateInSignedContent.isDefined()) {
                // Use per partnership
                bIncludeCertificateInSignedContent = eIncludeCertificateInSignedContent.getAsBooleanValue();
            } else {
                // Use global value
                bIncludeCertificateInSignedContent = aSession.isCryptoSignIncludeCertificateInBodyPart();
            }
        }
    }
    final boolean bUseOldRFC3851MicAlgs = aPartnership.isRFC3851MICAlgs();
    final boolean bRemoveCmsAlgorithmProtect = aPartnership.isRemoveCmsAlgorithmProtect();
    createMDNData(aSession, aMDN, bSignMDN, bIncludeCertificateInSignedContent, aDispositionOptions.getFirstMICAlg(), bUseOldRFC3851MicAlgs, bRemoveCmsAlgorithmProtect);
    aMDN.updateMessageID();
    // store MDN into msg in case AsynchMDN is sent fails, needs to be resent by
    // send module
    aMsg.setMDN(aMDN);
    return aMDN;
}
Also used : AS2MessageMDN(com.helger.as2lib.message.AS2MessageMDN) Partnership(com.helger.as2lib.partner.Partnership) ETriState(com.helger.commons.state.ETriState) DispositionOptions(com.helger.as2lib.disposition.DispositionOptions) MIC(com.helger.as2lib.crypto.MIC) MessageParameters(com.helger.as2lib.params.MessageParameters) AS2PartnershipNotFoundException(com.helger.as2lib.partner.AS2PartnershipNotFoundException) ECryptoAlgorithmSign(com.helger.as2lib.crypto.ECryptoAlgorithmSign) Nonnull(javax.annotation.Nonnull)

Example 4 with MessageParameters

use of com.helger.as2lib.params.MessageParameters 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)

Example 5 with MessageParameters

use of com.helger.as2lib.params.MessageParameters in project as2-lib by phax.

the class AbstractActiveNetModule method handleError.

public void handleError(@Nonnull final IMessage aMsg, @Nonnull final AS2Exception aSrcEx) {
    if (LOGGER.isTraceEnabled())
        LOGGER.trace("Handling error in " + ClassHelper.getClassLocalName(this.getClass()) + " for message with ID " + aMsg.getMessageID() + " and exception " + ClassHelper.getClassLocalName(aSrcEx.getClass()) + " with error " + aSrcEx.getMessage());
    aSrcEx.terminate(aMsg);
    try {
        final CompositeParameters aParams = new CompositeParameters(false).add("date", new DateParameters()).add("msg", new MessageParameters(aMsg));
        final String sErrorFilename = aParams.format(getErrorFormat());
        final String sErrorDirectory = aParams.format(getErrorDirectory());
        if (StringHelper.hasText(sErrorDirectory)) {
            final File aMsgErrorFile = AS2IOHelper.getUniqueFile(AS2IOHelper.getDirectoryFile(sErrorDirectory), FilenameHelper.getAsSecureValidFilename(sErrorFilename));
            // Default false for backwards compatibility reason
            final boolean bStoreBody = isErrorStoreBody();
            try (final OutputStream aFOS = FileHelper.getOutputStream(aMsgErrorFile)) {
                final String sMsgText = aMsg.getAsString();
                aFOS.write(sMsgText.getBytes());
                // Also store the body of the source message?
                if (bStoreBody)
                    StreamHelper.copyInputStreamToOutputStream(aMsg.getData().getInputStream(), aFOS);
            }
            // make sure an error of this event is logged
            new AS2InvalidMessageException("Stored invalid message to " + aMsgErrorFile.getAbsolutePath()).terminate();
        } else {
            LOGGER.warn("No error directory present, so ignoring the error");
        }
    } catch (final Exception ex) {
        WrappedAS2Exception.wrap(ex).terminate(aMsg);
    }
}
Also used : CompositeParameters(com.helger.as2lib.params.CompositeParameters) OutputStream(java.io.OutputStream) MessageParameters(com.helger.as2lib.params.MessageParameters) DateParameters(com.helger.as2lib.params.DateParameters) File(java.io.File) AS2Exception(com.helger.as2lib.exception.AS2Exception) WrappedAS2Exception(com.helger.as2lib.exception.WrappedAS2Exception) IOException(java.io.IOException)

Aggregations

MessageParameters (com.helger.as2lib.params.MessageParameters)6 CompositeParameters (com.helger.as2lib.params.CompositeParameters)3 DateParameters (com.helger.as2lib.params.DateParameters)3 AS2Exception (com.helger.as2lib.exception.AS2Exception)2 WrappedAS2Exception (com.helger.as2lib.exception.WrappedAS2Exception)2 AS2InvalidParameterException (com.helger.as2lib.params.AS2InvalidParameterException)2 Partnership (com.helger.as2lib.partner.Partnership)2 File (java.io.File)2 IOException (java.io.IOException)2 Nonnull (javax.annotation.Nonnull)2 ECryptoAlgorithmSign (com.helger.as2lib.crypto.ECryptoAlgorithmSign)1 MIC (com.helger.as2lib.crypto.MIC)1 DispositionOptions (com.helger.as2lib.disposition.DispositionOptions)1 AS2MessageMDN (com.helger.as2lib.message.AS2MessageMDN)1 IMessage (com.helger.as2lib.message.IMessage)1 RandomParameters (com.helger.as2lib.params.RandomParameters)1 AS2PartnershipNotFoundException (com.helger.as2lib.partner.AS2PartnershipNotFoundException)1 Nonempty (com.helger.commons.annotation.Nonempty)1 FileIOError (com.helger.commons.io.file.FileIOError)1 ETriState (com.helger.commons.state.ETriState)1