Search in sources :

Example 16 with NHINDAddress

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

the class TimelyAndReliableLocalDelivery method service.

/**
	 * {@inheritDoc}
	 */
@Override
public void service(Mail mail) throws MessagingException {
    LOGGER.debug("Calling timely and reliable service method.");
    boolean deliverySuccessful = false;
    final MimeMessage msg = mail.getMessage();
    final boolean isReliableAndTimely = TxUtil.isReliableAndTimelyRequested(msg);
    final NHINDAddressCollection recipients = getMailRecipients(mail);
    final NHINDAddress sender = getMailSender(mail);
    try {
        serviceMethod.invoke(localDeliveryMailet, mail);
        deliverySuccessful = true;
    } catch (Exception e) {
        LOGGER.error("Failed to invoke service method.", e);
    }
    final Tx txToTrack = this.getTxToTrack(msg, sender, recipients);
    if (deliverySuccessful) {
        if (isReliableAndTimely && txToTrack.getMsgType() == TxMessageType.IMF) {
            // send back an MDN dispatched message
            final Collection<NotificationMessage> notifications = notificationProducer.produce(new Message(msg), recipients.toInternetAddressCollection());
            if (notifications != null && notifications.size() > 0) {
                LOGGER.debug("Sending MDN \"dispatched\" messages");
                // create a message for each notification and put it on James "stack"
                for (NotificationMessage message : notifications) {
                    try {
                        message.saveChanges();
                        if (dispatchedMDNDelay > 0)
                            Thread.sleep(dispatchedMDNDelay);
                        getMailetContext().sendMail(message);
                    }///CLOVER:OFF
                     catch (Throwable t) {
                        // don't kill the process if this fails
                        LOGGER.error("Error sending MDN dispatched message.", t);
                    }
                ///CLOVER:ON
                }
            }
        }
    } else {
        // create a DSN message regarless if timely and reliable was requested
        if (txToTrack != null && txToTrack.getMsgType() == TxMessageType.IMF)
            this.sendDSN(txToTrack, recipients, false);
    }
    LOGGER.debug("Exiting timely and reliable service method.");
}
Also used : NHINDAddress(org.nhindirect.stagent.NHINDAddress) Tx(org.nhindirect.common.tx.model.Tx) NotificationMessage(org.nhindirect.stagent.mail.notifications.NotificationMessage) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) NotificationMessage(org.nhindirect.stagent.mail.notifications.NotificationMessage) MimeMessage(javax.mail.internet.MimeMessage) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) MessagingException(javax.mail.MessagingException)

Example 17 with NHINDAddress

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

the class AbstractDSNCreator method createDSNFailure.

@Override
public Collection<MimeMessage> createDSNFailure(Tx tx, NHINDAddressCollection failedRecipeints, boolean useSenderDomainForPostmaster) throws MessagingException {
    Collection<MimeMessage> retVal = new ArrayList<MimeMessage>();
    InternetAddress originalSender = null;
    String originalSubject = "";
    String originalMessageId = "";
    Enumeration<Header> fullMessageHeaders = null;
    final List<Address> failedRecipAddresses = new ArrayList<Address>();
    final TxDetail subject = tx.getDetail(TxDetailType.SUBJECT);
    if (subject != null)
        originalSubject = subject.getDetailValue();
    ///CLOVER:OFF
    final TxDetail origMessId = tx.getDetail(TxDetailType.MSG_ID);
    if (origMessId != null)
        originalMessageId = origMessId.getDetailValue();
    ///CLOVER:ON
    final TxDetail fullHeaders = tx.getDetail(TxDetailType.MSG_FULL_HEADERS);
    if (fullHeaders != null)
        fullMessageHeaders = this.convertStringToHeaders(fullHeaders.getDetailValue());
    final DSNMessageHeaders messageDSNHeaders = new DSNMessageHeaders(reportingMta, originalMessageId, MtaNameType.DNS);
    final TxDetail sender = tx.getDetail(TxDetailType.FROM);
    if (sender != null)
        originalSender = new InternetAddress(sender.getDetailValue());
    final Map<InternetAddress, Collection<NHINDAddress>> dsnMessagePostmasterToFailedRecipMap = groupPostMasterAndFailedRecips(sender, failedRecipeints, useSenderDomainForPostmaster);
    if (dsnMessagePostmasterToFailedRecipMap.size() > 0) {
        for (Entry<InternetAddress, Collection<NHINDAddress>> entry : dsnMessagePostmasterToFailedRecipMap.entrySet()) {
            final List<DSNRecipientHeaders> recipientDSNHeaders = new ArrayList<DSNRecipientHeaders>();
            for (NHINDAddress incompleteRecip : entry.getValue()) {
                final DSNRecipientHeaders dsnRecipHeaders = new DSNRecipientHeaders(DSNAction.FAILED, DSNStatus.getStatus(DSNStatus.PERMANENT, dsnStatus), incompleteRecip);
                recipientDSNHeaders.add(dsnRecipHeaders);
                failedRecipAddresses.add(incompleteRecip);
            }
            final MimeBodyPart textBodyPart = textGenerator.generate(originalSender, failedRecipAddresses, fullMessageHeaders);
            final MimeMessage dsnMessage = generator.createDSNMessage(originalSender, originalSubject, entry.getKey(), recipientDSNHeaders, messageDSNHeaders, textBodyPart);
            retVal.add(dsnMessage);
        }
    }
    return retVal;
}
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) MimeMessage(javax.mail.internet.MimeMessage) DSNMessageHeaders(org.nhindirect.common.mail.dsn.DSNMessageHeaders) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) Collection(java.util.Collection) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 18 with NHINDAddress

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

the class AbstractDSNCreator method groupPostMasterAndFailedRecips.

/**
	 * Groups postmasters with the proper list of failed recipients
	 * @param sender The sender of the original message
	 * @param failedRecipeints List of all failed recipients
	 * @param useSenderAsPostmaster Indicates if the sender's domain should be used as the postmaster domain.
	 * @return Map grouping a collection of failed recipients with a postmaster.  If the useSenderAsPostmaster flag is true, all failed recipients with be associated
	 * with one postmaster (using the senders domain).  Otherwise, a postmaster address is created per unique failed recipient domain and failed recipients are grouped by domain.
	 */
protected Map<InternetAddress, Collection<NHINDAddress>> groupPostMasterAndFailedRecips(TxDetail sender, NHINDAddressCollection failedRecipeints, boolean useSenderAsPostmaster) throws MessagingException {
    final Map<InternetAddress, Collection<NHINDAddress>> postmasterToFailed = new HashMap<InternetAddress, Collection<NHINDAddress>>();
    if (useSenderAsPostmaster) {
        // just group all failed recipients into one collection
        if (sender != null) {
            final InternetAddress originalSender = new InternetAddress(sender.getDetailValue());
            final InternetAddress postmaster = new InternetAddress(postmasterMailbox + "@" + getAddressDomain(originalSender));
            postmasterToFailed.put(postmaster, failedRecipeints);
        }
    } else {
        // group by domain
        for (NHINDAddress failedRecipeint : failedRecipeints) {
            // get the postmaster for the failed recip
            final InternetAddress postmaster = new InternetAddress(postmasterMailbox + "@" + failedRecipeint.getHost().toLowerCase(Locale.getDefault()));
            Collection<NHINDAddress> group = postmasterToFailed.get(postmaster);
            if (group == null) {
                group = new ArrayList<NHINDAddress>();
                postmasterToFailed.put(postmaster, group);
            }
            group.add(failedRecipeint);
        }
    }
    return postmasterToFailed;
}
Also used : NHINDAddress(org.nhindirect.stagent.NHINDAddress) InternetAddress(javax.mail.internet.InternetAddress) HashMap(java.util.HashMap) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) Collection(java.util.Collection)

Example 19 with NHINDAddress

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

the class NHINDSecurityAndTrustMailet_service_Test method testService_RejectRecipients_AssertRejectedList.

@SuppressWarnings("unused")
public void testService_RejectRecipients_AssertRejectedList() throws Exception {
    final MimeMessage mimeMsg = EntitySerializer.Default.deserialize(TestUtils.readMessageResource("PlainOutgoingMessage.txt"));
    final SmtpAgent mockAgent = mock(SmtpAgent.class);
    when(mockAgent.processMessage((MimeMessage) any(), (NHINDAddressCollection) any(), (NHINDAddress) any())).thenAnswer(new Answer<MessageProcessResult>() {

        public MessageProcessResult answer(InvocationOnMock invocation) throws Throwable {
            usedRecipients = (NHINDAddressCollection) invocation.getArguments()[1];
            usedRecipients.get(0).setStatus(TrustEnforcementStatus.Failed);
            usedRecipients.get(1).setStatus(TrustEnforcementStatus.Success);
            usedSender = (NHINDAddress) invocation.getArguments()[2];
            MyMessageEnvelope env = new MyMessageEnvelope(new Message(mimeMsg), usedRecipients, usedSender);
            env.setAgent(new MockNHINDAgent(Arrays.asList("cerner.com")));
            env.categorizeRecipients(TrustEnforcementStatus.Success);
            NHINDAddressCollection rejectedRecips = env.getRejectedRecipients();
            return new MessageProcessResult(env, null);
        }
    });
    final Mail mockMail = mock(MockMail.class, CALLS_REAL_METHODS);
    mockMail.setRecipients(Arrays.asList(new MailAddress("you@cerner.com"), new MailAddress("they@cerner.com")));
    when(mockMail.getSender()).thenReturn(new MailAddress("me@cerner.com"));
    mockMail.setMessage(mimeMsg);
    NHINDSecurityAndTrustMailet mailet = new NHINDSecurityAndTrustMailet();
    mailet.agent = mockAgent;
    mailet.service(mockMail);
    assertEquals(1, mockMail.getRecipients().size());
}
Also used : MailAddress(org.apache.mailet.MailAddress) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) SmtpAgent(org.nhindirect.gateway.smtp.SmtpAgent) MessageProcessResult(org.nhindirect.gateway.smtp.MessageProcessResult) NHINDAddress(org.nhindirect.stagent.NHINDAddress) MockNHINDAgent(org.nhindirect.stagent.MockNHINDAgent) Mail(org.apache.mailet.Mail) MimeMessage(javax.mail.internet.MimeMessage) InvocationOnMock(org.mockito.invocation.InvocationOnMock)

Example 20 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)

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