Search in sources :

Example 1 with Message

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

the class DefaultSmtpAgent method processMessage.

/**
	 * Processes an message from an SMTP stack.  The bridge component between the SMTP stack and the SMTP agent is responsible for
	 * extracting the message, the recipient list, and the sender.  In some cases, the routing headers may have different information than
	 * what is populated in the SMTP MAIL FROM and RCTP TO headers.  In these cases, the SMTP headers should be favored over the routing
	 * headers in the message and passed as the recipient collection and sender to this method.
	 * @param message The message in the SMTP envelope.
	 * @param recipients The recipients of the message.  The RCTP TO headers should be used over the message routing headers.
	 * @param sender The send of the message. The MAIL FROM header should be used over the From: routing header in the message.
	 */
public MessageProcessResult processMessage(MimeMessage message, NHINDAddressCollection recipients, NHINDAddress sender) {
    GatewayState.getInstance().lockForProcessing();
    try {
        LOGGER.trace("Entering processMessage(MimeMessage, NHINDAddressCollection, NHINDAddress");
        MessageProcessResult retVal = null;
        verifyInitialized();
        preProcessMessage(message, sender);
        Collection<NHINDAddress> originalRecipList = new ArrayList<NHINDAddress>(recipients);
        DefaultMessageEnvelope envelopeToProcess = null;
        try {
            envelopeToProcess = new DefaultMessageEnvelope(new Message(message), recipients, sender);
            envelopeToProcess.setAgent(agent);
            // should always result in either a non null object or an exception
            MessageEnvelope processEvn = processEnvelope(envelopeToProcess);
            retVal = new MessageProcessResult(processEvn, null);
            if (retVal.getProcessedMessage() != null)
                postProcessMessage(retVal);
        } catch (SmtpAgentException e) {
            // rethrow
            LOGGER.trace("Exiting processMessage(MimeMessage, NHINDAddressCollection, NHINDAddress", e);
            throw e;
        } catch (Exception e) {
            // audit the message rejection
            if (envelopeToProcess != null) {
                Collection<AuditContext> contexts = createContextCollectionFromMessage(envelopeToProcess, Arrays.asList(AuditEvents.DEFAULT_HEADER_CONTEXT));
                if (e instanceof NHINDException) {
                    NHINDException exception = (NHINDException) e;
                    if (exception.getError() != null) {
                        contexts.add(new DefaultAuditContext(AuditEvents.REJECTED_MESSAGE_REASON_CONTEXT, exception.getError().toString()));
                        if (exception.getError() != null && exception.getError() instanceof AgentException && ((AgentException) exception.getError()).getError() == AgentError.NoTrustedRecipients) {
                            StringBuilder rejectedRecips = new StringBuilder();
                            int cnt = 0;
                            for (NHINDAddress address : originalRecipList) {
                                rejectedRecips.append(address.getAddress());
                                if (++cnt < originalRecipList.size())
                                    rejectedRecips.append(", ");
                            }
                            contexts.add(new DefaultAuditContext(AuditEvents.REJECTED_RECIPIENTS_CONTEXT, rejectedRecips.toString()));
                        }
                    }
                }
                auditor.audit(PRINICPAL, new AuditEvent(AuditEvents.REJECTED_MESSAGE_NAME, AuditEvents.EVENT_TYPE), contexts);
            }
            LOGGER.trace("Exiting processMessage(MimeMessage, NHINDAddressCollection, NHINDAddress", e);
            throw new SmtpAgentException(SmtpAgentError.Unknown, e);
        }
        LOGGER.trace("Exiting processMessage(MimeMessage, NHINDAddressCollection, NHINDAddress");
        return retVal;
    } finally {
        GatewayState.getInstance().unlockFromProcessing();
    }
}
Also used : DefaultAuditContext(org.nhindirect.common.audit.DefaultAuditContext) NotificationMessage(org.nhindirect.stagent.mail.notifications.NotificationMessage) IncomingMessage(org.nhindirect.stagent.IncomingMessage) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) OutgoingMessage(org.nhindirect.stagent.OutgoingMessage) DefaultMessageEnvelope(org.nhindirect.stagent.DefaultMessageEnvelope) AgentException(org.nhindirect.stagent.AgentException) ArrayList(java.util.ArrayList) NHINDException(org.nhindirect.stagent.NHINDException) DefaultMessageEnvelope(org.nhindirect.stagent.DefaultMessageEnvelope) MessageEnvelope(org.nhindirect.stagent.MessageEnvelope) MessagingException(javax.mail.MessagingException) AgentException(org.nhindirect.stagent.AgentException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) NHINDException(org.nhindirect.stagent.NHINDException) NHINDAddress(org.nhindirect.stagent.NHINDAddress) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection) Collection(java.util.Collection) AuditEvent(org.nhindirect.common.audit.AuditEvent)

Example 2 with Message

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

the class NHINDSecurityAndTrustMailet_functionalTest method testProcessOutgoingMessageEndToEnd_multipleProcessThreads.

public void testProcessOutgoingMessageEndToEnd_multipleProcessThreads() throws Exception {
    new TestPlan() {

        protected String getMessageToProcess() throws Exception {
            return TestUtils.readMessageResource("PlainOutgoingMessage.txt");
        }

        final class MessageEncrypter implements Callable<MimeMessage> {

            private final Mailet theMailet;

            public MessageEncrypter(Mailet theMailet) {
                this.theMailet = theMailet;
            }

            public MimeMessage call() throws Exception {
                // encrypt
                String originalMessage = getMessageToProcess();
                MimeMessage msg = EntitySerializer.Default.deserialize(originalMessage);
                // add an MDN request
                msg.setHeader(MDNStandard.Headers.DispositionNotificationTo, msg.getHeader(MailStandard.Headers.From, ","));
                MockMail theMessage = new MockMail(msg);
                theMailet.service(theMessage);
                assertNotNull(theMessage);
                assertNotNull(theMessage.getMessage());
                msg = theMessage.getMessage();
                return msg;
            }
        }

        protected void performInner() throws Exception {
            ExecutorService execService = Executors.newFixedThreadPool(10);
            String originalMessage = getMessageToProcess();
            // execute 100 times
            GatewayState.getInstance().setSettingsUpdateInterval(1);
            Mailet theMailet = getMailet("ValidConfig.xml");
            List<Future<MimeMessage>> futures = new ArrayList<Future<MimeMessage>>();
            for (int i = 0; i < 100; ++i) {
                futures.add(execService.submit(new MessageEncrypter(theMailet)));
            }
            assertEquals(100, futures.size());
            GatewayState.getInstance().setSettingsUpdateInterval(300);
            for (Future<MimeMessage> future : futures) {
                // decrypt
                theMailet = getMailet("ValidConfigStateLine.txt");
                MockMail theMessage = new MockMail(future.get());
                theMailet.service(theMessage);
                assertNotNull(theMessage);
                assertNotNull(theMessage.getMessage());
                MimeMessage msg = theMessage.getMessage();
                assertFalse(SMIMEStandard.isEncrypted(msg));
                assertEquals(theMessage.getState(), Mail.TRANSPORT);
                Message compareMessage = new Message(theMessage.getMessage());
                // remove the MDN before comparison				
                compareMessage.removeHeader(MDNStandard.Headers.DispositionNotificationTo);
                assertEquals(originalMessage, compareMessage.toString());
            }
        }
    }.perform();
}
Also used : Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) BaseTestPlan(org.nhindirect.gateway.testutils.BaseTestPlan) NHINDSecurityAndTrustMailet(org.nhindirect.gateway.smtp.james.mailet.NHINDSecurityAndTrustMailet) Mailet(org.apache.mailet.Mailet) Callable(java.util.concurrent.Callable) MimeMessage(javax.mail.internet.MimeMessage) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ArrayList(java.util.ArrayList) List(java.util.List)

Example 3 with Message

use of org.nhindirect.stagent.mail.Message 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 4 with Message

use of org.nhindirect.stagent.mail.Message 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 5 with Message

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

the class DefaultNHINDAgent_ProcessOutgoingMessage_Test method testMessageIsWrapped_WrapMessageIsNotCalled.

/**
	 * 
	 * @throws Exception
	 */
public void testMessageIsWrapped_WrapMessageIsNotCalled() throws Exception {
    new TestPlan() {

        protected OutgoingMessage createMessage() throws Exception {
            MimeMessage mimeMsg = new SecondaryMimeMessage();
            mimeMsg.setText("");
            Message msg = new Message(mimeMsg) {

                @Override
                public String getContentType() throws MessagingException {
                    return MailStandard.MediaType.WrappedMessage;
                }
            };
            NHINDAddressCollection recipients = new NHINDAddressCollection();
            recipients.add(new NHINDAddress(""));
            NHINDAddress sender = new NHINDAddress("");
            theCreateMessage = new OutgoingMessage(msg, recipients, sender) {

                @Override
                protected void categorizeRecipients(TrustEnforcementStatus minTrustStatus) {
                    categorizeRecipientsCalls++;
                    categorizeRecipients_Internal(minTrustStatus);
                }
            };
            return theCreateMessage;
        }

        protected void doAssertions() throws Exception {
            assertEquals(0, wrapMessageCalls);
        }
    }.perform();
}
Also used : TrustEnforcementStatus(org.nhindirect.stagent.trust.TrustEnforcementStatus) SecondaryMimeMessage(org.nhindirect.stagent.utils.SecondaryMimeMessage) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) BaseTestPlan(org.nhindirect.stagent.utils.BaseTestPlan) SecondaryMimeMessage(org.nhindirect.stagent.utils.SecondaryMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) SecondaryMimeMessage(org.nhindirect.stagent.utils.SecondaryMimeMessage) MessagingException(javax.mail.MessagingException)

Aggregations

Message (org.nhindirect.stagent.mail.Message)25 MimeMessage (javax.mail.internet.MimeMessage)17 ByteArrayInputStream (java.io.ByteArrayInputStream)14 MessagingException (javax.mail.MessagingException)7 NHINDAddressCollection (org.nhindirect.stagent.NHINDAddressCollection)7 ArrayList (java.util.ArrayList)5 MimeMultipart (javax.mail.internet.MimeMultipart)5 NHINDAddress (org.nhindirect.stagent.NHINDAddress)5 MimeEntity (org.nhindirect.stagent.mail.MimeEntity)5 IOException (java.io.IOException)4 X509Certificate (java.security.cert.X509Certificate)4 MailAddress (org.apache.mailet.MailAddress)4 NotificationMessage (org.nhindirect.stagent.mail.notifications.NotificationMessage)4 Header (javax.mail.Header)3 InternetHeaders (javax.mail.internet.InternetHeaders)3 Mail (org.apache.mailet.Mail)3 CMSSignedData (org.bouncycastle.cms.CMSSignedData)3 InvocationOnMock (org.mockito.invocation.InvocationOnMock)3 MessageProcessResult (org.nhindirect.gateway.smtp.MessageProcessResult)3 SmtpAgent (org.nhindirect.gateway.smtp.SmtpAgent)3