Example usage for javax.mail.internet MimeMultipart getBodyPart

List of usage examples for javax.mail.internet MimeMultipart getBodyPart

Introduction

In this page you can find the example usage for javax.mail.internet MimeMultipart getBodyPart.

Prototype

public synchronized BodyPart getBodyPart(String CID) throws MessagingException 

Source Link

Document

Get the MimeBodyPart referred to by the given ContentID (CID).

Usage

From source file:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test/*  ww w.j  a  v  a2  s . c o  m*/
public void testWriteToWithAttachment() throws Exception {
    SOAPMessage message = getFactory().createMessage();
    message.getSOAPPart().getEnvelope().getBody().addBodyElement(new QName("urn:ns", "test", "p"));
    AttachmentPart attachment = message.createAttachmentPart();
    attachment.setDataHandler(new DataHandler("This is a test", "text/plain; charset=iso-8859-15"));
    message.addAttachmentPart(attachment);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    message.writeTo(baos);
    System.out.write(baos.toByteArray());
    MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), "multipart/related"));
    assertEquals(2, mp.getCount());
    BodyPart part1 = mp.getBodyPart(0);
    // TODO
    //        assertEquals(messageSet.getVersion().getContentType(), part1.getContentType());
    BodyPart part2 = mp.getBodyPart(1);
    // Note: text/plain is the default content type, so we need to include the parameters in the assertion
    assertEquals("text/plain; charset=iso-8859-15", part2.getContentType());
}

From source file:com.caris.oscarexchange4j.proxy.PreviewCoverage.java

@Override
public void processInputStream(InputStream is) throws Exception {
    try {/*www .j av  a  2s  .co  m*/
        MimeMultipart multiPart = new MimeMultipart(new ByteArrayDataSource(is, MULTI_PART_MIME_TYPE));
        int count = multiPart.getCount();
        for (int part = 0; part < count; part++) {
            BodyPart body = multiPart.getBodyPart(part);
            if (body.isMimeType(OUTPUT_MIME_TYPE)) {
                this.inputStream = body.getInputStream();
                break;
            }
        }
    } catch (Exception e) {
        this.inputStream = getErrorResponseStream();
    }
}

From source file:org.nuxeo.client.api.marshaller.NuxeoResponseConverterFactory.java

@Override
public T convert(ResponseBody value) throws IOException {
    // Checking custom marshallers with the type of the method clientside.
    if (nuxeoMarshaller != null) {
        String response = value.string();
        logger.debug(response);/* ww  w .ja  va  2s .com*/
        JsonParser jsonParser = objectMapper.getFactory().createParser(response);
        return nuxeoMarshaller.read(jsonParser);
    }
    // Checking if multipart outputs.
    MediaType mediaType = MediaType.parse(value.contentType().toString());
    if (!(mediaType.type().equals(ConstantsV1.APPLICATION) && mediaType.subtype().equals(ConstantsV1.JSON))
            && !(mediaType.type().equals(ConstantsV1.APPLICATION)
                    && mediaType.subtype().equals(ConstantsV1.JSON_NXENTITY))) {
        if (mediaType.type().equals(ConstantsV1.MULTIPART)) {
            Blobs blobs = new Blobs();
            try {
                MimeMultipart mp = new MimeMultipart(
                        new ByteArrayDataSource(value.byteStream(), mediaType.toString()));
                int size = mp.getCount();
                for (int i = 0; i < size; i++) {
                    BodyPart part = mp.getBodyPart(i);
                    blobs.add(part.getFileName(), IOUtils.copyToTempFile(part.getInputStream()));
                }
            } catch (MessagingException reason) {
                throw new IOException(reason);
            }
            return (T) blobs;
        } else {
            return (T) new Blob(IOUtils.copyToTempFile(value.byteStream()));
        }
    }
    String nuxeoEntity = mediaType.nuxeoEntity();
    // Checking the type of the method clientside - aka object for Automation calls.
    if (javaType.getRawClass().equals(Object.class)) {
        if (nuxeoEntity != null) {
            switch (nuxeoEntity) {
            case ConstantsV1.ENTITY_TYPE_DOCUMENT:
                return (T) readJSON(value.charStream(), Document.class);
            case ConstantsV1.ENTITY_TYPE_DOCUMENTS:
                return (T) readJSON(value.charStream(), Documents.class);
            default:
                return (T) value;
            }
        } else {
            // This workaround is only for recordsets. There is not
            // header nuxeo-entity set for now serverside.
            String response = value.string();
            Object objectResponse = readJSON(response, Object.class);
            switch ((String) ((Map<String, Object>) objectResponse).get(ConstantsV1.ENTITY_TYPE)) {
            case ConstantsV1.ENTITY_TYPE_RECORDSET:
                return (T) readJSON(response, RecordSet.class);
            default:
                return (T) value;
            }
        }
    }
    Reader reader = value.charStream();
    try {
        return adapter.readValue(reader);
    } catch (IOException reason) {
        throw new NuxeoClientException(reason);
    } finally {
        closeQuietly(reader);
    }
}

From source file:org.ikasan.component.endpoint.email.producer.EmailProducerTest.java

@Test
public void test_successful_email_withoutAttachment() throws MessagingException, IOException {
    EmailProducerConfiguration emailProducerConfiguration = getConfiguration(false, null);

    EmailProducer emailProducer = new EmailProducer();
    ((Configured) emailProducer).setConfiguration(emailProducerConfiguration);
    ((ManagedResource) emailProducer).startManagedResource();

    emailProducer.invoke(getEmailPayload(false, null));
    List<WiserMessage> messages = wiser.getMessages();

    Assert.assertTrue("Should be three messages - one per addressee", messages.size() == 3);
    for (WiserMessage message : wiser.getMessages()) {
        Assert.assertTrue("sender should be " + sender, sender.equals(message.getEnvelopeSender()));

        MimeMessage mimeMessage = message.getMimeMessage();
        MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
        Assert.assertTrue("should be only 1 bodypart", mimeMultipart.getCount() == 1);
        BodyPart bodyPart = mimeMultipart.getBodyPart(0);
        String content = (String) bodyPart.getContent();
        Assert.assertTrue("The email content should be empty", content.isEmpty());
        Assert.assertTrue("Should fild email format as \"text/plain\"",
                bodyPart.getContentType().contains("text/plain"));
    }// w  w w.  ja  v  a 2 s . co m
}

From source file:org.ikasan.component.endpoint.email.producer.EmailProducerTest.java

@Test
public void test_successful_email_contentFromConfig() throws MessagingException, IOException {
    EmailProducerConfiguration emailProducerConfiguration = getConfiguration(false,
            "This content is from config");

    EmailProducer emailProducer = new EmailProducer();
    ((Configured) emailProducer).setConfiguration(emailProducerConfiguration);
    ((ManagedResource) emailProducer).startManagedResource();

    emailProducer.invoke(getEmailPayload(false, null));
    List<WiserMessage> messages = wiser.getMessages();

    Assert.assertTrue("Should be three messages - one per addressee", messages.size() == 3);
    for (WiserMessage message : wiser.getMessages()) {
        Assert.assertTrue("sender should be " + sender, sender.equals(message.getEnvelopeSender()));

        MimeMessage mimeMessage = message.getMimeMessage();
        MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
        Assert.assertTrue("should be only 1 bodypart", mimeMultipart.getCount() == 1);
        BodyPart bodyPart = mimeMultipart.getBodyPart(0);
        String content = (String) bodyPart.getContent();
        Assert.assertEquals("The email content should be from config", "This content is from config", content);
        Assert.assertTrue("Should find email format as \"text/plain\"",
                bodyPart.getContentType().contains("text/plain"));
    }/*from  www. j  a v  a  2  s  . c  om*/
}

From source file:org.ikasan.component.endpoint.email.producer.EmailProducerTest.java

@Test
public void test_successful_email_contentFromPayload() throws MessagingException, IOException {
    EmailProducerConfiguration emailProducerConfiguration = getConfiguration(false,
            "This content is from config");

    EmailProducer emailProducer = new EmailProducer();
    ((Configured) emailProducer).setConfiguration(emailProducerConfiguration);
    ((ManagedResource) emailProducer).startManagedResource();

    emailProducer.invoke(getEmailPayload(false, "The content is from payload"));
    List<WiserMessage> messages = wiser.getMessages();

    Assert.assertTrue("Should be three messages - one per addressee", messages.size() == 3);
    for (WiserMessage message : wiser.getMessages()) {
        Assert.assertTrue("sender should be " + sender, sender.equals(message.getEnvelopeSender()));

        MimeMessage mimeMessage = message.getMimeMessage();
        MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
        Assert.assertTrue("should be only 1 bodypart", mimeMultipart.getCount() == 1);
        BodyPart bodyPart = mimeMultipart.getBodyPart(0);
        String content = (String) bodyPart.getContent();
        Assert.assertEquals("The email content should be from payload", "The content is from payload", content);
        Assert.assertTrue("Should find email format as \"text/plain\"",
                bodyPart.getContentType().contains("text/plain"));
    }/*w w  w.ja  v a  2  s.c o  m*/
}

From source file:org.ikasan.component.endpoint.email.producer.EmailProducerTest.java

@Test
public void test_successful_email_withAttachment() throws MessagingException, IOException {

    EmailProducerConfiguration emailProducerConfiguration = getConfiguration(true, null);

    EmailProducer emailProducer = new EmailProducer();
    ((Configured) emailProducer).setConfiguration(emailProducerConfiguration);
    ((ManagedResource) emailProducer).startManagedResource();

    emailProducer.invoke(getEmailPayload(true, null));
    List<WiserMessage> messages = wiser.getMessages();

    Assert.assertTrue("Should be three messages - one per addressee", messages.size() == 3);
    for (WiserMessage message : wiser.getMessages()) {
        Assert.assertTrue("sender should be " + sender, sender.equals(message.getEnvelopeSender()));

        MimeMessage mimeMessage = message.getMimeMessage();
        MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
        Assert.assertTrue("should be 2 bodypart", mimeMultipart.getCount() == 2);
        BodyPart bodyPart = mimeMultipart.getBodyPart(0);
        String content = (String) bodyPart.getContent();
        Assert.assertTrue("The email content should be empty", content.isEmpty());
        BodyPart attachment = mimeMultipart.getBodyPart(1);
        Assert.assertEquals("Check attachment file name", "testAttachment", attachment.getFileName());
        Assert.assertTrue("Check file content",
                IOUtils.toString(attachment.getDataHandler().getDataSource().getInputStream())
                        .contains("1997,Ford,E350"));
        Assert.assertTrue("Should find email format as \"text/plain\"",
                bodyPart.getContentType().contains("text/plain"));

    }//  w w w.j  a  v  a 2s  . c  o  m
}

From source file:com.adobe.acs.commons.email.impl.EmailServiceImplTest.java

@Test
public final void testSendEmailAttachment() throws Exception {

    final String expectedMessage = "This is just a message";
    final String expectedSenderName = "John Smith";
    final String expectedSenderEmailAddress = "john@smith.com";
    final String attachment = "This is a attachment.";
    final String attachmentName = "attachment.txt";
    //Subject is provided inside the HtmlTemplate directly
    final String expectedSubject = "Greetings";

    final Map<String, String> params = new HashMap<String, String>();
    params.put("message", expectedMessage);
    params.put("senderName", expectedSenderName);
    params.put("senderEmailAddress", expectedSenderEmailAddress);

    final String recipient = "upasanac@acs.com";

    Map<String, DataSource> attachments = new HashMap();
    attachments.put(attachmentName, new ByteArrayDataSource(attachment, "text/plain"));

    ArgumentCaptor<HtmlEmail> captor = ArgumentCaptor.forClass(HtmlEmail.class);

    final List<String> failureList = emailService.sendEmail(emailTemplateAttachmentPath, params, attachments,
            recipient);/*from   ww  w.jav  a2s .  c om*/

    verify(messageGatewayHtmlEmail, times(1)).send(captor.capture());

    assertEquals(expectedSenderEmailAddress, captor.getValue().getFromAddress().getAddress());
    assertEquals(expectedSenderName, captor.getValue().getFromAddress().getPersonal());
    assertEquals(expectedSubject, captor.getValue().getSubject());
    assertEquals(recipient, captor.getValue().getToAddresses().get(0).toString());
    Method getContainer = captor.getValue().getClass().getSuperclass().getDeclaredMethod("getContainer");
    getContainer.setAccessible(true);
    MimeMultipart mimeMultipart = (MimeMultipart) getContainer.invoke(captor.getValue());
    getContainer.setAccessible(false);
    assertEquals(attachment, mimeMultipart.getBodyPart(0).getContent().toString());

    //If email is sent to the recipient successfully, the response is an empty failureList
    assertTrue(failureList.isEmpty());
}

From source file:org.alfresco.cacheserver.CacheServer.java

public List<Patch> getPatches(String host, int port, String nodeId, long nodeVersion)
        throws MessagingException, IOException {
    List<Patch> patches = new LinkedList<>();

    StringBuilder sb = new StringBuilder();
    sb.append("/patch/");
    sb.append(nodeId);/*from   w w w.j  a  v a2  s  . co m*/
    sb.append("/");
    sb.append(nodeVersion);
    String url = sb.toString();

    final ClientConfig config = new DefaultClientConfig();
    config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    final Client client = Client.create(config);

    final WebResource resource = client.resource(url);
    final MimeMultipart response = resource.get(MimeMultipart.class);

    // This will iterate the individual parts of the multipart response
    for (int i = 0; i < response.getCount(); i++) {
        final BodyPart part = response.getBodyPart(i);
        System.out.printf("Embedded Body Part [Mime Type: %s, Length: %s]\n", part.getContentType(),
                part.getSize());
        InputStream in = part.getInputStream();
        // Patch patch = new Patch();
        // patches.add(patch);
    }

    return patches;
}

From source file:org.apache.james.transport.mailets.DSNBounceTest.java

@Test
public void serviceShouldSendMultipartMailContainingTextPartWhenCustomMessageIsConfigured() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext).setProperty("messageString", "My custom message\n").build();
    dsnBounce.init(mailetConfig);/* www  .jav  a 2 s.com*/

    MailAddress senderMailAddress = new MailAddress("sender@domain.com");
    FakeMail mail = FakeMail.builder().sender(senderMailAddress).attribute("delivery-error", "Delivery error")
            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder().setText("My content")).name(MAILET_NAME)
            .recipient("recipient@domain.com").lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z")))
            .build();

    dsnBounce.service(mail);

    String expectedContent = "My custom message\n\n" + "Failed recipient(s):\n" + "recipient@domain.com\n"
            + "\n" + "Error message:\n" + "Delivery error\n" + "\n";

    List<SentMail> sentMails = fakeMailContext.getSentMails();
    assertThat(sentMails).hasSize(1);
    SentMail sentMail = sentMails.get(0);
    MimeMessage sentMessage = sentMail.getMsg();
    MimeMultipart content = (MimeMultipart) sentMessage.getContent();
    BodyPart bodyPart = content.getBodyPart(0);
    assertThat(bodyPart.getContentType()).isEqualTo("text/plain; charset=us-ascii");
    assertThat(bodyPart.getContent()).isEqualTo(expectedContent);
}