Example usage for javax.mail BodyPart getInputStream

List of usage examples for javax.mail BodyPart getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException, MessagingException;

Source Link

Document

Return an input stream for this part's "content".

Usage

From source file:com.crawlersick.nettool.GetattchmentFromMail1.java

public boolean fetchmailforattch() throws IOException, MessagingException {
    boolean fetchtest = false;

    Properties props = new Properties();
    props.setProperty("mail.store.protocol", "imaps");

    try {//from   w w w  .  ja  v a2s.  com
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(IMapHost, MailId, MailPassword);
        Folder inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_ONLY);
        totalmailcount = inbox.getMessageCount();

        Message msg = null;
        for (int i = totalmailcount; i > 0; i--) {
            fromadd = "";
            msg = inbox.getMessage(i);
            Address[] in = msg.getFrom();
            for (Address address : in) {
                fromadd = address.toString() + fromadd;
                //System.out.println("FROM:" + address.toString());
            }
            if (fromadd.matches("admin@cronmailservice.appspotmail.com") && msg.getSubject().matches(
                    "ThanksToTsukuba_World-on-my-shoulders-as-I-run-back-to-this-8-Mile-Road_cronmailservice"))
                break;
        }

        if (fromadd.equals("'")) {
            log.log(Level.SEVERE, "Error: no related mail found!" + this.MailId);
            return fetchtest;
        }

        //    Multipart mp = (Multipart) msg.getContent();
        //  BodyPart bp = mp.getBodyPart(0);
        sentdate = msg.getSentDate().toString();

        subject = msg.getSubject();

        Content = msg.getContent().toString();

        log.log(Level.INFO, Content);
        log.log(Level.INFO, sentdate);
        localIntent.putExtra("213123", "Got Server latest update at : " + sentdate + " , Reading the Data...");
        LocalBroadcastManager.getInstance(myis).sendBroadcast(localIntent);

        Multipart multipart = (Multipart) msg.getContent();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && (bodyPart.getFileName() == null
                    || !bodyPart.getFileName().equals("dataforvgendwithudp.gzip"))) {
                continue; // dealing with attachments only
            }
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            InputStream is = bodyPart.getInputStream();
            //validvgbinary = IOUtils.toByteArray(is);
            int nRead;
            byte[] data = new byte[5000000];

            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }

            buffer.flush();

            validvgbinary = buffer.toByteArray();
            break;
        }

        fetchtest = true;
    } catch (Exception mex) {
        mex.printStackTrace();

    }

    return fetchtest;
}

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//w  w  w . j a  va2s  .  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:ch.algotrader.util.mail.EmailTransformer.java

/**
 * Parses any {@link Multipart} instances that contains attachments
 *
 * Will create the respective {@link EmailFragment}s representing those attachments.
 * @throws MessagingException// w  w  w  . jav  a  2  s  . c  o m
 */
public void handleMultipart(Multipart multipart, List<EmailFragment> emailFragments) throws MessagingException {

    final int count = multipart.getCount();

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

        BodyPart bodyPart = multipart.getBodyPart(i);
        String filename = bodyPart.getFileName();
        String disposition = bodyPart.getDisposition();

        if (filename == null && bodyPart instanceof MimeBodyPart) {
            filename = ((MimeBodyPart) bodyPart).getContentID();
        }

        if (disposition == null) {

            //ignore message body

        } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE)) {

            try {
                try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        BufferedInputStream bis = new BufferedInputStream(bodyPart.getInputStream())) {

                    IOUtils.copy(bis, bos);

                    emailFragments.add(new EmailFragment(filename, bos.toByteArray()));

                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info(String.format("processing file: %s", new Object[] { filename }));
                    }

                }

            } catch (IOException e) {
                throw new MessagingException("error processing streams", e);
            }

        } else {
            throw new MessagingException("unkown disposition " + disposition);
        }
    }
}

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
 * /*www.  j  av  a  2s.co m*/
 * @throws Exception
 */
@Test
public void testRotatedGet() throws Exception {
    String request = "wcs?&service=WCS&request=GetCoverage&version=1.1.1&identifier=RotatedCad&BoundingBox=7.7634071540971386,45.14712131948007,7.76437367395267,45.14764567708965,urn:ogc:def:crs:OGC:1.3:CRS84&Format=image/tiff";
    MockHttpServletResponse response = getAsServletResponse(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.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]);//from  w w  w . j a  va 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]);// w w  w. j  a v a  2 s.co m
    assertEquals(0, pixel[1]);
    assertEquals(0, pixel[2]);
}

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: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 w  w  w .ja va  2  s .  c  o m
 * @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:nl.nn.adapterframework.http.HttpSender.java

public static String handleMultipartResponse(String contentType, InputStream inputStream,
        ParameterResolutionContext prc, HttpMethod httpMethod) throws IOException, SenderException {
    String result = null;//w  w  w  .  j  a  v  a  2 s  .  c o m
    try {
        InputStreamDataSource dataSource = new InputStreamDataSource(contentType, inputStream);
        MimeMultipart mimeMultipart = new MimeMultipart(dataSource);
        for (int i = 0; i < mimeMultipart.getCount(); i++) {
            BodyPart bodyPart = mimeMultipart.getBodyPart(i);
            boolean lastPart = mimeMultipart.getCount() == i + 1;
            if (i == 0) {
                String charset = org.apache.http.entity.ContentType.parse(bodyPart.getContentType())
                        .getCharset().name();
                InputStream bodyPartInputStream = bodyPart.getInputStream();
                result = Misc.streamToString(bodyPartInputStream, charset);
                if (lastPart) {
                    bodyPartInputStream.close();
                }
            } else {
                // When the last stream is read the
                // httpMethod.releaseConnection() can be called, hence pass
                // httpMethod to ReleaseConnectionAfterReadInputStream.
                prc.getSession().put("multipart" + i, new ReleaseConnectionAfterReadInputStream(
                        lastPart ? httpMethod : null, bodyPart.getInputStream()));
            }
        }
    } catch (MessagingException e) {
        throw new SenderException("Could not read mime multipart response", e);
    }
    return result;
}

From source file:org.sakaiproject.nakamura.smtp.SakaiSmtpServer.java

private void createChildNodeForPart(Session session, int index, BodyPart part, Content message)
        throws MessagingException, AccessDeniedException, StorageClientException, IOException {
    ContentManager contentManager = session.getContentManager();
    String childName = String.format("part%1$03d", index);
    String childPath = message.getPath() + "/" + childName;
    // multipart message
    if (part.getContentType().toLowerCase().startsWith("multipart/")) {
        contentManager.update(new Content(childPath, EMPTY_MAP));
        Content childNode = contentManager.get(childPath);
        writePartPropertiesToNode(part, childNode);
        contentManager.update(childNode);
        MimeMultipart multi = new MimeMultipart(
                new SMTPDataSource(part.getContentType(), part.getInputStream()));
        writeMultipartToNode(session, childNode, multi);
        return;//from  w  w  w.j a  va 2s . c  o m
    }

    // text
    if (!isTextType(part)) {
        writePartAsFile(session, part, childName, message);
        return;
    }

    // not multipart; not text
    contentManager.update(new Content(childPath, EMPTY_MAP));
    Content childNode = contentManager.get(childPath);
    writePartPropertiesToNode(part, childNode);
    contentManager.update(childNode);
    // childNode.setProperty(MessageConstants.PROP_SAKAI_BODY, part.getInputStream());
    contentManager.writeBody(childNode.getPath(), part.getInputStream());
}