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:com.hmsinc.epicenter.surveillance.notification.MailingEventNotifierTest.java

@Test
public void shouldHaveCorrectStructure() throws MessagingException, IOException {
    MimeMessage message = (MimeMessage) sentMessages.get(0);

    MimeMultipart mm = (MimeMultipart) message.getContent();
    assertEquals(1, mm.getCount());

    MimeBodyPart body0 = (MimeBodyPart) mm.getBodyPart(0);
    assertNotNull(loadContent(body0.getInputStream()));
}

From source file:cherry.foundation.mail.MailSendHandlerImplTest.java

@Test
public void testSendNowAttached() throws Exception {
    LocalDateTime now = LocalDateTime.now();
    MailSendHandler handler = create(now);

    ArgumentCaptor<MimeMessagePreparator> preparator = ArgumentCaptor.forClass(MimeMessagePreparator.class);
    doNothing().when(mailSender).send(preparator.capture());

    final File file = File.createTempFile("test_", ".txt", new File("."));
    file.deleteOnExit();//from   w  w  w.  j a  va2s.co  m
    try {

        try (OutputStream out = new FileOutputStream(file)) {
            out.write("attach2".getBytes());
        }

        final DataSource dataSource = new DataSource() {
            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getName() {
                return "name3.txt";
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream("attach3".getBytes());
            }

            @Override
            public String getContentType() {
                return "text/plain";
            }
        };

        long messageId = handler.sendNow("loginId", "messageName", "from@addr", asList("to@addr"),
                asList("cc@addr"), asList("bcc@addr"), "subject", "body", new AttachmentPreparator() {
                    @Override
                    public void prepare(Attachment attachment) throws MessagingException {
                        attachment.add("name0.txt", new ByteArrayResource("attach0".getBytes()));
                        attachment.add("name1.bin", new ByteArrayResource("attach1".getBytes()),
                                "application/octet-stream");
                        attachment.add("name2.txt", file);
                        attachment.add("name3.txt", dataSource);
                    }
                });

        Session session = Session.getDefaultInstance(new Properties());
        MimeMessage message = new MimeMessage(session);
        preparator.getValue().prepare(message);

        assertEquals(0L, messageId);
        assertEquals(1, message.getRecipients(RecipientType.TO).length);
        assertEquals(parse("to@addr")[0], message.getRecipients(RecipientType.TO)[0]);
        assertEquals(1, message.getRecipients(RecipientType.CC).length);
        assertEquals(parse("cc@addr")[0], message.getRecipients(RecipientType.CC)[0]);
        assertEquals(1, message.getRecipients(RecipientType.BCC).length);
        assertEquals(parse("bcc@addr")[0], message.getRecipients(RecipientType.BCC)[0]);
        assertEquals(1, message.getFrom().length);
        assertEquals(parse("from@addr")[0], message.getFrom()[0]);
        assertEquals("subject", message.getSubject());

        MimeMultipart mm = (MimeMultipart) message.getContent();
        assertEquals(5, mm.getCount());
        assertEquals("body", ((MimeMultipart) mm.getBodyPart(0).getContent()).getBodyPart(0).getContent());

        assertEquals("name0.txt", mm.getBodyPart(1).getFileName());
        assertEquals("text/plain", mm.getBodyPart(1).getContentType());
        assertEquals("attach0", mm.getBodyPart(1).getContent());

        assertEquals("name1.bin", mm.getBodyPart(2).getDataHandler().getName());
        assertEquals("application/octet-stream", mm.getBodyPart(2).getDataHandler().getContentType());
        assertEquals("attach1", new String(
                ByteStreams.toByteArray((InputStream) mm.getBodyPart(2).getDataHandler().getContent())));

        assertEquals("name2.txt", mm.getBodyPart(3).getFileName());
        assertEquals("text/plain", mm.getBodyPart(3).getContentType());
        assertEquals("attach2", mm.getBodyPart(3).getContent());

        assertEquals("name3.txt", mm.getBodyPart(4).getFileName());
        assertEquals("text/plain", mm.getBodyPart(4).getContentType());
        assertEquals("attach3", mm.getBodyPart(4).getContent());
    } finally {
        file.delete();
    }
}

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);//from  w  ww .  j  a v  a2 s .c om
        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:com.googlecode.ddom.saaj.SOAPMessageTest.java

@Validated
@Test//from  w  w w  .  j  a va2 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.xebialabs.xlt.ci.server.XLTestServerImplTest.java

private void verifyUploadRequest(final RecordedRequest request) throws IOException, MessagingException {
    assertEquals(request.getRequestLine(), "POST /api/internal/import/testspecid HTTP/1.1");
    assertEquals(request.getHeader("accept"), "application/json; charset=utf-8");
    assertEquals(request.getHeader("authorization"), "Basic YWRtaW46YWRtaW4=");
    assertThat(request.getHeader("Content-Length"), is(nullValue()));
    assertThat(request.getHeader("Transfer-Encoding"), is("chunked"));
    assertThat(request.getChunkSizes().get(0), greaterThan(0));
    assertThat(request.getChunkSizes().size(), greaterThan(0));

    assertTrue(request.getBodySize() > 0);

    ByteArrayDataSource bads = new ByteArrayDataSource(request.getBody().inputStream(), "multipart/mixed");
    MimeMultipart mp = new MimeMultipart(bads);
    assertTrue(request.getBodySize() > 0);

    assertEquals(mp.getCount(), 2);
    assertEquals(mp.getContentType(), "multipart/mixed");

    // TODO could do additional checks on metadata content
    BodyPart bodyPart1 = mp.getBodyPart(0);
    assertEquals(bodyPart1.getContentType(), "application/json; charset=utf-8");

    BodyPart bodyPart2 = mp.getBodyPart(1);
    assertEquals(bodyPart2.getContentType(), "application/zip");
}

From source file:mitm.common.mail.filter.UnsupportedFormatStripper.java

private void scanPart(Part part, PartsContext context, int depth) throws MessagingException, IOException {
    if (depth > MAX_DEPTH) {
        return;//from  www .j  ava 2s .  c  o  m
    }

    if (part.isMimeType("multipart/mixed")) {
        MimeMultipart parts = (MimeMultipart) part.getContent();

        int partCount = parts.getCount();

        for (int i = 0; i < partCount; i++) {
            Part child = parts.getBodyPart(i);

            scanPart(child, context, ++depth);
        }
    } else if (part.isMimeType("multipart/*")) {
        /*
         * We will always add any multipart that's not a mixed multipart
         */
        context.getParts().add(part);
    } else if (part.isMimeType("text/plain")) {
        context.getParts().add(part);
    } else if (part.isMimeType("text/html")) {
        context.getParts().add(part);
    } else if (!addSupportedPart(part, context)) {
        skipPart(part, true, context);
    }
}

From source file:io.lavagna.service.MailTicketService.java

private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException {
    String result = "";
    int count = mimeMultipart.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            result = result + "\n" + bodyPart.getContent();
            break;
        } else if (bodyPart.isMimeType("text/html")) {
            String html = (String) bodyPart.getContent();
            result = result + "\n" + Jsoup.parse(html).text();
        } else if (bodyPart.getContent() instanceof MimeMultipart) {
            result = result + getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent());
        }/*  w  ww.  j a va2 s .  c o  m*/
    }
    return result;
}

From source file:org.jahia.modules.gateway.mail.MailToJSONImpl.java

protected void parseMailMessage(Part part, MailContent content) throws IOException, MessagingException {
    Object mailContent = part.getContent();
    if (mailContent instanceof MimeMultipart) {
        MimeMultipart mailMessageContent = (MimeMultipart) mailContent;
        // We have some attachments
        for (int i = 0; i < mailMessageContent.getCount(); i++) {
            BodyPart bodyPart = mailMessageContent.getBodyPart(i);
            parseMailMessage(bodyPart, content);
        }//ww w  . j a  v a  2  s  .  c o  m
    } else if (mailContent instanceof String && part.getDisposition() == null) {
        boolean isHtml = false;
        if (content.getBody() == null || ((isHtml = part.isMimeType("text/html")) && !content.isHtml())) {
            if (isHtml) {
                content.setBodyHtml((String) mailContent);
            } else {
                content.setBody((String) mailContent);
            }
        }
    } else if (mailContent instanceof InputStream || mailContent instanceof String) {
        File tempFile = File.createTempFile("mail2json-", null);
        try {
            FileUtils.copyInputStreamToFile(
                    mailContent instanceof InputStream ? (InputStream) mailContent : part.getInputStream(),
                    tempFile);
            content.getFiles()
                    .add(new FileItem(StringUtils.defaultIfEmpty(part.getFileName(), "unknown"), tempFile));
        } catch (IOException e) {
            FileUtils.deleteQuietly(tempFile);
            throw e;
        }
    }
    assert content.getBody() != null;
}

From source file:pt.lsts.neptus.comm.iridium.RockBlockIridiumMessenger.java

@Override
public Collection<IridiumMessage> pollMessages(Date timeSince) throws Exception {

    if (askGmailPassword || gmailPassword == null || gmailUsername == null) {
        Pair<String, String> credentials = GuiUtils.askCredentials(ConfigFetch.getSuperParentFrame(),
                "Enter Gmail Credentials", getGmailUsername(), getGmailPassword());
        if (credentials == null)
            return null;
        setGmailUsername(credentials.first());
        setGmailPassword(credentials.second());
        PluginUtils.saveProperties("conf/rockblock.props", this);
        askGmailPassword = false;// ww  w.  jav  a 2  s .co m
    }

    Properties props = new Properties();
    props.put("mail.store.protocol", "imaps");
    ArrayList<IridiumMessage> messages = new ArrayList<>();
    try {
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.gmail.com", getGmailUsername(), getGmailPassword());

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        int numMsgs = inbox.getMessageCount();

        for (int i = numMsgs; i > 0; i--) {
            Message m = inbox.getMessage(i);
            if (m.getReceivedDate().before(timeSince)) {
                break;
            } else {
                MimeMultipart mime = (MimeMultipart) m.getContent();
                for (int j = 0; j < mime.getCount(); j++) {
                    BodyPart p = mime.getBodyPart(j);
                    Matcher matcher = pattern.matcher(p.getContentType());
                    if (matcher.matches()) {
                        InputStream stream = (InputStream) p.getContent();
                        byte[] data = IOUtils.toByteArray(stream);
                        IridiumMessage msg = process(data, matcher.group(1));
                        if (msg != null)
                            messages.add(msg);
                    }
                }
            }
        }
    } catch (NoSuchProviderException ex) {
        ex.printStackTrace();
        System.exit(1);
    } catch (MessagingException ex) {
        ex.printStackTrace();
        System.exit(2);
    }

    return messages;
}

From source file:it.greenvulcano.gvesb.virtual.http.HTTPCallOperation.java

/**
 * @param responseBody/* w  ww  .  j  a v a  2s.co  m*/
 * @throws MessagingException
 */
private Document handleMultipart(byte[] responseBody, String contentType) throws Exception {
    ByteArrayDataSource bads = new ByteArrayDataSource(responseBody, contentType);
    MimeMultipart multipart = new MimeMultipart(bads);
    XMLUtils xml = XMLUtils.getParserInstance();
    Document doc = null;
    try {
        doc = xml.newDocument("MultipartHttpResponse");
    } finally {
        XMLUtils.releaseParserInstance(xml);
    }
    for (int i = 0; i < multipart.getCount(); i++) {
        dumpPart(multipart.getBodyPart(i), doc.getDocumentElement(), doc);
    }
    return doc;
}