use of javax.mail.internet.InternetHeaders in project nhin-d by DirectProject.
the class DefaultTxDetailParser method getMessageDetails.
@SuppressWarnings("incomplete-switch")
@Override
public Map<String, TxDetail> getMessageDetails(MimeMessage msg) {
Map<String, TxDetail> retVal = new HashMap<String, TxDetail>();
// get the message id
final String msgId = MailStandard.getHeader(msg, MailStandard.Headers.MessageID);
if (!msgId.isEmpty())
retVal.put(TxDetailType.MSG_ID.getType(), new TxDetail(TxDetailType.MSG_ID.getType(), msgId));
// get the subject
final String subject = MailStandard.getHeader(msg, MailStandard.Headers.Subject);
if (!subject.isEmpty())
retVal.put(TxDetailType.SUBJECT.getType(), new TxDetail(TxDetailType.SUBJECT.getType(), subject));
// get the full headers as a string
final String fullHeaders = getHeadersAsStringInternal(msg);
if (!fullHeaders.isEmpty())
retVal.put(TxDetailType.MSG_FULL_HEADERS.getType(), new TxDetail(TxDetailType.MSG_FULL_HEADERS.getType(), fullHeaders));
// get the from addresses
try {
final String from = MailStandard.getHeader(msg, MailStandard.Headers.From);
if (!from.isEmpty()) {
StringBuilder builder = new StringBuilder();
int cnt = 0;
for (InternetAddress addr : (InternetAddress[]) msg.getFrom()) {
// comma delimit multiple addresses
if (cnt > 0)
builder.append(",");
builder.append(addr.getAddress().toLowerCase(Locale.getDefault()));
++cnt;
}
retVal.put(TxDetailType.FROM.getType(), new TxDetail(TxDetailType.FROM.getType(), builder.toString()));
}
}/// CLOVER:OFF
catch (MessagingException e) {
LOGGER.warn("Failed to retrieve message sender list.", e);
}
// get the sender if it exists
try {
final InternetAddress sender = (InternetAddress) msg.getSender();
if (sender != null)
retVal.put(TxDetailType.SENDER.getType(), new TxDetail(TxDetailType.SENDER.toString(), sender.getAddress().toLowerCase(Locale.getDefault())));
}/// CLOVER:OFF
catch (MessagingException e) {
LOGGER.warn("Failed to retrieve message sender", e);
}
// get the recipient addresses
try {
if (msg.getAllRecipients() != null) {
StringBuilder builder = new StringBuilder();
int cnt = 0;
for (Address addr : msg.getAllRecipients()) {
// comma delimit multiple addresses
if (cnt > 0)
builder.append(",");
if (addr instanceof InternetAddress)
builder.append(((InternetAddress) addr).getAddress().toLowerCase(Locale.getDefault()));
++cnt;
}
retVal.put(TxDetailType.RECIPIENTS.getType(), new TxDetail(TxDetailType.RECIPIENTS.getType(), builder.toString()));
}
}/// CLOVER:OFF
catch (MessagingException e) {
LOGGER.warn("Failed to retrieve message recipient list.", e);
}
/// CLOVER:ON
// get the message type
final TxMessageType messageType = TxUtil.getMessageType(msg);
if (messageType != TxMessageType.UNKNOWN) {
switch(messageType) {
case MDN:
{
// the disposition if a field in the second part of the MDN message
final String disposition = MDNStandard.getMDNField(msg, MDNStandard.Headers.Disposition);
if (!disposition.isEmpty())
retVal.put(TxDetailType.DISPOSITION.getType(), new TxDetail(TxDetailType.DISPOSITION.getType(), disposition.toLowerCase(Locale.getDefault())));
// the final recipients is a field in the second part of the MDN message
final String finalRecipient = MDNStandard.getMDNField(msg, MDNStandard.Headers.FinalRecipient);
if (!finalRecipient.isEmpty())
retVal.put(TxDetailType.FINAL_RECIPIENTS.getType(), new TxDetail(TxDetailType.FINAL_RECIPIENTS.getType(), finalRecipient.toLowerCase(Locale.getDefault())));
// the original message id if a field in the second part of the MDN message
String origMsgId = MDNStandard.getMDNField(msg, MDNStandard.Headers.OriginalMessageID);
if (origMsgId.isEmpty()) {
// it might be in a reply to header
origMsgId = MailStandard.getHeader(msg, MailStandard.Headers.InReplyTo);
}
if (!origMsgId.isEmpty())
retVal.put(TxDetailType.PARENT_MSG_ID.getType(), new TxDetail(TxDetailType.PARENT_MSG_ID.getType(), origMsgId));
// check for X-DIRECT-FINAL-DESTINATION-DELIVER extension
try {
final InternetHeaders mdnHeaders = MDNStandard.getNotificationFieldsAsHeaders(msg);
if (mdnHeaders.getHeader(MDNStandard.DispositionOption_TimelyAndReliable, ",") != null) {
retVal.put(TxDetailType.DISPOSITION_OPTIONS.getType(), new TxDetail(TxDetailType.DISPOSITION_OPTIONS.getType(), MDNStandard.DispositionOption_TimelyAndReliable));
}
}// CLOVER:OFF
catch (Exception e) {
LOGGER.warn("Failed to retrieve MDN headers from message. Message may not be an MDN message.", e);
}
// CLOVER:ON
break;
}
case DSN:
{
// the Original-Envelope-ID header does not reflect the message id
try {
final DeliveryStatus status = new DeliveryStatus(new ByteArrayInputStream(MailUtil.serializeToBytes(msg)));
retVal.put(TxDetailType.FINAL_RECIPIENTS.getType(), new TxDetail(TxDetailType.FINAL_RECIPIENTS.getType(), DSNStandard.getFinalRecipients(status).toLowerCase(Locale.getDefault())));
// check at the message level
boolean parentFound = false;
final String origMsgId = DSNStandard.getHeaderValueFromDeliveryStatus(status, DSNStandard.Headers.OriginalMessageID);
if (!origMsgId.isEmpty()) {
parentFound = true;
retVal.put(TxDetailType.PARENT_MSG_ID.getType(), new TxDetail(TxDetailType.PARENT_MSG_ID, origMsgId));
}
if (!parentFound) {
// it might be in a reply to header
final String parentMsgId = MailStandard.getHeader(msg, MailStandard.Headers.InReplyTo);
if (!parentMsgId.isEmpty())
retVal.put(TxDetailType.PARENT_MSG_ID.getType(), new TxDetail(TxDetailType.PARENT_MSG_ID.getType(), parentMsgId));
}
// get the action
final String action = DSNStandard.getHeaderValueFromDeliveryStatus(status, DSNStandard.Headers.Action);
if (!action.isEmpty())
retVal.put(TxDetailType.DSN_ACTION.getType(), new TxDetail(TxDetailType.DSN_ACTION.getType(), action.toLowerCase(Locale.getDefault())));
// get the status
final String dsnStatus = DSNStandard.getHeaderValueFromDeliveryStatus(status, DSNStandard.Headers.Status);
if (!dsnStatus.isEmpty())
retVal.put(TxDetailType.DSN_STATUS.getType(), new TxDetail(TxDetailType.DSN_STATUS.getType(), dsnStatus.toLowerCase(Locale.getDefault())));
}///CLOVER:OFF
catch (Exception e) {
LOGGER.warn("Could not get a requested field from the DSN message", e);
}
///CLOVER:ON
break;
}
}
}
// check for the existence of disposition request options
final String dispOption = MailStandard.getHeader(msg, MDNStandard.Headers.DispositionNotificationOptions);
if (!dispOption.isEmpty())
retVal.put(TxDetailType.DISPOSITION_OPTIONS.getType(), new TxDetail(TxDetailType.DISPOSITION_OPTIONS.getType(), dispOption.toLowerCase(Locale.getDefault())));
return retVal;
}
use of javax.mail.internet.InternetHeaders in project nhin-d by DirectProject.
the class DSNGenerator method createDeliveryStatus.
/**
* Creates the deliver status section of the message
* @param recipientDSNHeaders
* @param messageDSNHeaders
* @return
* @throws MessagingException
*/
protected DeliveryStatus createDeliveryStatus(List<DSNRecipientHeaders> recipientDSNHeaders, DSNMessageHeaders messageDSNHeaders) throws MessagingException {
final DeliveryStatus deliveryStatus = new DeliveryStatus();
for (DSNRecipientHeaders dsnHeaders : recipientDSNHeaders) {
final InternetHeaders recipHeaders = new InternetHeaders();
final DSNAction dsnAction = dsnHeaders.getAction();
recipHeaders.addHeader(DSNStandard.Headers.Action, "" + dsnAction);
final Address finalRecipient = dsnHeaders.getFinalRecipient();
if (finalRecipient != null) {
recipHeaders.addHeader(DSNStandard.Headers.FinalRecipient, finalRecipient.getType() + ";" + finalRecipient.toString());
}
String status = dsnHeaders.getStatus();
recipHeaders.addHeader(DSNStandard.Headers.Status, status);
deliveryStatus.addRecipientDSN(recipHeaders);
}
final InternetHeaders messageHeaders = new InternetHeaders();
final MtaNameType mtaNameType = messageDSNHeaders.getMtaNameType();
final String reportingMta = messageDSNHeaders.getReportingMta();
messageHeaders.addHeader(DSNStandard.Headers.ReportingMTA, mtaNameType + ";" + reportingMta);
// add a custom header with original message id
final String originalMessageId = messageDSNHeaders.getOriginalMessageId();
messageHeaders.addHeader(DSNStandard.Headers.OriginalMessageID, originalMessageId);
deliveryStatus.setMessageDSN(messageHeaders);
return deliveryStatus;
}
use of javax.mail.internet.InternetHeaders in project nhin-d by DirectProject.
the class DefaultTxDetailParser_getMessageDetails_OptionalInputsTest method testGetMessageDetailsFromHeaders_getDetailsFromCommonMessage.
@Test
public void testGetMessageDetailsFromHeaders_getDetailsFromCommonMessage() throws Exception {
final MimeMessage msg = TestUtils.readMimeMessageFromFile("MessageWithAttachment.txt");
final InputStream inStream = IOUtils.toInputStream(TestUtils.readMessageFromFile("MessageWithAttachment.txt"));
try {
final InternetHeaders headers = new InternetHeaders(inStream);
final DefaultTxDetailParser parser = new DefaultTxDetailParser();
final Map<String, TxDetail> details = parser.getMessageDetails(headers);
assertEquals(MailStandard.getHeader(msg, MailStandard.Headers.MessageID), details.get(TxDetailType.MSG_ID.getType()).getDetailValue());
assertEquals(MailStandard.getHeader(msg, MailStandard.Headers.From).toLowerCase(Locale.getDefault()), details.get(TxDetailType.FROM.getType()).getDetailValue());
assertEquals(MailStandard.getHeader(msg, MailStandard.Headers.To).toLowerCase(Locale.getDefault()), details.get(TxDetailType.RECIPIENTS.getType()).getDetailValue());
assertEquals(MailStandard.getHeader(msg, MailStandard.Headers.Subject).toLowerCase(Locale.getDefault()), details.get(TxDetailType.SUBJECT.getType()).getDetailValue());
} finally {
IOUtils.closeQuietly(inStream);
}
}
use of javax.mail.internet.InternetHeaders in project nhin-d by DirectProject.
the class SMIMECryptographerImpl method createSignatureEntity.
protected MimeMultipart createSignatureEntity(byte[] entity, Collection<X509Certificate> signingCertificates) {
MimeMultipart retVal = null;
try {
final MimeBodyPart signedContent = new MimeBodyPart(new ByteArrayInputStream(entity));
final ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
final SMIMECapabilityVector caps = new SMIMECapabilityVector();
caps.addCapability(SMIMECapability.dES_EDE3_CBC);
caps.addCapability(SMIMECapability.rC2_CBC, 128);
caps.addCapability(SMIMECapability.dES_CBC);
caps.addCapability(new DERObjectIdentifier("1.2.840.113549.1.7.1"));
caps.addCapability(x509CertificateObjectsIdent);
signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
final List<X509Certificate> certList = new ArrayList<X509Certificate>();
final DirectSignedDataGenerator generator = sigFactory.createInstance();
for (X509Certificate signer : signingCertificates) {
if (signer instanceof X509CertificateEx) {
generator.addSigner(((X509CertificateEx) signer).getPrivateKey(), signer, this.m_digestAlgorithm.getOID(), createAttributeTable(signedAttrs), null);
certList.add(signer);
}
}
final CertStore certsAndcrls = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderNameForTypeAndAlgorithm("CertStore", "Collection"));
generator.addCertificatesAndCRLs(certsAndcrls);
final CMSProcessableBodyPart content = new CMSProcessableBodyPart(signedContent);
final CMSSignedData signedData = generator.generate(content);
final String header = "signed; protocol=\"application/pkcs7-signature\"; micalg=" + CryptoAlgorithmsHelper.toDigestAlgorithmMicalg(this.m_digestAlgorithm);
//String encodedSig = Base64.encodeBase64String(signedData.getEncoded());
final String encodedSig = StringUtils.newStringUtf8(Base64.encodeBase64(signedData.getEncoded(), true));
retVal = new MimeMultipart(header.toString());
final MimeBodyPart sig = new MimeBodyPart(new InternetHeaders(), encodedSig.getBytes("ASCII"));
sig.addHeader("Content-Type", "application/pkcs7-signature; name=smime.p7s; smime-type=signed-data");
sig.addHeader("Content-Disposition", "attachment; filename=\"smime.p7s\"");
sig.addHeader("Content-Description", "S/MIME Cryptographic Signature");
sig.addHeader("Content-Transfer-Encoding", "base64");
retVal.addBodyPart(signedContent);
retVal.addBodyPart(sig);
} catch (MessagingException e) {
throw new MimeException(MimeError.InvalidMimeEntity, e);
} catch (IOException e) {
throw new SignatureException(SignatureError.InvalidMultipartSigned, e);
} catch (Exception e) {
throw new NHINDException(MimeError.Unexpected, e);
}
return retVal;
}
use of javax.mail.internet.InternetHeaders in project nhin-d by DirectProject.
the class SMIMECryptographerImpl method encrypt.
/**
* Encrypts a mulit part MIME entity using the provided certificates.
* @param entity The entity that will be encrypted.
* @param encryptingCertificates The public certificates that will be used to encrypt the message.
* @return A MimeEntity containing the encrypted part.
*/
public MimeEntity encrypt(MimeMultipart mmEntity, Collection<X509Certificate> encryptingCertificates) {
MimeEntity entToEncrypt = null;
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
try {
mmEntity.writeTo(oStream);
oStream.flush();
InternetHeaders headers = new InternetHeaders();
headers.addHeader(MimeStandard.ContentTypeHeader, mmEntity.getContentType());
entToEncrypt = new MimeEntity(headers, oStream.toByteArray());
IOUtils.closeQuietly(oStream);
} catch (Exception e) {
throw new MimeException(MimeError.InvalidMimeEntity, e);
}
return this.encrypt(entToEncrypt, encryptingCertificates);
}
Aggregations