Search in sources :

Example 46 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project nhin-d by DirectProject.

the class Notification method getNotificationFieldsAsHeaders.

/**
	 * Parses the notification part fields of a MDN MimeMessage message.  The message is expected to conform to the MDN specification
	 * as described in RFC3798.
	 * @return The notification part fields as a set of Internet headers. 
	 */
public static InternetHeaders getNotificationFieldsAsHeaders(MimeMessage message) {
    if (message == null)
        throw new IllegalArgumentException("Message can not be null");
    MimeMultipart mm = null;
    try {
        ByteArrayDataSource dataSource = new ByteArrayDataSource(message.getRawInputStream(), message.getContentType());
        mm = new MimeMultipart(dataSource);
    } catch (Exception e) {
        throw new NHINDException("Failed to parse notification fields.", e);
    }
    return getNotificationFieldsAsHeaders(mm);
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) NHINDException(org.nhindirect.stagent.NHINDException) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) NHINDException(org.nhindirect.stagent.NHINDException)

Example 47 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project nhin-d by DirectProject.

the class EntitySerializer method serialize.

/**
     * Serializes a collection of MimeBodyPart to an output stream with a given boundary.
     * @param entity The entities to serialize.
     * @param boundary The boundary string that will separate each entity.
     * @param stream The output stream that the entities will be serialized to.
     */
public void serialize(Collection<MimeBodyPart> parts, String boundary, OutputStream stream) {
    if (parts == null || parts.size() == 0) {
        throw new IllegalArgumentException();
    }
    try {
        MimeMultipart mm = new MimeMultipart();
        for (MimeBodyPart part : parts) {
            mm.addBodyPart(part);
        }
        ByteArrayOutputStream oStream = new ByteArrayOutputStream();
        mm.writeTo(oStream);
        oStream.flush();
    } catch (Exception e) {
        throw new MimeException(MimeError.Unexpected, e);
    }
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) MimeException(org.nhindirect.stagent.mail.MimeException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MimeBodyPart(javax.mail.internet.MimeBodyPart) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) MimeException(org.nhindirect.stagent.mail.MimeException)

Example 48 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project nhin-d by DirectProject.

the class CryptographerTest method testEncryptAndDecryptMultipartEntity.

private void testEncryptAndDecryptMultipartEntity(EncryptionAlgorithm encAlgo, boolean enforceStrongEncryption) throws Exception {
    X509Certificate cert = TestUtils.getExternalCert("user1");
    SMIMECryptographerImpl cryptographer = new SMIMECryptographerImpl();
    cryptographer.setEncryptionAlgorithm(encAlgo);
    cryptographer.setStrongEncryptionEnforced(enforceStrongEncryption);
    MimeEntity entityText = new MimeEntity();
    entityText.setText("Hello world.");
    entityText.setHeader(MimeStandard.ContentTypeHeader, "text/plain");
    entityText.setHeader(MimeStandard.ContentTransferEncodingHeader, "7bit");
    MimeEntity entityXML = new MimeEntity();
    entityXML.setText("<Test></Test>");
    entityXML.setHeader(MimeStandard.ContentTypeHeader, "text/xml");
    MimeMultipart mpEntity = new MimeMultipart();
    mpEntity.addBodyPart(entityText);
    mpEntity.addBodyPart(entityXML);
    MimeEntity encEntity = cryptographer.encrypt(mpEntity, cert);
    assertNotNull(encEntity);
    X509CertificateEx certex = TestUtils.getInternalCert("user1");
    MimeEntity decryEntity = cryptographer.decrypt(encEntity, certex);
    assertNotNull(decryEntity);
    ByteArrayOutputStream oStream = new ByteArrayOutputStream();
    mpEntity.writeTo(oStream);
    InternetHeaders hdrs = new InternetHeaders();
    hdrs.addHeader(MimeStandard.ContentTypeHeader, mpEntity.getContentType());
    MimeEntity orgEntity = new MimeEntity(hdrs, oStream.toByteArray());
    byte[] decryEntityBytes = EntitySerializer.Default.serializeToBytes(decryEntity);
    byte[] entityBytes = EntitySerializer.Default.serializeToBytes(orgEntity);
    System.out.println("Original:\r\n" + new String(entityBytes));
    System.out.println("\r\n\r\n\r\nNew:\r\n" + new String(decryEntityBytes));
    assertTrue(Arrays.equals(decryEntityBytes, entityBytes));
}
Also used : InternetHeaders(javax.mail.internet.InternetHeaders) SMIMECryptographerImpl(org.nhindirect.stagent.cryptography.SMIMECryptographerImpl) MimeMultipart(javax.mail.internet.MimeMultipart) X509CertificateEx(org.nhindirect.stagent.cert.X509CertificateEx) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) ByteArrayOutputStream(java.io.ByteArrayOutputStream) X509Certificate(java.security.cert.X509Certificate)

Example 49 with MimeMultipart

use of javax.mail.internet.MimeMultipart 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 50 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project nhin-d by DirectProject.

the class NotificationTest method testError_AssertError.

public void testError_AssertError() throws Exception {
    Notification noti = new Notification(NotificationType.Processed);
    MimeMultipart mm = noti.getAsMultipart();
    assertNotNull(mm);
    assertEquals(2, mm.getCount());
    BodyPart part = mm.getBodyPart(1);
    assertTrue(part.getContentType().startsWith("message/disposition-notification"));
    InternetHeaders headers = noti.getNotificationFieldsAsHeaders();
    assertNull(headers.getHeader(MDNStandard.Headers.Error));
    // set a new gateway
    noti.setError("Junit Error");
    mm = noti.getAsMultipart();
    assertNotNull(mm);
    assertEquals(2, mm.getCount());
    part = mm.getBodyPart(1);
    assertTrue(part.getContentType().startsWith("message/disposition-notification"));
    headers = noti.getNotificationFieldsAsHeaders();
    assertNotNull(headers.getHeader(MDNStandard.Headers.Error));
    assertEquals("Junit Error", headers.getHeader(MDNStandard.Headers.Error, ","));
    assertEquals(headers.getHeader(MDNStandard.Headers.Error, ","), noti.getError());
}
Also used : BodyPart(javax.mail.BodyPart) InternetHeaders(javax.mail.internet.InternetHeaders) MimeMultipart(javax.mail.internet.MimeMultipart) DispositionNotification(com.sun.mail.dsn.DispositionNotification)

Aggregations

MimeMultipart (javax.mail.internet.MimeMultipart)213 MimeBodyPart (javax.mail.internet.MimeBodyPart)134 MimeMessage (javax.mail.internet.MimeMessage)85 MessagingException (javax.mail.MessagingException)69 ByteArrayOutputStream (java.io.ByteArrayOutputStream)55 BodyPart (javax.mail.BodyPart)55 IOException (java.io.IOException)47 ByteString (com.linkedin.data.ByteString)37 DataHandler (javax.activation.DataHandler)33 InternetAddress (javax.mail.internet.InternetAddress)33 Test (org.testng.annotations.Test)31 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)27 HashMap (java.util.HashMap)27 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)26 Multipart (javax.mail.Multipart)26 Properties (java.util.Properties)25 Session (javax.mail.Session)24 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)24 InputStream (java.io.InputStream)23 Date (java.util.Date)21