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"));
}
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();
}
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);
}
}
}
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, ","));
}
}
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.");
}
Aggregations