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:org.apache.axis2.transport.http.MultipartFormDataFormatterTest.java

public void testTransportHeadersOfFileAttachments() throws Exception {

    String FILE_NAME = "binaryFile.xml";
    String FIELD_NAME = "fileData";
    String CONTENT_TYPE_VALUE = "text/xml";
    String MEDIATE_ELEMENT = "mediate";
    String FILE_KEY = "fileAttachment";
    String CONTENT_DISPOSITION = "Content-Disposition";
    String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding";
    String CONTENT_TYPE = "Content-Type";
    String FORM_DATA_ELEMENT = "form-data";
    String NAME_ELEMENT = "name";
    String FILE_NAME_ELEMENT = "filename";
    String CONTENT_TRANSFER_ENCODING_VALUE = "binary";

    MultipartFormDataFormatter formatter = new MultipartFormDataFormatter();
    File binaryAttachment = getTestResourceFile(FILE_NAME);

    MessageContext mc = new MessageContext();

    DiskFileItem diskFileItem = null;//from   www  .ja va  2s.c  o  m
    InputStream input = null;
    try {
        if (binaryAttachment.exists() && !binaryAttachment.isDirectory()) {
            diskFileItem = (DiskFileItem) new DiskFileItemFactory().createItem(FIELD_NAME, CONTENT_TYPE_VALUE,
                    true, binaryAttachment.getName());
            input = new FileInputStream(binaryAttachment);
            OutputStream os = diskFileItem.getOutputStream();
            int ret = input.read();
            while (ret != -1) {
                os.write(ret);
                ret = input.read();
            }
            os.flush();
        }

    } finally {
        input.close();
    }

    DataSource dataSource = new DiskFileDataSource(diskFileItem);
    DataHandler dataHandler = new DataHandler(dataSource);

    SOAPFactory soapFactory = OMAbstractFactory.getSOAP12Factory();
    SOAPEnvelope soapEnvelope = soapFactory.getDefaultEnvelope();
    SOAPBody body = soapEnvelope.getBody();
    OMElement bodyFirstChild = soapFactory.createOMElement(new QName(MEDIATE_ELEMENT), body);
    OMText binaryNode = soapFactory.createOMText(dataHandler, true);
    soapFactory.createOMElement(FILE_KEY, null, bodyFirstChild).addChild(binaryNode);
    mc.setEnvelope(soapEnvelope);

    OMOutputFormat format = new OMOutputFormat();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    formatter.writeTo(mc, format, baos, true);

    MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), format.getContentType()));
    BodyPart bp = mp.getBodyPart(0);
    String contentDispositionValue = FORM_DATA_ELEMENT + "; " + NAME_ELEMENT + "=\"" + FILE_KEY + "\"; "
            + FILE_NAME_ELEMENT + "=\"" + binaryAttachment.getName() + "\"";
    String contentTypeValue = bp.getHeader(CONTENT_TYPE)[0].split(";")[0];
    assertEquals(contentDispositionValue, bp.getHeader(CONTENT_DISPOSITION)[0]);
    assertEquals(CONTENT_TYPE_VALUE, contentTypeValue);
    assertEquals(CONTENT_TRANSFER_ENCODING_VALUE, bp.getHeader(CONTENT_TRANSFER_ENCODING)[0]);
}

From source file:org.nuxeo.ecm.automation.jaxrs.io.operations.MultiPartFormRequestReader.java

@Override
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 w  w  . j a v a  2s .com*/
    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 = Framework.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();
            JsonParser jp = factory.createJsonParser(pin);
            req = JsonRequestReader.readRequest(jp, headers, getCoreSession());
            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 WebException.newException(
                        new IllegalStateException("Received only " + cnt + " part in a multipart request"));
            }
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // do nothing
            }
            tmp.delete();
        }
    } catch (MessagingException | IOException e) {
        throw WebException.newException("Failed to parse multipart request", e);
    }
    return req;
}

From source file:com.it.j2ee.email.MailServiceTest.java

@Test
public void sendMimeMail() throws InterruptedException, MessagingException, IOException {
    mimeMailService.sendNotificationMail("calvin");

    greenMail.waitForIncomingEmail(2000, 1);
    MimeMessage[] messages = greenMail.getReceivedMessages();
    MimeMessage message = messages[messages.length - 1];

    assertThat(message.getFrom()[0].toString()).isEqualTo("springside3.demo@gmail.com");
    assertThat(message.getSubject()).isEqualTo("");

    MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();

    assertThat(mimeMultipart.getCount()).isEqualTo(2);

    // Html?/* w  w  w . j  av  a2  s  .c  o m*/
    String mainPartText = getMainPartText(mimeMultipart.getBodyPart(0));
    System.out.println(mainPartText);
    assertThat(mainPartText).contains("<h1>calvin.</h1>");

    // 
    assertThat(GreenMailUtil.getBody(mimeMultipart.getBodyPart(1)).trim())
            .isEqualTo("Hello,i am a attachment.");
}

From source file:com.adaptris.util.text.mime.ByteArrayIterator.java

@Override
protected void initIterator() throws MessagingException, IOException {
    bodyParts = new Vector<BytePartHolder>();
    MimeMultipart multipart = new MimeMultipart(dataSource);
    for (int i = 0; i < multipart.getCount(); i++) {
        MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(i);
        BytePartHolder ph = new BytePartHolder(part);
        if (bodyParts.contains(ph)) {
            log.warn("{} already exists as a part", ph.contentId);
        }//from  w  w w .jav  a2 s.  c  o  m
        bodyParts.add(ph);
    }
    bodyPartIterator = bodyParts.iterator();
}

From source file:org.apache.usergrid.chop.webapp.coordinator.rest.UploadResource.java

/**
 * Uploads a file to the servlet context temp directory. More for testing proper uploads.
 *///from w  w  w .j a  va  2  s. c  om
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public Response upload(MimeMultipart multipart) {
    try {
        String filename = multipart.getBodyPart(0).getContent().toString();
        LOG.warn("FILENAME: " + filename);
        InputStream in = multipart.getBodyPart(1).getInputStream();
        File tempDir = new File(chopUiFig.getContextTempDir());
        String fileLocation = new File(tempDir, filename).getAbsolutePath();
        CoordinatorUtils.writeToFile(in, fileLocation);
    } catch (Exception ex) {
        LOG.error("upload", ex);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    }

    return Response.status(Response.Status.CREATED).entity("ok").build();
}

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

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

    StringBuilder sb = new StringBuilder();
    sb.append("/patch/");
    sb.append(nodeId);/*www .  j a  v  a2 s  . c o  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.usergrid.chop.webapp.coordinator.rest.UploadResource.java

@SuppressWarnings("unchecked")
@POST//from  w w w.  ja v a 2 s .  com
@Path("/results")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public Response uploadResults(MimeMultipart multipart) throws Exception {
    String runId = multipart.getBodyPart(RestParams.RUN_ID).getContent().toString();
    LOG.debug("extracted {} = {}", RestParams.RUN_ID, runId);

    InputStream in = multipart.getBodyPart(RestParams.CONTENT).getInputStream();

    JSONObject object = (JSONObject) new JSONParser().parse(new InputStreamReader(in));
    JSONArray runResults = (JSONArray) object.get("runResults");
    Iterator<JSONObject> iterator = runResults.iterator();

    //noinspection WhileLoopReplaceableByForEach
    while (iterator.hasNext()) {
        JSONObject jsonResult = iterator.next();

        BasicRunResult runResult = new BasicRunResult(runId, Util.getInt(jsonResult, "runCount"),
                Util.getInt(jsonResult, "runTime"), Util.getInt(jsonResult, "ignoreCount"),
                Util.getInt(jsonResult, "failureCount"));

        if (runResultDao.save(runResult)) {
            LOG.info("Saved run result: {}", runResult);
        }
    }

    return Response.status(Response.Status.CREATED).entity("TRUE").build();
}

From source file:org.apache.usergrid.chop.webapp.coordinator.rest.UploadResource.java

@POST
@Path("/summary")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)//from w  w  w .  j  a  v a 2  s .com
public Response uploadSummary(MimeMultipart multipart) throws Exception {
    String runnerHostname = multipart.getBodyPart(RestParams.RUNNER_HOSTNAME).getContent().toString();
    LOG.debug("extracted {} = {}", RestParams.RUNNER_HOSTNAME, runnerHostname);

    InputStream in = multipart.getBodyPart(RestParams.CONTENT).getInputStream();

    JSONObject json = (JSONObject) new JSONParser().parse(new InputStreamReader(in));
    BasicRun run = new BasicRun(COMMIT_ID, runnerHostname, Util.getInt(json, "runNumber"),
            Util.getString(json, "testName"));
    run.copyJson(json);

    if (runDao.save(run)) {
        LOG.info("Created new Run {} ", run);
    } else {
        LOG.warn("Failed to create new Run");
    }

    return Response.status(Response.Status.CREATED).entity(run.getId()).build();
}

From source file:ca.airspeed.demo.testingemail.EmailServiceTest.java

@Test
public void testWithAttachment() throws Exception {
    // Given://from   ww  w  . jav a2s . c o  m
    EmailService service = makeALocalMailer();

    InternetAddress expectedTo = new InternetAddress("Indiana.Jones@domain.com", "Indiana Jones");
    String expectedSubject = "This is a Test Email";
    String expectedTextBody = "This is a test with a PDF attachment.";
    List<FileSystemResource> filesToAttach = new ArrayList<FileSystemResource>();
    filesToAttach.add(
            new FileSystemResource(this.getClass().getClassLoader().getResource("HelloWorld.pdf").getFile()));

    // When:
    service.sendWithAttachments(expectedTo, expectedSubject, expectedTextBody, filesToAttach);

    // Then:
    List<WiserMessage> messages = wiser.getMessages();
    assertEquals("Number of messages sent;", 1, messages.size());
    WiserMessage message = messages.get(0);
    MimeMessage mimeMessage = message.getMimeMessage();

    assertEquals("Subject;", expectedSubject, mimeMessage.getSubject());

    MimeMultipart body = ((MimeMultipart) mimeMessage.getContent());
    assertEquals("Number of MIME Parts in the body;", 2, body.getCount());

    MimeBodyPart attachment = ((MimeBodyPart) body.getBodyPart(1));
    assertTrue("Attachment MIME Type should be application/pdf", attachment.isMimeType("application/pdf"));
    assertEquals("Attachment filename;", "HelloWorld.pdf", attachment.getFileName());
    assertTrue("No content found in the attachment.", isNotBlank(attachment.getContent().toString()));
}

From source file:org.openhie.openempi.service.MailEngineTest.java

public void testSendMessageWithAttachment() throws Exception {
    final String ATTACHMENT_NAME = "boring-attachment.txt";

    //mock smtp server
    Wiser wiser = new Wiser();
    int port = 2525 + (int) (Math.random() * 100);
    mailSender.setPort(port);//  w w  w. jav a  2s  .com
    wiser.setPort(port);
    wiser.start();

    Date dte = new Date();
    String emailSubject = "grepster testSendMessageWithAttachment: " + dte;
    String emailBody = "Body of the grepster testSendMessageWithAttachment message sent at: " + dte;

    ClassPathResource cpResource = new ClassPathResource("/test-attachment.txt");
    mailEngine.sendMessage(new String[] { "foo@bar.com" }, mailMessage.getFrom(), cpResource, emailBody,
            emailSubject, ATTACHMENT_NAME);

    wiser.stop();
    assertTrue(wiser.getMessages().size() == 1);
    WiserMessage wm = wiser.getMessages().get(0);
    MimeMessage mm = wm.getMimeMessage();

    Object o = wm.getMimeMessage().getContent();
    assertTrue(o instanceof MimeMultipart);
    MimeMultipart multi = (MimeMultipart) o;
    int numOfParts = multi.getCount();

    boolean hasTheAttachment = false;
    for (int i = 0; i < numOfParts; i++) {
        BodyPart bp = multi.getBodyPart(i);
        String disp = bp.getDisposition();
        if (disp == null) { //the body of the email
            Object innerContent = bp.getContent();
            MimeMultipart innerMulti = (MimeMultipart) innerContent;
            assertEquals(emailBody, innerMulti.getBodyPart(0).getContent());
        } else if (disp.equals(Part.ATTACHMENT)) { //the attachment to the email
            hasTheAttachment = true;
            assertEquals(ATTACHMENT_NAME, bp.getFileName());
        } else {
            fail("Did not expect to be able to get here.");
        }
    }
    assertTrue(hasTheAttachment);
    assertEquals(emailSubject, mm.getSubject());
}