Example usage for javax.mail.internet MimeMultipart getCount

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

Introduction

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

Prototype

@Override
public synchronized int getCount() throws MessagingException 

Source Link

Document

Return the number of enclosed BodyPart objects.

Usage

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private void ensureResponse(String subject, String... contents) throws MessagingException, IOException {
    MimeMessage result = verifyHeaders(subject);
    MimeMultipart multipart = (MimeMultipart) result.getContent();
    assertThat(multipart.getCount()).isEqualTo(contents.length);
    for (int i = 0; i < contents.length; i++) {
        if (multipart.getBodyPart(i).getContent() instanceof String) {
            assertThat(((String) multipart.getBodyPart(i).getContent()).trim()).isEqualTo(contents[i]);
        } else {//w  w w.java2s . c  o m
            assertThat(IOUtils.toString((ByteArrayInputStream) multipart.getBodyPart(i).getContent()).trim())
                    .isEqualTo(contents[i]);
        }
    }
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java

private void appendMultiPart(SampleResult child, StringBuilder cdata, MimeMultipart mmp)
        throws MessagingException, IOException {
    String preamble = mmp.getPreamble();
    if (preamble != null) {
        cdata.append(preamble);/*from   ww  w  .java2 s .  com*/
    }
    child.setResponseData(cdata.toString(), child.getDataEncodingNoDefault());
    int count = mmp.getCount();
    for (int j = 0; j < count; j++) {
        BodyPart bodyPart = mmp.getBodyPart(j);
        final Object bodyPartContent = bodyPart.getContent();
        final String contentType = bodyPart.getContentType();
        SampleResult sr = new SampleResult();
        sr.setSampleLabel("Part: " + j);
        sr.setContentType(contentType);
        sr.setDataEncoding(RFC_822_DEFAULT_ENCODING);
        sr.setEncodingAndType(contentType);
        sr.sampleStart();
        if (bodyPartContent instanceof InputStream) {
            sr.setResponseData(IOUtils.toByteArray((InputStream) bodyPartContent));
        } else if (bodyPartContent instanceof MimeMultipart) {
            appendMultiPart(sr, cdata, (MimeMultipart) bodyPartContent);
        } else {
            sr.setResponseData(bodyPartContent.toString(), sr.getDataEncodingNoDefault());
        }
        sr.setResponseOK();
        if (sr.getEndTime() == 0) {// not been set by any child samples
            sr.sampleEnd();
        }
        child.addSubResult(sr);
    }
}

From source file:org.bonitasoft.connectors.email.test.EmailConnectorTest.java

private List<byte[]> getAttachmentsContent(MimeMultipart multipart) throws MessagingException, IOException {
    List<byte[]> attachments = new ArrayList<byte[]>();
    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        attachments.add(IOUtils.toByteArray(bodyPart.getInputStream()));
    }/*ww  w  . j  a  v a  2 s  . c o  m*/
    return attachments;
}

From source file:org.eclipse.ecr.automation.server.jaxrs.io.MultiPartFormRequestReader.java

public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
        MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException {
    ExecutionRequest req = null;/*from w ww . ja v a 2  s  .  c  om*/
    try {
        List<String> ctypes = headers.get("Content-Type");
        String ctype = ctypes.get(0);
        // we need to copy first the stream into a file otherwise it may
        // happen that
        // javax.mail fail to receive some parts - I am not sure why -
        // perhaps the stream is no more available when javax.mail need it?
        File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp");
        FileUtils.copyToFile(in, tmp);
        // get the input from the saved file
        in = new SharedFileInputStream(tmp);
        try {
            MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
            BodyPart part = mp.getBodyPart(0); // use content ids
            InputStream pin = part.getInputStream();
            req = JsonRequestReader.readRequest(pin, headers);
            int cnt = mp.getCount();
            if (cnt == 2) { // a blob
                req.setInput(readBlob(request, mp.getBodyPart(1)));
            } else if (cnt > 2) { // a blob list
                BlobList blobs = new BlobList();
                for (int i = 1; i < cnt; i++) {
                    blobs.add(readBlob(request, mp.getBodyPart(i)));
                }
                req.setInput(blobs);
            } else {
                log.error("Not all parts received.");
                for (int i = 0; i < cnt; i++) {
                    log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> "
                            + mp.getBodyPart(i).getContentType());
                }
                throw ExceptionHandler.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // do nothing
            }
            tmp.delete();
        }
    } catch (Throwable e) {
        throw ExceptionHandler.newException("Failed to parse multipart request", e);
    }
    return req;
}

From source file:org.eclipse.ecr.automation.server.jaxrs.io.MultiPartRequestReader.java

public ExecutionRequest readFrom(Class<ExecutionRequest> arg0, Type arg1, Annotation[] arg2, MediaType arg3,
        MultivaluedMap<String, String> headers, InputStream in) throws IOException, WebApplicationException {
    ExecutionRequest req = null;/*from www  .  j a  v  a2 s .c o  m*/
    try {
        List<String> ctypes = headers.get("Content-Type");
        String ctype = ctypes.get(0);
        // we need to copy first the stream into a file otherwise it may
        // happen that
        // javax.mail fail to receive some parts - I am not sure why -
        // perhaps the stream is no more available when javax.mail need it?
        File tmp = File.createTempFile("nx-automation-mp-upload-", ".tmp");
        FileUtils.copyToFile(in, tmp);
        in = new FileInputStream(tmp); // get the input from the saved
                                       // file
        try {
            MimeMultipart mp = new MimeMultipart(new InputStreamDataSource(in, ctype));
            BodyPart part = mp.getBodyPart(0); // use content ids
            InputStream pin = part.getInputStream();
            req = JsonRequestReader.readRequest(pin, headers);
            int cnt = mp.getCount();
            if (cnt == 2) { // a blob
                req.setInput(readBlob(request, mp.getBodyPart(1)));
            } else if (cnt > 2) { // a blob list
                BlobList blobs = new BlobList();
                for (int i = 1; i < cnt; i++) {
                    blobs.add(readBlob(request, mp.getBodyPart(i)));
                }
                req.setInput(blobs);
            } else {
                log.error("Not all parts received.");
                for (int i = 0; i < cnt; i++) {
                    log.error("Received parts: " + mp.getBodyPart(i).getHeader("Content-ID")[0] + " -> "
                            + mp.getBodyPart(i).getContentType());
                }
                throw ExceptionHandler.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            tmp.delete();
        }
    } catch (Throwable e) {
        throw ExceptionHandler.newException("Failed to parse multipart request", e);
    }
    return req;
}

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"));
    }/*  ww  w. j av a  2  s.  c  o 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   w  w  w .  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"));
    }//from ww  w  . j a v a2s.  c  om
}

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 av a2s  .  com
}

From source file:org.liveSense.service.email.EmailServiceImpl.java

/**
 * {@inheritDoc}//from  w  ww . j a v  a2  s.c om
 */
@Override
public void sendEmailFromTemplateString(Session session, String template, Node resource, String subject,
        Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc,
        HashMap<String, Object> variables) throws Exception {
    boolean haveSession = false;

    try {
        if (session != null && session.isLive()) {
            haveSession = true;
        } else {
            session = repository.loginAdministrative(null);
        }

        if (template == null) {
            throw new RepositoryException("Template is null");
        }
        String html = templateNode(Md5Encrypter.encrypt(template), resource, template, variables);
        if (html == null)
            throw new RepositoryException("Template is empty");

        // create the messge.
        MimeMessage mimeMessage = new MimeMessage((javax.mail.Session) null);

        MimeMultipart rootMixedMultipart = new MimeMultipart("mixed");
        mimeMessage.setContent(rootMixedMultipart);

        MimeMultipart nestedRelatedMultipart = new MimeMultipart("related");
        MimeBodyPart relatedBodyPart = new MimeBodyPart();
        relatedBodyPart.setContent(nestedRelatedMultipart);
        rootMixedMultipart.addBodyPart(relatedBodyPart);

        MimeMultipart messageBody = new MimeMultipart("alternative");
        MimeBodyPart bodyPart = null;
        for (int i = 0; i < nestedRelatedMultipart.getCount(); i++) {
            BodyPart bp = nestedRelatedMultipart.getBodyPart(i);
            if (bp.getFileName() == null) {
                bodyPart = (MimeBodyPart) bp;
            }
        }
        if (bodyPart == null) {
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            nestedRelatedMultipart.addBodyPart(mimeBodyPart);
            bodyPart = mimeBodyPart;
        }
        bodyPart.setContent(messageBody, "text/alternative");

        // Create the plain text part of the message.
        MimeBodyPart plainTextPart = new MimeBodyPart();
        plainTextPart.setText(extractTextFromHtml(html), configurator.getEncoding());
        messageBody.addBodyPart(plainTextPart);

        // Create the HTML text part of the message.
        MimeBodyPart htmlTextPart = new MimeBodyPart();
        htmlTextPart.setContent(html, "text/html;charset=" + configurator.getEncoding()); // ;charset=UTF-8
        messageBody.addBodyPart(htmlTextPart);

        // Check if resource have nt:file childs adds as attachment
        if (resource != null && resource.hasNodes()) {
            NodeIterator iter = resource.getNodes();
            while (iter.hasNext()) {
                Node n = iter.nextNode();
                if (n.getPrimaryNodeType().isNodeType("nt:file")) {
                    // Part two is attachment
                    MimeBodyPart attachmentBodyPart = new MimeBodyPart();
                    InputStream fileData = n.getNode("jcr:content").getProperty("jcr:data").getBinary()
                            .getStream();
                    String mimeType = n.getNode("jcr:content").getProperty("jcr:mimeType").getString();
                    String fileName = n.getName();

                    DataSource source = new StreamDataSource(fileData, fileName, mimeType);
                    attachmentBodyPart.setDataHandler(new DataHandler(source));
                    attachmentBodyPart.setFileName(fileName);
                    attachmentBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
                    attachmentBodyPart.setContentID(fileName);
                    rootMixedMultipart.addBodyPart(attachmentBodyPart);
                }
            }
        }

        prepareMimeMessage(mimeMessage, resource, template, subject, replyTo, from, date, to, cc, bcc,
                variables);
        sendEmail(session, mimeMessage);

        //
    } finally {
        if (!haveSession && session != null) {
            if (session.hasPendingChanges()) {
                try {
                    session.save();
                } catch (Throwable th) {
                }
            }
            session.logout();
        }
    }
}