Search in sources :

Example 6 with NHINDAddressCollection

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

the class NHINDSecurityAndTrustMailet_service_Test method testService_UseRcpt_AssertRecipientsUsed.

public void testService_UseRcpt_AssertRecipientsUsed() 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];
            usedSender = (NHINDAddress) invocation.getArguments()[2];
            return new MessageProcessResult(new DefaultMessageEnvelope(new Message(mimeMsg), usedRecipients, usedSender), null);
        }
    });
    final Mail mockMail = mock(MockMail.class, CALLS_REAL_METHODS);
    when(mockMail.getRecipients()).thenReturn(Arrays.asList(new MailAddress("you@cerner.com")));
    when(mockMail.getSender()).thenReturn(new MailAddress("me@cerner.com"));
    mockMail.setMessage(mimeMsg);
    NHINDSecurityAndTrustMailet mailet = new NHINDSecurityAndTrustMailet();
    mailet.agent = mockAgent;
    mailet.service(mockMail);
    assertNotNull(usedRecipients);
    assertEquals(1, usedRecipients.size());
    assertEquals("you@cerner.com", usedRecipients.iterator().next().toString());
}
Also used : MailAddress(org.apache.mailet.MailAddress) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) DefaultMessageEnvelope(org.nhindirect.stagent.DefaultMessageEnvelope) SmtpAgent(org.nhindirect.gateway.smtp.SmtpAgent) MessageProcessResult(org.nhindirect.gateway.smtp.MessageProcessResult) NHINDAddress(org.nhindirect.stagent.NHINDAddress) Mail(org.apache.mailet.Mail) MimeMessage(javax.mail.internet.MimeMessage) InvocationOnMock(org.mockito.invocation.InvocationOnMock)

Example 7 with NHINDAddressCollection

use of org.nhindirect.stagent.NHINDAddressCollection 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 8 with NHINDAddressCollection

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

the class ReliableDispatchedNotificationProducer_produceTest method testCreateAckWithNoText.

public void testCreateAckWithNoText() throws Exception {
    final MimeMessage msg = new MimeMessage(null, IOUtils.toInputStream(TestUtils.readMessageResource("PlainOutgoingMessage.txt")));
    final NHINDAddressCollection recipients = getMailRecipients(msg);
    final NotificationProducer prod = new ReliableDispatchedNotificationProducer(new NotificationSettings(true, "Local Direct Delivery Agent", ""));
    final Collection<NotificationMessage> notifications = prod.produce(new Message(msg), recipients.toInternetAddressCollection());
    assertNotNull(notifications);
    for (NotificationMessage noteMsg : notifications) {
        // assert that we removed the notification option from the headers as part of the fix of 
        // version 1.5.1
        assertNull(noteMsg.getHeader(MDNStandard.Headers.DispositionNotificationOptions, ","));
        final InternetHeaders headers = Notification.getNotificationFieldsAsHeaders(noteMsg);
        assertEquals("", headers.getHeader(MDNStandard.DispositionOption_TimelyAndReliable, ","));
    }
}
Also used : Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) NotificationMessage(org.nhindirect.stagent.mail.notifications.NotificationMessage) NotificationMessage(org.nhindirect.stagent.mail.notifications.NotificationMessage) InternetHeaders(javax.mail.internet.InternetHeaders) MimeMessage(javax.mail.internet.MimeMessage) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection)

Example 9 with NHINDAddressCollection

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

the class ReliableDispatchedNotificationProducer_produceTest method getMailRecipients.

protected NHINDAddressCollection getMailRecipients(MimeMessage mail) throws MessagingException {
    final NHINDAddressCollection recipients = new NHINDAddressCollection();
    final Address[] recipsAddr = mail.getAllRecipients();
    for (Address addr : recipsAddr) {
        recipients.add(new NHINDAddress(addr.toString(), (AddressSource) null));
    }
    return recipients;
}
Also used : NHINDAddress(org.nhindirect.stagent.NHINDAddress) AddressSource(org.nhindirect.stagent.AddressSource) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) NHINDAddress(org.nhindirect.stagent.NHINDAddress) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection)

Example 10 with NHINDAddressCollection

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

the class NHINDSecurityAndTrustMailet method service.

/**
	 * {@inheritDoc}
	 */
@SuppressWarnings("unchecked")
@Override
public void service(Mail mail) throws MessagingException {
    GatewayState.getInstance().lockForProcessing();
    try {
        Tx txToMonitor = null;
        LOGGER.trace("Entering service(Mail mail)");
        onPreprocessMessage(mail);
        final MimeMessage msg = mail.getMessage();
        final NHINDAddressCollection recipients = getMailRecipients(mail);
        // get the sender
        final NHINDAddress sender = getMailSender(mail);
        LOGGER.info("Proccessing incoming message from sender " + sender.toString());
        MessageProcessResult result = null;
        final boolean isOutgoing = this.isOutgoing(msg, sender);
        // gathered now before the message is transformed
        if (isOutgoing)
            txToMonitor = getTxToTrack(msg, sender, recipients);
        // recipients can get modified by the security and trust agent, so make a local copy
        // before processing
        final NHINDAddressCollection originalRecipList = NHINDAddressCollection.create(recipients);
        try {
            // process the message with the agent stack
            LOGGER.trace("Calling agent.processMessage");
            result = agent.processMessage(msg, recipients, sender);
            LOGGER.trace("Finished calling agent.processMessage");
            if (result == null) {
                LOGGER.error("Failed to process message.  processMessage returned null.");
                onMessageRejected(mail, originalRecipList, sender, isOutgoing, txToMonitor, null);
                mail.setState(Mail.GHOST);
                LOGGER.trace("Exiting service(Mail mail)");
                return;
            }
        } catch (Exception e) {
            // catch all
            LOGGER.error("Failed to process message: " + e.getMessage(), e);
            onMessageRejected(mail, originalRecipList, sender, isOutgoing, txToMonitor, e);
            mail.setState(Mail.GHOST);
            LOGGER.trace("Exiting service(Mail mail)");
            return;
        }
        if (result.getProcessedMessage() != null) {
            mail.setMessage(result.getProcessedMessage().getMessage());
        } else {
            /*
				 * TODO: Handle exception... GHOST the message for now and eat it
				 */
            LOGGER.debug("Processed message is null.  GHOST and eat the message.");
            onMessageRejected(mail, recipients, sender, null);
            mail.setState(Mail.GHOST);
            return;
        }
        // remove reject recipients from the RCTP headers
        if (result.getProcessedMessage().getRejectedRecipients() != null && result.getProcessedMessage().getRejectedRecipients().size() > 0 && mail.getRecipients() != null && mail.getRecipients().size() > 0) {
            final Collection<MailAddress> newRCPTList = new ArrayList<MailAddress>();
            for (MailAddress rctpAdd : (Collection<MailAddress>) mail.getRecipients()) {
                if (!isRcptRejected(rctpAdd, result.getProcessedMessage().getRejectedRecipients())) {
                    newRCPTList.add(rctpAdd);
                }
            }
            mail.setRecipients(newRCPTList);
        }
        /*
			 * Handle sending MDN messages
			 */
        final Collection<NotificationMessage> notifications = result.getNotificationMessages();
        if (notifications != null && notifications.size() > 0) {
            LOGGER.info("MDN messages requested.  Sending MDN \"processed\" messages");
            // create a message for each notification and put it on James "stack"
            for (NotificationMessage message : notifications) {
                try {
                    this.getMailetContext().sendMail(message);
                } catch (Throwable t) {
                    // don't kill the process if this fails
                    LOGGER.error("Error sending MDN message.", t);
                }
            }
        }
        // track message
        trackMessage(txToMonitor, isOutgoing);
        onPostprocessMessage(mail, result, isOutgoing, txToMonitor);
        LOGGER.trace("Exiting service(Mail mail)");
    } finally {
        GatewayState.getInstance().unlockFromProcessing();
    }
}
Also used : MailAddress(org.apache.mailet.MailAddress) Tx(org.nhindirect.common.tx.model.Tx) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) ArrayList(java.util.ArrayList) MessageProcessResult(org.nhindirect.gateway.smtp.MessageProcessResult) MessagingException(javax.mail.MessagingException) InvocationTargetException(java.lang.reflect.InvocationTargetException) SmtpAgentException(org.nhindirect.gateway.smtp.SmtpAgentException) MalformedURLException(java.net.MalformedURLException) ServiceException(org.nhindirect.common.rest.exceptions.ServiceException) NHINDAddress(org.nhindirect.stagent.NHINDAddress) NotificationMessage(org.nhindirect.stagent.mail.notifications.NotificationMessage) MimeMessage(javax.mail.internet.MimeMessage) Collection(java.util.Collection) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection)

Aggregations

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