Example usage for javax.mail Multipart getBodyPart

List of usage examples for javax.mail Multipart getBodyPart

Introduction

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

Prototype

public synchronized BodyPart getBodyPart(int index) throws MessagingException 

Source Link

Document

Get the specified Part.

Usage

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

@Test
public void testReadNoGridCRS() throws Exception {
    String request = //
            "  <wcs:GetCoverage service=\"WCS\" version=\"1.1.1\" "
                    + "                   xmlns:wcs=\"http://www.opengis.net/wcs/1.1.1\" "
                    + "                   xmlns:gml=\"http://www.opengis.net/gml\""
                    + "                   xmlns:ows=\"http://www.opengis.net/ows/1.1\" >\n"
                    + "   <ows:Identifier>" + getLayerId(MockData.TASMANIA_DEM) + "   </ows:Identifier>\n"
                    + "            <wcs:DomainSubset>\n"
                    + "              <ows:BoundingBox crs=\"http://www.opengis.net/gml/srs/epsg.xml#4326\">\n"
                    + "                <ows:LowerCorner>-180.0 -90.0</ows:LowerCorner>\n"
                    + "                <ows:UpperCorner>180.0 90.0</ows:UpperCorner>\n"
                    + "              </ows:BoundingBox>\n" //
                    + "            </wcs:DomainSubset>\n" + "            <wcs:Output format=\"image/tiff\"/>\n"
                    + "          </wcs:GetCoverage>";

    MockHttpServletResponse response = postAsServletResponse("wcs", request);

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

From source file:MultipartViewer.java

protected void setupDisplay(Multipart mp) {
    // we display the first body part in a main frame on the left, and then
    // on the right we display the rest of the parts as attachments

    GridBagConstraints gc = new GridBagConstraints();
    gc.gridheight = GridBagConstraints.REMAINDER;
    gc.fill = GridBagConstraints.BOTH;
    gc.weightx = 1.0;/*  ww  w  .  j  ava 2s  . co  m*/
    gc.weighty = 1.0;

    // get the first part
    try {
        BodyPart bp = mp.getBodyPart(0);
        Component comp = getComponent(bp);
        add(comp, gc);

    } catch (MessagingException me) {
        add(new Label(me.toString()), gc);
    }

    // see if there are more than one parts
    try {
        int count = mp.getCount();

        // setup how to display them
        gc.gridwidth = GridBagConstraints.REMAINDER;
        gc.gridheight = 1;
        gc.fill = GridBagConstraints.NONE;
        gc.anchor = GridBagConstraints.NORTH;
        gc.weightx = 0.0;
        gc.weighty = 0.0;
        gc.insets = new Insets(4, 4, 4, 4);

        // for each one we create a button with the content type
        for (int i = 1; i < count; i++) { // we skip the first one 
            BodyPart curr = mp.getBodyPart(i);
            String label = null;
            if (label == null)
                label = curr.getFileName();
            if (label == null)
                label = curr.getDescription();
            if (label == null)
                label = curr.getContentType();

            Button but = new Button(label);
            but.addActionListener(new AttachmentViewer(curr));
            add(but, gc);
        }

    } catch (MessagingException me2) {
        me2.printStackTrace();
    }

}

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

/**
 * This tests just ended up throwing an exception as the coverage being encoded
 * was too large due to a bug in the scales estimation
 * //from   ww w . j a  v a 2  s .  com
 * @throws Exception
 */
@Test
public void testRotatedPost() throws Exception {
    String request = "<GetCoverage xmlns=\"http://www.opengis.net/wcs/1.1.1\" xmlns:gml=\"http://www.opengis.net/gml\"\n"
            + "             xmlns:ows11=\"http://www.opengis.net/ows/1.1\"\n"
            + "             xmlns:ows=\"http://www.opengis.net/ows/1.1\"\n"
            + "             xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \r\n" + //
            "             xmlns:wcs=\"http://schemas.opengis.net/wcs/1.1.1\"\n"
            + "             xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n" + "             service=\"WCS\"\n"
            + "             version=\"1.1.1\"\n"
            + "             xsi:schemaLocation=\"http://www.opengis.net/wcs/1.1.1 http://schemas.opengis.net/wcs/1.1.1/wcsAll.xsd\">\n"
            + "   <ows11:Identifier>RotatedCad</ows11:Identifier>\n" + "   <DomainSubset>\n"
            + "      <ows11:BoundingBox crs=\"urn:ogc:def:crs:OGC:1.3:CRS84\">\n"
            + "         <ows11:LowerCorner>7.7634301664746515 45.14713380418506</ows11:LowerCorner>\n"
            + "         <ows11:UpperCorner>7.764350661575157 45.14763319238466</ows11:UpperCorner>\n"
            + "      </ows11:BoundingBox>\n" + "   </DomainSubset>\n" + "   <Output format=\"image/tiff\"/>\n"
            + "</GetCoverage>";

    MockHttpServletResponse response = postAsServletResponse("wcs", request);

    // 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 image is suitably small (without requiring an exact size)
    assertTrue(image.getWidth() < 1000);
    assertTrue(image.getHeight() < 1000);
}

From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java

public void buildAttachments(List<Attach> attachs, Part part, String baseStorePath)
        throws MessagingException, IOException {
    if (part.isMimeType(MULTIPART_TYPE)) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            buildAttachments(attachs, mp.getBodyPart(i), baseStorePath);
        }// ww w .  j ava 2 s .  c  o m
    } else if (isAttach(part)) {
        attachs.add(getAttach(part, baseStorePath));
    }
}

From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java

public void buildMd5CheckSums(List<String> checksums, Part part) throws MessagingException, IOException {
    if (part.isMimeType(MULTIPART_TYPE)) {
        Multipart mp = (Multipart) part.getContent();
        for (int i = 0; i < mp.getCount(); i++) {
            buildMd5CheckSums(checksums, mp.getBodyPart(i));
        }/*www . j  av  a  2 s.c o  m*/
    } else if (isAttach(part)) {
        checksums.add(getCheckSum(part));
    }
}

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/*from  w ww. j a  v a  2  s.  c o  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.springintegration.demo.service.EmailTransformer.java

public void handleMultipart(Multipart multipart, javax.mail.Message mailMessage, List<Message<?>> messages) {
    final int count;
    try {// ww  w. ja va 2  s.  c o  m
        count = multipart.getCount();
    } catch (MessagingException e) {
        throw new IllegalStateException("Error while retrieving the number of enclosed BodyPart objects.", e);
    }

    for (int i = 0; i < count; i++) {

        final BodyPart bp;

        try {
            bp = multipart.getBodyPart(i);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving body part.", e);
        }

        final String contentType;
        final String filename;
        final String disposition;
        final String subject;

        try {
            contentType = bp.getContentType();
            filename = bp.getFileName();
            disposition = bp.getDisposition();
            subject = mailMessage.getSubject();

        } catch (MessagingException e) {
            throw new IllegalStateException("Unable to retrieve body part meta data.", e);
        }

        if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            LOGGER.info("Handdling attachment '{}', type: '{}'", filename, contentType);
        }

        final Object content;

        try {
            content = bp.getContent();
        } catch (IOException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        } catch (MessagingException e) {
            throw new IllegalStateException("Error while retrieving the email contents.", e);
        }

        if (content instanceof String) {

            final Message<String> message = MessageBuilder.withPayload((String) content)
                    .setHeader(FileHeaders.FILENAME, subject + ".txt").build();

            messages.add(message);

        } else if (content instanceof InputStream) {

            InputStream inputStream = (InputStream) content;
            ByteArrayOutputStream bis = new ByteArrayOutputStream();

            try {
                IOUtils.copy(inputStream, bis);
            } catch (IOException e) {
                throw new IllegalStateException(
                        "Error while copying input stream to the ByteArrayOutputStream.", e);
            }

            Message<byte[]> message = MessageBuilder.withPayload((bis.toByteArray()))
                    .setHeader(FileHeaders.FILENAME, filename).build();

            messages.add(message);

        } else if (content instanceof javax.mail.Message) {
            handleMessage((javax.mail.Message) content, messages);
        } else if (content instanceof Multipart) {
            Multipart mp2 = (Multipart) content;
            handleMultipart(mp2, mailMessage, messages);
        } else {
            throw new IllegalStateException("Content type not handled: " + content.getClass().getSimpleName());
        }
    }

}

From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java

public boolean hasAttach(Part part) throws MessagingException, IOException {
    if (part.isMimeType(MULTIPART_TYPE)) {
        Multipart mp = (Multipart) part.getContent();
        boolean has = false;
        for (int i = 0; i < mp.getCount(); i++) {
            if (hasAttach(mp.getBodyPart(i))) {
                has = true;//from w ww. j  av a 2  s . co  m
                break;
            }
        }
        return has;
    } else if (isAttach(part)) {
        return true;
    } else {
        return false;
    }
}

From source file:org.apache.hupa.server.handler.GetMessageDetailsHandler.java

/**
 * Handle the parts of the given message. The method will call itself recursively to handle all nested parts
 * @param message the MimeMessage /* w w  w.  java 2  s . c o m*/
 * @param con the current processing Content
 * @param sbPlain the StringBuffer to fill with text
 * @param attachmentList ArrayList with attachments
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 * @throws IOException
 */
protected boolean handleParts(MimeMessage message, Object con, StringBuffer sbPlain,
        ArrayList<MessageAttachment> attachmentList)
        throws UnsupportedEncodingException, MessagingException, IOException {
    boolean isHTML = false;
    if (con instanceof String) {
        if (message.getContentType().toLowerCase().startsWith("text/html")) {
            isHTML = true;
        } else {
            isHTML = false;
        }
        sbPlain.append((String) con);

    } else if (con instanceof Multipart) {

        Multipart mp = (Multipart) con;
        String multipartContentType = mp.getContentType().toLowerCase();

        String text = null;

        if (multipartContentType.startsWith("multipart/alternative")) {
            isHTML = handleMultiPartAlternative(mp, sbPlain);
        } else {
            for (int i = 0; i < mp.getCount(); i++) {
                Part part = mp.getBodyPart(i);

                String contentType = part.getContentType().toLowerCase();

                Boolean bodyRead = sbPlain.length() > 0;

                if (!bodyRead && contentType.startsWith("text/plain")) {
                    isHTML = false;
                    text = (String) part.getContent();
                } else if (!bodyRead && contentType.startsWith("text/html")) {
                    isHTML = true;
                    text = (String) part.getContent();
                } else if (!bodyRead && contentType.startsWith("message/rfc822")) {
                    // Extract the message and pass it
                    MimeMessage msg = (MimeMessage) part.getDataHandler().getContent();
                    isHTML = handleParts(msg, msg.getContent(), sbPlain, attachmentList);
                } else {
                    if (part.getFileName() != null) {
                        // Inline images are not added to the attachment list
                        // TODO: improve the in-line images detection 
                        if (part.getHeader("Content-ID") == null) {
                            MessageAttachment attachment = new MessageAttachment();
                            attachment.setName(MimeUtility.decodeText(part.getFileName()));
                            attachment.setContentType(part.getContentType());
                            attachment.setSize(part.getSize());
                            attachmentList.add(attachment);
                        }
                    } else {
                        isHTML = handleParts(message, part.getContent(), sbPlain, attachmentList);
                    }
                }

            }
            if (text != null)
                sbPlain.append(text);
        }

    }
    return isHTML;
}

From source file:org.mxhero.engine.plugin.attachmentlink.alcommand.internal.domain.Message.java

public void removeAll(Part part, BodyPart notDelete) throws MessagingException, IOException {
    if (isAttach(part)) {
        if (part != notDelete) {
            BodyPart multi = (BodyPart) part;
            Multipart parent = multi.getParent();
            parent.removeBodyPart(multi);
        }/*from w w  w . j a  v  a2  s  .c  o m*/
    } else if (part.isMimeType(MULTIPART_TYPE)) {
        Multipart mp = (Multipart) part.getContent();
        List<BodyPart> toRemove = new ArrayList<BodyPart>();
        for (int i = 0; i < mp.getCount(); i++) {
            BodyPart bodyPart = mp.getBodyPart(i);
            if (removePart(bodyPart, notDelete)) {
                toRemove.add(bodyPart);
            } else {
                removeAll(bodyPart, notDelete);
            }
        }
        for (BodyPart bp : toRemove)
            mp.removeBodyPart(bp);
    }
}