Search in sources :

Example 6 with Message

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

the class NHINDAgentTest method testOutgoingMessageIsWrappedCorrectly.

@SuppressWarnings("unchecked")
public void testOutgoingMessageIsWrappedCorrectly() throws Exception {
    DefaultNHINDAgent agent = TestUtils.getStockAgent(Arrays.asList(new String[] { "messaging.cernerdemos.com" }));
    String testMessage = TestUtils.readResource("raw2.txt");
    Message wrappedMessage = agent.wrapMessage(testMessage);
    assertNotNull(wrappedMessage);
    assertTrue(wrappedMessage.toString().length() > 0);
    assertEquals(MailStandard.MediaType.WrappedMessage, wrappedMessage.getContentType());
    List<String> headers = new ArrayList<String>();
    Enumeration<Header> allHeaders = wrappedMessage.getAllHeaders();
    while (allHeaders.hasMoreElements()) {
        Header header = (Header) allHeaders.nextElement();
        headers.add(header.getName());
    }
    // assert that the headers (according to the NHIND spec) are copied correctly from the 
    // original message into the wrapped message
    assertTrue(headers.contains(MimeStandard.VersionHeader));
    assertTrue(headers.contains("From"));
    assertTrue(headers.contains("To"));
    assertTrue(headers.contains("Message-ID"));
    // The wrapped message should not contain Subject header
    assertFalse(headers.contains("Subject"));
}
Also used : Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Header(javax.mail.Header) ArrayList(java.util.ArrayList) DefaultNHINDAgent(org.nhindirect.stagent.DefaultNHINDAgent)

Example 7 with Message

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

the class NHINDAgentTest method testRejectMessageOnRoutingTamper_policyTrue_assertMessageRejected.

public void testRejectMessageOnRoutingTamper_policyTrue_assertMessageRejected() throws Exception {
    OptionsManager.getInstance().setOptionsParameter(new OptionsParameter(OptionsParameter.REJECT_ON_ROUTING_TAMPER, "true"));
    /*
		 * EncryptedMessage2
		 */
    DefaultNHINDAgent agent = TestUtils.getStockAgent(Arrays.asList(new String[] { "securehealthemail.com" }));
    String testMessage = TestUtils.readResource("EncryptedMessage2.txt");
    Message originalMsg = new Message(new MimeMessage(null, new ByteArrayInputStream(testMessage.getBytes("ASCII"))));
    // add an extra recipient that should not receive this message
    final NHINDAddressCollection tamperedRecips = new NHINDAddressCollection();
    tamperedRecips.add(new NHINDAddress("ryan@securehealthemail.com"));
    tamperedRecips.add(new NHINDAddress("john@securehealthemail.com"));
    final IncomingMessage inMessage = new IncomingMessage(originalMsg, tamperedRecips, new NHINDAddress(originalMsg.getFrom()[0].toString()));
    boolean exceptionOccured = false;
    try {
        agent.processIncoming(inMessage);
    } catch (AgentException e) {
        assertEquals(AgentError.MessageTamperDectection, e.getError());
        exceptionOccured = true;
    }
    assertTrue(exceptionOccured);
    OptionsManager.destroyInstance();
}
Also used : OptionsParameter(org.nhindirect.stagent.options.OptionsParameter) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MimeMessage(javax.mail.internet.MimeMessage) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultNHINDAgent(org.nhindirect.stagent.DefaultNHINDAgent)

Example 8 with Message

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

the class SMIMECryptographerImpl_createSignatureEntityTest method testCreateSignatureEntity_hsmSignatureGenerator_assertEntityCreatedAndMatchesControl.

public void testCreateSignatureEntity_hsmSignatureGenerator_assertEntityCreatedAndMatchesControl() throws Exception {
    final String installedAlias = "JunitTestKey";
    /**
         * This test is only run if a specific SafeNet eToken Pro HSM is connected to the testing 
         * system.  This can be modified for another specific machine and/or token.
         */
    pkcs11ProvName = TestUtils.setupSafeNetToken();
    if (!StringUtils.isEmpty(pkcs11ProvName)) {
        // get a certificate from the key store
        final KeyStore ks = KeyStore.getInstance("PKCS11");
        ks.load(null, "1Kingpuff".toCharArray());
        // delete the entry in case it exists
        try {
            ks.deleteEntry(installedAlias);
        } catch (Exception e) {
        /*no-op */
        }
        // add the signing cert and private key into the token
        final X509Certificate sigCertBPrivate = (X509CertificateEx) TestUtils.loadCertificate("certCheckB.p12");
        try {
            ks.setKeyEntry(installedAlias, ((X509CertificateEx) sigCertBPrivate).getPrivateKey(), null, new Certificate[] { sigCertBPrivate });
            final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) ks.getEntry(installedAlias, null);
            final X509Certificate signerCert = X509CertificateEx.fromX509Certificate((X509Certificate) entry.getCertificate(), entry.getPrivateKey());
            SplitProviderDirectSignedDataGeneratorFactory factory = new SplitProviderDirectSignedDataGeneratorFactory(pkcs11ProvName, "BC");
            final SMIMECryptographerImpl impl = new SMIMECryptographerImpl();
            impl.setSignedDataGeneratorFactory(factory);
            final String testMessage = TestUtils.readResource("MultipartMimeMessage.txt");
            final MimeEntity ent = new Message(new ByteArrayInputStream(testMessage.getBytes())).extractEntityForSignature(true);
            byte[] bytesToSign = EntitySerializer.Default.serializeToBytes(ent);
            final MimeMultipart mm = impl.createSignatureEntity(bytesToSign, Arrays.asList(signerCert));
            assertNotNull(mm);
            assertEquals(2, mm.getCount());
            validatedSignatureHeaders(mm);
            // now create the control
            final SMIMECryptographerImpl controllImpl = new SMIMECryptographerImpl();
            final MimeMultipart controllmm = controllImpl.createSignatureEntity(bytesToSign, Arrays.asList(sigCertBPrivate));
            assertNotNull(controllmm);
            assertEquals(2, controllmm.getCount());
            // make sure the signatures can be verified
            // the actual byte data may not be the same due to 
            // randomness in the signature
            validateSignature(deserializeSignatureEnvelope(mm), sigCertBPrivate);
            validateSignature(deserializeSignatureEnvelope(controllmm), sigCertBPrivate);
        } finally {
            ks.deleteEntry(installedAlias);
        }
    }
}
Also used : Message(org.nhindirect.stagent.mail.Message) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeMultipart(javax.mail.internet.MimeMultipart) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) SplitProviderDirectSignedDataGeneratorFactory(org.nhindirect.stagent.cryptography.activekeyops.SplitProviderDirectSignedDataGeneratorFactory)

Example 9 with Message

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

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

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