Search in sources :

Example 11 with NHINDAddress

use of org.nhindirect.stagent.NHINDAddress in project nhin-d by DirectProject.

the class DirectXdMailet method service.

/*
     * (non-Javadoc)
     * 
     * @see org.apache.mailet.base.GenericMailet#service(org.apache.mailet.Mail)
     */
@Override
public void service(Mail mail) throws MessagingException {
    LOGGER.info("Servicing DirectXdMailet");
    if (StringUtils.isBlank(endpointUrl)) {
        LOGGER.error("DirectXdMailet endpoint URL cannot be empty or null.");
        throw new MessagingException("DirectXdMailet endpoint URL cannot be empty or null.");
    }
    boolean successfulTransaction = false;
    final MimeMessage msg = mail.getMessage();
    final boolean isReliableAndTimely = TxUtil.isReliableAndTimelyRequested(msg);
    final NHINDAddressCollection initialRecipients = getMailRecipients(mail);
    final NHINDAddressCollection xdRecipients = new NHINDAddressCollection();
    final NHINDAddress sender = getMailSender(mail);
    Tx txToTrack = null;
    // Get recipients and create a collection of Strings
    final List<String> recipAddresses = new ArrayList<String>();
    for (NHINDAddress addr : initialRecipients) {
        recipAddresses.add(addr.getAddress());
    }
    // Service XD* addresses
    if (getResolver().hasXdEndpoints(recipAddresses)) {
        LOGGER.info("Recipients include XD endpoints");
        try {
            //List<Address> xdAddresses = new ArrayList<Address>();
            for (String s : getResolver().getXdEndpoints(recipAddresses)) {
                //xdAddresses.add((new MailAddress(s)).toInternetAddress());
                xdRecipients.add(new NHINDAddress(s));
            }
            txToTrack = this.getTxToTrack(msg, sender, xdRecipients);
            // Replace recipients with only XD* addresses
            //msg.setRecipients(RecipientType.TO, xdAddresses.toArray(new Address[0]));
            msg.setRecipients(RecipientType.TO, xdRecipients.toArray(new Address[0]));
            // Transform MimeMessage into ProvideAndRegisterDocumentSetRequestType object
            ProvideAndRegisterDocumentSetRequestType request = getMimeXDSTransformer().transform(msg);
            for (String directTo : recipAddresses) {
                String response = getDocumentRepository().forwardRequest(endpointUrl, request, directTo, sender.toString());
                if (!isSuccessful(response)) {
                    LOGGER.error("DirectXdMailet failed to deliver XD message.");
                    LOGGER.error(response);
                } else {
                    successfulTransaction = true;
                    if (isReliableAndTimely && txToTrack != null && txToTrack.getMsgType() == TxMessageType.IMF) {
                        // send MDN dispatch for messages the recipients that were successful
                        final Collection<NotificationMessage> notifications = notificationProducer.produce(new Message(msg), xdRecipients.toInternetAddressCollection());
                        if (notifications != null && notifications.size() > 0) {
                            LOGGER.debug("Sending MDN \"dispathed\" messages");
                            // create a message for each notification and put it on James "stack"
                            for (NotificationMessage message : notifications) {
                                try {
                                    getMailetContext().sendMail(message);
                                } catch (Throwable t) {
                                    // don't kill the process if this fails
                                    LOGGER.error("Error sending MDN dispatched message.", t);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Throwable e) {
            LOGGER.error("DirectXdMailet delivery failure", e);
        }
    }
    // this basically sets the message back to it's original state with SMTP addresses only
    if (getResolver().hasSmtpEndpoints(recipAddresses)) {
        LOGGER.info("Recipients include SMTP endpoints");
        mail.setRecipients(getSmtpRecips(recipAddresses));
    } else {
        LOGGER.info("Recipients do not include SMTP endpoints");
        // No SMTP addresses, ghost it
        mail.setState(Mail.GHOST);
    }
    if (!successfulTransaction) {
        if (txToTrack != null && txToTrack.getMsgType() == TxMessageType.IMF) {
            // for good measure, send DSN messages back to the original sender on failure
            // create a DSN message
            this.sendDSN(txToTrack, xdRecipients, false);
        }
    }
}
Also used : Tx(org.nhindirect.common.tx.model.Tx) Address(javax.mail.Address) MailAddress(org.apache.mailet.MailAddress) NHINDAddress(org.nhindirect.stagent.NHINDAddress) NotificationMessage(org.nhindirect.stagent.mail.notifications.NotificationMessage) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) ArrayList(java.util.ArrayList) NHINDAddress(org.nhindirect.stagent.NHINDAddress) NotificationMessage(org.nhindirect.stagent.mail.notifications.NotificationMessage) MimeMessage(javax.mail.internet.MimeMessage) ProvideAndRegisterDocumentSetRequestType(ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType)

Example 12 with NHINDAddress

use of org.nhindirect.stagent.NHINDAddress in project nhin-d by DirectProject.

the class TrustModel method enforce.

/**
     * Enforces the trust policy an incoming message.  Each domain recipient's trust status is set according the models trust policy. 
     */
public void enforce(IncomingMessage message) {
    if (message == null)
        throw new IllegalArgumentException();
    if (!message.hasSignatures())
        throw new AgentException(AgentError.UntrustedMessage);
    findSenderSignatures(message);
    if (!message.hasSenderSignatures())
        throw new AgentException(AgentError.MissingSenderSignature);
    // 
    // For each domain recipient, find at least one valid sender signature that the recipient trusts
    // the default value of the trust status is false, so only change the status if a trusted
    // certificate is found
    //        
    NHINDAddressCollection recipients = message.getDomainRecipients();
    for (NHINDAddress recipient : recipients) {
        recipient.setStatus(TrustEnforcementStatus.Failed);
        // be a bogus recipient
        if (recipient.getCertificates() != null) {
            // Find a trusted signature
            DefaultMessageSignatureImpl trustedSignature = findTrustedSignature(message, recipient, recipient.getTrustAnchors());
            // verify the signature
            if (trustedSignature != null) {
                recipient.setStatus(trustedSignature.isThumbprintVerified() ? TrustEnforcementStatus.Success : TrustEnforcementStatus.Success_ThumbprintMismatch);
            } else {
                LOGGER.warn("enforce(IncomingMessage message) - could not find a trusted certificate for recipient " + recipient.getAddress());
            }
        } else {
            LOGGER.warn("enforce(IncomingMessage message) - recipient " + recipient.getAddress() + " does not have a bound certificate");
        }
    }
}
Also used : NHINDAddress(org.nhindirect.stagent.NHINDAddress) DefaultMessageSignatureImpl(org.nhindirect.stagent.DefaultMessageSignatureImpl) AgentException(org.nhindirect.stagent.AgentException) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection)

Example 13 with NHINDAddress

use of org.nhindirect.stagent.NHINDAddress in project nhin-d by DirectProject.

the class TrustModel method enforce.

/**
     * {@inheritDoc}}
     */
public void enforce(OutgoingMessage message) {
    if (message == null) {
        throw new IllegalArgumentException();
    }
    NHINDAddress sender = message.getSender();
    NHINDAddressCollection recipients = message.getRecipients();
    for (NHINDAddress recipient : recipients) {
        recipient.setStatus(TrustEnforcementStatus.Failed);
        Collection<X509Certificate> certs = recipient.getCertificates();
        if (certs == null || certs.size() == 0)
            LOGGER.warn("enforce(OutgoingMessage message) - recipient " + recipient.getAddress() + " has no bound certificates");
        recipient.setCertificates(findTrustedCerts(certs, sender.getTrustAnchors()));
        if (recipient.hasCertificates())
            recipient.setStatus(TrustEnforcementStatus.Success);
        else
            LOGGER.warn("enforce(OutgoingMessage message) - could not trust any certificates for recipient " + recipient.getAddress());
    }
}
Also used : NHINDAddress(org.nhindirect.stagent.NHINDAddress) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) X509Certificate(java.security.cert.X509Certificate)

Example 14 with NHINDAddress

use of org.nhindirect.stagent.NHINDAddress in project nhin-d by DirectProject.

the class AbstractDSNCreator method createDSNFailure.

@Override
public MimeMessage createDSNFailure(Tx tx, NHINDAddressCollection failedRecipeints) throws MessagingException {
    InternetAddress originalSender = null;
    String originalSubject = "";
    InternetAddress postmaster = null;
    String originalMessageId = "";
    Enumeration<Header> fullMessageHeaders = null;
    final List<DSNRecipientHeaders> recipientDSNHeaders = new ArrayList<DSNRecipientHeaders>();
    final List<Address> failedRecipAddresses = new ArrayList<Address>();
    final TxDetail sender = tx.getDetail(TxDetailType.FROM);
    if (sender != null) {
        originalSender = new InternetAddress(sender.getDetailValue());
        postmaster = new InternetAddress(postmasterMailbox + "@" + getAddressDomain(originalSender));
    }
    final TxDetail subject = tx.getDetail(TxDetailType.SUBJECT);
    if (subject != null)
        originalSubject = subject.getDetailValue();
    for (NHINDAddress incompleteRecip : failedRecipeints) {
        DSNRecipientHeaders dsnRecipHeaders = new DSNRecipientHeaders(DSNAction.FAILED, DSNStatus.getStatus(DSNStatus.PERMANENT, dsnStatus), incompleteRecip);
        recipientDSNHeaders.add(dsnRecipHeaders);
        failedRecipAddresses.add(incompleteRecip);
    }
    ///CLOVER:OFF
    final TxDetail origMessId = tx.getDetail(TxDetailType.MSG_ID);
    if (origMessId != null)
        originalMessageId = origMessId.getDetailValue();
    ///CLOVER:ON
    final DSNMessageHeaders messageDSNHeaders = new DSNMessageHeaders(reportingMta, originalMessageId, MtaNameType.DNS);
    final TxDetail fullHeaders = tx.getDetail(TxDetailType.MSG_FULL_HEADERS);
    if (fullHeaders != null)
        fullMessageHeaders = this.convertStringToHeaders(fullHeaders.getDetailValue());
    final MimeBodyPart textBodyPart = textGenerator.generate(originalSender, failedRecipAddresses, fullMessageHeaders);
    return generator.createDSNMessage(originalSender, originalSubject, postmaster, recipientDSNHeaders, messageDSNHeaders, textBodyPart);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) NHINDAddress(org.nhindirect.stagent.NHINDAddress) DSNRecipientHeaders(org.nhindirect.common.mail.dsn.DSNRecipientHeaders) ArrayList(java.util.ArrayList) TxDetail(org.nhindirect.common.tx.model.TxDetail) NHINDAddress(org.nhindirect.stagent.NHINDAddress) Header(javax.mail.Header) DSNMessageHeaders(org.nhindirect.common.mail.dsn.DSNMessageHeaders) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 15 with NHINDAddress

use of org.nhindirect.stagent.NHINDAddress in project nhin-d by DirectProject.

the class DefaultSmtpAgent method postProcessMessage.

private void postProcessMessage(MessageProcessResult result) {
    boolean isOutgoing = (result.getProcessedMessage() instanceof OutgoingMessage);
    // check for rejected recipients
    if (auditor != null && result.getProcessedMessage().getRejectedRecipients() != null && result.getProcessedMessage().getRejectedRecipients().size() > 0) {
        Collection<AuditContext> contexts = createContextCollectionFromMessage(result.getProcessedMessage(), Arrays.asList(AuditEvents.DEFAULT_HEADER_CONTEXT));
        StringBuffer rejectedRecips = new StringBuffer();
        int cnt = 0;
        for (NHINDAddress address : result.getProcessedMessage().getRejectedRecipients()) {
            rejectedRecips.append(address.getAddress());
            if (++cnt < result.getProcessedMessage().getRejectedRecipients().size())
                rejectedRecips.append(", ");
        }
        contexts.add(new DefaultAuditContext(AuditEvents.REJECTED_RECIPIENTS_CONTEXT, rejectedRecips.toString()));
        auditor.audit(PRINICPAL, new AuditEvent(AuditEvents.REJECTED_RECIP_NAME, AuditEvents.EVENT_TYPE), contexts);
    }
    if (isOutgoing)
        postProcessOutgoingMessage(result);
    else
        postProcessIncomingMessage(result);
}
Also used : DefaultAuditContext(org.nhindirect.common.audit.DefaultAuditContext) NHINDAddress(org.nhindirect.stagent.NHINDAddress) OutgoingMessage(org.nhindirect.stagent.OutgoingMessage) AuditEvent(org.nhindirect.common.audit.AuditEvent) AuditContext(org.nhindirect.common.audit.AuditContext) DefaultAuditContext(org.nhindirect.common.audit.DefaultAuditContext)

Aggregations

NHINDAddress (org.nhindirect.stagent.NHINDAddress)22 NHINDAddressCollection (org.nhindirect.stagent.NHINDAddressCollection)15 MimeMessage (javax.mail.internet.MimeMessage)11 ArrayList (java.util.ArrayList)6 Tx (org.nhindirect.common.tx.model.Tx)6 Address (javax.mail.Address)5 InternetAddress (javax.mail.internet.InternetAddress)5 MailAddress (org.apache.mailet.MailAddress)5 Message (org.nhindirect.stagent.mail.Message)5 NotificationMessage (org.nhindirect.stagent.mail.notifications.NotificationMessage)5 Collection (java.util.Collection)4 MessagingException (javax.mail.MessagingException)4 DefaultMessageSignatureImpl (org.nhindirect.stagent.DefaultMessageSignatureImpl)4 ServiceException (org.nhindirect.common.rest.exceptions.ServiceException)3 TxDetail (org.nhindirect.common.tx.model.TxDetail)3 MessageProcessResult (org.nhindirect.gateway.smtp.MessageProcessResult)3 Header (javax.mail.Header)2 MimeBodyPart (javax.mail.internet.MimeBodyPart)2 Mail (org.apache.mailet.Mail)2 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2