Example usage for javax.mail BodyPart getContentType

List of usage examples for javax.mail BodyPart getContentType

Introduction

In this page you can find the example usage for javax.mail BodyPart getContentType.

Prototype

public String getContentType() throws MessagingException;

Source Link

Document

Returns the Content-Type of the content of this part.

Usage

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);//from w ww .j a  v a2  s.  c om

    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);
}

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

@Test
public void serviceShouldAttachTheOriginalMailHeadersOnlyWhenAttachmentIsEqualToHeads() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext).setProperty("attachment", "heads").build();
    dsnBounce.init(mailetConfig);//from ww w.j  a  v a  2s  . c o  m

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

    dsnBounce.service(mail);

    List<SentMail> sentMails = fakeMailContext.getSentMails();
    assertThat(sentMails).hasSize(1);
    SentMail sentMail = sentMails.get(0);
    assertThat(sentMail.getSender()).isNull();
    assertThat(sentMail.getRecipients()).containsOnly(senderMailAddress);
    MimeMessage sentMessage = sentMail.getMsg();
    MimeMultipart content = (MimeMultipart) sentMessage.getContent();
    BodyPart bodyPart = content.getBodyPart(2);
    SharedByteArrayInputStream actualContent = (SharedByteArrayInputStream) bodyPart.getContent();
    assertThat(IOUtils.toString(actualContent, StandardCharsets.UTF_8)).contains("Subject: mySubject")
            .contains("myHeader: myValue");
    assertThat(bodyPart.getContentType()).isEqualTo("text/rfc822-headers; name=mySubject");
}

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);//w  w w . j a  v  a 2  s.c  o m
    }
    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.apereo.portal.portlets.account.EmailPasswordResetNotificationImplTest.java

private String getBodyHtml(Multipart msg) throws Exception {
    for (int i = 0; i < msg.getCount(); i++) {
        BodyPart part = msg.getBodyPart(i);
        String type = part.getContentType();

        if ("text/plain".equals(type) || "text/html".equals(type)) {
            DataHandler handler = part.getDataHandler();
            String val = IOUtils.toString(handler.getInputStream());
            return val;
        }/*from  w  ww.j  av a 2s .c  o m*/
    }

    return null;
}

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

public static Blob readBlob(HttpServletRequest request, BodyPart part) throws Exception {
    String ctype = part.getContentType();
    String fname = part.getFileName();
    InputStream pin = part.getInputStream();
    final File tmp = File.createTempFile("nx-automation-upload-", ".tmp");
    FileUtils.copyToFile(pin, tmp);//from ww  w  .  j  av  a 2 s .  c  om
    FileBlob blob = new FileBlob(tmp, ctype, null, fname, null);
    RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() {
        public void cleanup(HttpServletRequest req) {
            tmp.delete();
        }
    });
    return blob;
}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static List<AttachmentInfo> saveAttachmentToWeedFs(Part message, List<AttachmentInfo> attachments,
        EmailRiverConfig config)//from w  ww.  j  a v  a2 s  . c  om
        throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
    if (attachments == null) {
        attachments = new ArrayList<AttachmentInfo>();
    }
    boolean hasAttachment = false;
    try {
        hasAttachment = isContainAttachment(message);
    } catch (MessagingException e) {
        logger.error("save attachment", e);
    } catch (IOException e) {
        logger.error("save attachment", e);
    }
    if (hasAttachment) {

        if (message.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) message.getContent();

            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {

                BodyPart bodyPart = multipart.getBodyPart(i);

                String disp = bodyPart.getDisposition();
                if (disp != null
                        && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();

                    BufferedInputStream bis = new BufferedInputStream(is);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();

                    int len = -1;
                    while ((len = bis.read()) != -1) {
                        bos.write(len);
                    }
                    bos.close();
                    bis.close();

                    byte[] data = bos.toByteArray();
                    String fileId = uploadFileToWeedfs(data, config);
                    if (fileId != null) {
                        AttachmentInfo info = new AttachmentInfo();
                        info.fileId = fileId;
                        info.fileName = decodeText(bodyPart.getFileName());
                        info.fileSize = data.length;
                        attachments.add(info);
                    }

                } else if (bodyPart.isMimeType("multipart/*")) {

                    attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config));

                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        attachments.addAll(saveAttachmentToWeedFs(bodyPart, attachments, config));
                    }
                }
            }
        } else if (message.isMimeType("message/rfc822")) {

            attachments.addAll(saveAttachmentToWeedFs(message, attachments, config));

        }

    }
    return attachments;
}

From source file:org.elasticsearch.river.email.EmailToJson.java

public static void saveAttachment(Part part, String destDir)
        throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
    if (part.isMimeType("multipart/*")) {
        Multipart multipart = (Multipart) part.getContent();

        int partCount = multipart.getCount();
        for (int i = 0; i < partCount; i++) {

            BodyPart bodyPart = multipart.getBodyPart(i);

            String disp = bodyPart.getDisposition();
            if (disp != null
                    && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                InputStream is = bodyPart.getInputStream();
                saveFile(is, destDir, decodeText(bodyPart.getFileName()));
            } else if (bodyPart.isMimeType("multipart/*")) {
                saveAttachment(bodyPart, destDir);
            } else {
                String contentType = bodyPart.getContentType();
                if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                    saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                }//  ww  w  .  j av a2s.co  m
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        saveAttachment((Part) part.getContent(), destDir);
    }
}

From source file:org.geoserver.wcs.GetCoverageTest.java

@Test
public void testLargerThanData() throws Exception {
    MockHttpServletResponse response = getAsServletResponse("wcs/BlueMarble/wcs?identifier="
            + getLayerId(TASMANIA_BM) + "&request=getcoverage&service=wcs&version=1.1.1&&format=image/geotiff"
            + "&BoundingBox=-90,-180,90,180,urn:ogc:def:crs:EPSG:6.6:4326&GridBaseCRS=EPSG:4326");

    // parse the multipart, check there are two parts
    Multipart multipart = getMultipart(response);
    assertEquals(2, multipart.getCount());
    BodyPart coveragePart = multipart.getBodyPart(1);
    assertEquals("image/tiff", coveragePart.getContentType());
    assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]);

    // save//  ww w. j  a v  a  2s.co m
    File tiffFile = File.createTempFile("wcs", "", new File("target"));
    IOUtils.copy(coveragePart.getInputStream(), new FileOutputStream(tiffFile));

    // make sure we can read the coverage back
    GeoTiffReader reader = new GeoTiffReader(tiffFile);
    GridCoverage2D result = reader.read(null);
    coverages.add(result);

    // see that we got the entire coverage, but nothing more
    CoverageInfo ci = getCatalog().getCoverageByName(TASMANIA_BM.getLocalPart());
    GridCoverage2D original = (GridCoverage2D) ci.getGridCoverage(null, null);
    coverages.add(original);

    // the grid should not be swapped since the target output is expressed in EPSG:XYWZ form
    GridEnvelope originalRange = original.getGridGeometry().getGridRange();
    GridEnvelope actualRange = result.getGridGeometry().getGridRange();
    assertEquals(originalRange.getSpan(0), actualRange.getSpan(0));
    assertEquals(originalRange.getSpan(1), actualRange.getSpan(1));

    // check also the geographic bounds
    Envelope2D originalEnv = original.getEnvelope2D();
    Envelope2D actualEnv = result.getEnvelope2D();
    assertEquals(originalEnv.getMinX(), actualEnv.getMinX(), 1e-6);
    assertEquals(originalEnv.getMinY(), actualEnv.getMinY(), 1e-6);
    assertEquals(originalEnv.getMaxX(), actualEnv.getMaxX(), 1e-6);
    assertEquals(originalEnv.getMaxY(), actualEnv.getMaxY(), 1e-6);

    // cleanup
    tiffFile.delete();
}

From source file:org.geoserver.wcs.GetCoverageTest.java

@Test
public void testRasterFilterGreen() throws Exception {
    String queryString = "wcs?identifier=" + getLayerId(MOSAIC) + "&request=getcoverage"
            + "&service=wcs&version=1.1.1&&format=image/tiff"
            + "&BoundingBox=0,0,1,1,urn:ogc:def:crs:EPSG:6.6:4326" + "&CQL_FILTER=location like 'green%25'";

    MockHttpServletResponse response = getAsServletResponse(queryString);

    // parse the multipart, check there are two parts
    Multipart multipart = getMultipart(response);
    assertEquals(2, multipart.getCount());
    BodyPart coveragePart = multipart.getBodyPart(1);
    assertEquals("image/tiff", coveragePart.getContentType());
    assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]);

    // make sure we can read the coverage back
    ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next();
    reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream()));
    RenderedImage image = reader.read(0);

    // check the pixel
    int[] pixel = new int[3];
    image.getData().getPixel(0, 0, pixel);
    assertEquals(0, pixel[0]);/*ww  w  . ja v  a  2 s  .  c  om*/
    assertEquals(255, pixel[1]);
    assertEquals(0, pixel[2]);
}

From source file:org.geoserver.wcs.GetCoverageTest.java

@Test
public void testRasterFilterRed() throws Exception {
    String queryString = "wcs?identifier=" + getLayerId(MOSAIC) + "&request=getcoverage"
            + "&service=wcs&version=1.1.1&&format=image/tiff"
            + "&BoundingBox=0,0,1,1,urn:ogc:def:crs:EPSG:6.6:4326" + "&CQL_FILTER=location like 'red%25'";

    MockHttpServletResponse response = getAsServletResponse(queryString);

    // parse the multipart, check there are two parts
    Multipart multipart = getMultipart(response);
    assertEquals(2, multipart.getCount());
    BodyPart coveragePart = multipart.getBodyPart(1);
    assertEquals("image/tiff", coveragePart.getContentType());
    assertEquals("<theCoverage>", coveragePart.getHeader("Content-ID")[0]);

    // make sure we can read the coverage back
    ImageReader reader = ImageIO.getImageReadersByFormatName("tiff").next();
    reader.setInput(ImageIO.createImageInputStream(coveragePart.getInputStream()));
    RenderedImage image = reader.read(0);

    // check the pixel
    int[] pixel = new int[3];
    image.getData().getPixel(0, 0, pixel);
    assertEquals(255, pixel[0]);/*from   w w w  .  j a v a 2s.com*/
    assertEquals(0, pixel[1]);
    assertEquals(0, pixel[2]);
}