Example usage for javax.mail.internet MimeBodyPart getInputStream

List of usage examples for javax.mail.internet MimeBodyPart getInputStream

Introduction

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

Prototype

@Override
public InputStream getInputStream() throws IOException, MessagingException 

Source Link

Document

Return a decoded input stream for this body part's "content".

Usage

From source file:voldemort.restclient.R2Store.java

private List<Versioned<byte[]>> parseGetResponse(ByteString entity) {
    List<Versioned<byte[]>> results = new ArrayList<Versioned<byte[]>>();

    try {/*  w ww  .  j a v a 2  s .  c  o m*/
        // Build the multipart object
        byte[] bytes = new byte[entity.length()];
        entity.copyBytes(bytes, 0);

        ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed");
        MimeMultipart mp = new MimeMultipart(ds);
        for (int i = 0; i < mp.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i);
            String serializedVC = part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0];
            int contentLength = Integer.parseInt(part.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]);

            if (logger.isDebugEnabled()) {
                logger.debug("Received VC : " + serializedVC);
            }
            VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class);

            InputStream input = part.getInputStream();
            byte[] bodyPartBytes = new byte[contentLength];
            input.read(bodyPartBytes);

            VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp());
            results.add(new Versioned<byte[]>(bodyPartBytes, clock));

        }

    } catch (MessagingException e) {
        throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(),
                e);
    } catch (JsonParseException e) {
        throw new VoldemortException(
                "JSON parsing exception while trying to parse GET response " + e.getMessage(), e);
    } catch (JsonMappingException e) {
        throw new VoldemortException(
                "JSON mapping exception while trying to parse GET response " + e.getMessage(), e);
    } catch (IOException e) {
        throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e);
    }
    return results;

}

From source file:voldemort.restclient.R2Store.java

private Map<ByteArray, List<Versioned<byte[]>>> parseGetAllResults(ByteString entity) {
    Map<ByteArray, List<Versioned<byte[]>>> results = new HashMap<ByteArray, List<Versioned<byte[]>>>();

    try {/*from w  ww . j a va2 s .  c  o  m*/
        // Build the multipart object
        byte[] bytes = new byte[entity.length()];
        entity.copyBytes(bytes, 0);

        // Get the outer multipart object
        ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed");
        MimeMultipart mp = new MimeMultipart(ds);
        for (int i = 0; i < mp.getCount(); i++) {

            // Get an individual part. This contains all the versioned
            // values for a particular key referenced by content-location
            MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i);

            // Get the key
            String contentLocation = part.getHeader("Content-Location")[0];
            String base64Key = contentLocation.split("/")[2];
            ByteArray key = new ByteArray(RestUtils.decodeVoldemortKey(base64Key));

            if (logger.isDebugEnabled()) {
                logger.debug("Content-Location : " + contentLocation);
                logger.debug("Base 64 key : " + base64Key);
            }

            // Create an array list for holding all the (versioned values)
            List<Versioned<byte[]>> valueResultList = new ArrayList<Versioned<byte[]>>();

            // Get the nested Multi-part object. This contains one part for
            // each unique versioned value.
            ByteArrayDataSource nestedDS = new ByteArrayDataSource((String) part.getContent(),
                    "multipart/mixed");
            MimeMultipart valueParts = new MimeMultipart(nestedDS);

            for (int valueId = 0; valueId < valueParts.getCount(); valueId++) {

                MimeBodyPart valuePart = (MimeBodyPart) valueParts.getBodyPart(valueId);
                String serializedVC = valuePart.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0];
                int contentLength = Integer.parseInt(valuePart.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]);

                if (logger.isDebugEnabled()) {
                    logger.debug("Received serialized Vector Clock : " + serializedVC);
                }

                VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class);

                // get the value bytes
                InputStream input = valuePart.getInputStream();
                byte[] bodyPartBytes = new byte[contentLength];
                input.read(bodyPartBytes);

                VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp());
                valueResultList.add(new Versioned<byte[]>(bodyPartBytes, clock));

            }
            results.put(key, valueResultList);
        }

    } catch (MessagingException e) {
        throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(),
                e);
    } catch (JsonParseException e) {
        throw new VoldemortException(
                "JSON parsing exception while trying to parse GET response " + e.getMessage(), e);
    } catch (JsonMappingException e) {
        throw new VoldemortException(
                "JSON mapping exception while trying to parse GET response " + e.getMessage(), e);
    } catch (IOException e) {
        throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e);
    }
    return results;

}

From source file:org.apache.olingo.fit.V4Services.java

@Override
public InputStream exploreMultipart(final List<Attachment> attachments, final String boundary,
        final boolean continueOnError) throws IOException {

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    Response res = null;//from ww w .  ja v a 2s .co m
    boolean goon = true;
    for (int i = 0; i < attachments.size() && goon; i++) {
        try {
            final Attachment obj = attachments.get(i);
            bos.write(("--" + boundary).getBytes());
            bos.write(Constants.CRLF);

            final Object content = obj.getDataHandler().getContent();
            if (content instanceof MimeMultipart) {
                final ByteArrayOutputStream chbos = new ByteArrayOutputStream();
                String lastContebtID = null;
                try {
                    final Map<String, String> references = new HashMap<String, String>();

                    final String cboundary = "changeset_" + UUID.randomUUID().toString();
                    chbos.write(("Content-Type: multipart/mixed;boundary=" + cboundary).getBytes());
                    chbos.write(Constants.CRLF);
                    chbos.write(Constants.CRLF);

                    for (int j = 0; j < ((MimeMultipart) content).getCount(); j++) {
                        final MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) content).getBodyPart(j);
                        lastContebtID = part.getContentID();
                        addChangesetItemIntro(chbos, lastContebtID, cboundary);

                        res = bodyPartRequest(new MimeBodyPart(part.getInputStream()), references);
                        if (!continueOnError && (res == null || res.getStatus() >= 400)) {
                            throw new Exception("Failure processing changeset");
                        }

                        addSingleBatchResponse(res, lastContebtID, chbos);
                        references.put("$" + lastContebtID, res.getHeaderString("Location"));
                    }

                    chbos.write(("--" + cboundary + "--").getBytes());
                    chbos.write(Constants.CRLF);

                    bos.write(chbos.toByteArray());
                    IOUtils.closeQuietly(chbos);
                } catch (Exception e) {
                    LOG.warn("While processing changeset", e);
                    IOUtils.closeQuietly(chbos);

                    addItemIntro(bos, lastContebtID);

                    if (res == null || res.getStatus() < 400) {
                        addErrorBatchResponse(e, "1", bos);
                    } else {
                        addSingleBatchResponse(res, lastContebtID, bos);
                    }

                    goon = continueOnError;
                }
            } else {
                addItemIntro(bos);

                res = bodyPartRequest(new MimeBodyPart(obj.getDataHandler().getInputStream()));

                if (res.getStatus() >= 400) {
                    goon = continueOnError;
                    throw new Exception("Failure processing batch item");
                }

                addSingleBatchResponse(res, bos);
            }
        } catch (Exception e) {
            if (res == null || res.getStatus() < 400) {
                addErrorBatchResponse(e, bos);
            } else {
                addSingleBatchResponse(res, bos);
            }
        }
    }

    bos.write(("--" + boundary + "--").getBytes());

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java

private void saveAttachment(Part part, InboxEvent inboxentry) throws Exception {

    MimeBodyPart mbp = (MimeBodyPart) part;
    String fileName = mbp.getFileName();
    String fileType = mbp.getContentType();
    String fileId = mbp.getContentID();
    String fileEncoding = mbp.getEncoding();
    String attContent;/*  w w  w . j a v  a  2  s.  c  om*/

    if (fileName == null || fileName.length() < 2) {
        fileName = new String("Unknown");
        if (fileType.indexOf("name") > 0) {
            int i = fileType.indexOf("name");
            int j = fileType.indexOf("\"", i + 1);
            if (j != -1) {
                int k = fileType.indexOf("\"", j + 1);
                if (k != -1) {
                    fileName = fileType.substring(j + 1, k);
                }

            } else {
                int k = fileType.indexOf(";", i + 1);
                if (k != -1) {
                    fileName = fileType.substring(i + 5, k);

                } else {
                    fileName = fileType.substring(i + 5, fileType.length());
                }

            }
        }
    }

    InboxAttachment entryItem = new InboxAttachment();

    entryItem.setFileName(fileName);
    if (fileType != null)
        entryItem.setContentType(fileType);

    if (mbp.getContent() instanceof InputStream) {
        InputStream is = new Base64.InputStream(mbp.getInputStream(), Base64.ENCODE);

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        StringBuffer att = new StringBuffer();
        String thisLine = reader.readLine();

        while (thisLine != null) {
            att.append(thisLine);
            thisLine = reader.readLine();
        }

        attContent = att.toString();
        //           MimeUtility.encode(part.getOutputStream(), "base64");
        //           attachments += saveFile(part.getFileName(), part.getInputStream());

    } else {
        attContent = part.getContent().toString();
    }

    entryItem.setContent(attContent);
    entryItem.setContentId(fileId);

    inboxentry.addInboxAttachment(entryItem);

}

From source file:org.xwiki.contrib.mail.internal.JavamailMessageParser.java

/**
 * Extracts mail content, and manage attachments.
 * /*from   ww  w.ja v a2  s .  c  o  m*/
 * @param part
 * @return
 * @throws MessagingException
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
public MailContent extractMailContent(Part part) throws MessagingException, IOException {
    logger.debug("extractMailContent...");

    if (part == null) {
        return null;
    }
    MailContent mailContent = new MailContent();

    if (part.isMimeType("application/pkcs7-mime") || part.isMimeType("multipart/encrypted")) {
        logger.debug("Mail content is ENCRYPTED");
        mailContent.setText(
                "<<<This e-mail part is encrypted. Text Content and attachments of encrypted e-mails are not published in Mail Archiver to avoid disclosure of restricted or confidential information.>>>");
        mailContent.setHtml(
                "<i>&lt;&lt;&lt;This e-mail is encrypted. Text Content and attachments of encrypted e-mails are not published in Mail Archiver to avoid disclosure of restricted or confidential information.&gt;&gt;&gt;</i>");
        mailContent.setEncrypted(true);

        return mailContent;
    } else {
        mailContent = extractPartsContent(part);
    }
    // TODO : filling attachment cids and creating xwiki attachments should be done in same method
    HashMap<String, String> attachmentsMap = fillAttachmentContentIds(mailContent.getAttachments());
    String fileName = "";
    for (MimeBodyPart currentbodypart : mailContent.getAttachments()) {
        try {
            String cid = currentbodypart.getContentID();
            fileName = currentbodypart.getFileName();

            // replace by correct name if filename was renamed (multiple attachments with same name)
            if (attachmentsMap.containsKey(cid)) {
                fileName = attachmentsMap.get(cid);
            }
            logger.debug("Treating attachment: " + fileName + " with contentid " + cid);
            if (fileName == null) {
                fileName = "file.ext";
            }
            if (fileName.equals("oledata.mso") || fileName.endsWith(".wmz") || fileName.endsWith(".emz")) {
                logger.debug("Garbaging Microsoft crap !");
            } else {
                String disposition = currentbodypart.getDisposition();
                String attcontentType = currentbodypart.getContentType().toLowerCase();

                logger.debug("Treating attachment of type: " + attcontentType);

                /*
                 * XWikiAttachment wikiAttachment = new XWikiAttachment(); wikiAttachment.setFilename(fileName);
                 * wikiAttachment.setContent(currentbodypart.getInputStream());
                 */

                MailAttachment wikiAttachment = new MailAttachment();
                wikiAttachment.setCid(cid);
                wikiAttachment.setFilename(fileName);
                byte[] filedatabytes = IOUtils.toByteArray(currentbodypart.getInputStream());
                wikiAttachment.setData(filedatabytes);

                mailContent.addWikiAttachment(cid, wikiAttachment);

            } // end if
        } catch (Exception e) {
            logger.warn("Attachment " + fileName + " could not be treated", e);
        }
    }

    return mailContent;
}

From source file:org.xwiki.contrib.mailarchive.xwiki.internal.XWikiPersistence.java

private int addAttachmentsToMailPage(final XWikiDocument doc1, final ArrayList<MimeBodyPart> bodyparts,
        final HashMap<String, String> attachmentsMap) throws MessagingException {
    int nb = 0;/*from  ww w.  ja v  a2s .  c o m*/
    for (MimeBodyPart bodypart : bodyparts) {
        String fileName = bodypart.getFileName();
        String cid = bodypart.getContentID();

        try {
            // replace by correct name if filename was renamed (multiple attachments with same name)
            if (attachmentsMap.containsKey(cid)) {
                fileName = attachmentsMap.get(cid);
            }
            logger.debug("Treating attachment: " + fileName + " with contentid " + cid);
            if (fileName == null) {
                fileName = "fichier.doc";
            }
            if (fileName.equals("oledata.mso") || fileName.endsWith(".wmz") || fileName.endsWith(".emz")) {
                logger.debug("Not treating Microsoft crap !");
            } else {
                String disposition = bodypart.getDisposition();
                String contentType = bodypart.getContentType().toLowerCase();

                logger.debug("Treating attachment of type: " + contentType);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                OutputStream out = new BufferedOutputStream(baos);
                // We can't just use p.writeTo() here because it doesn't
                // decode the attachment. Instead we copy the input stream
                // onto the output stream which does automatically decode
                // Base-64, quoted printable, and a variety of other formats.
                InputStream ins = new BufferedInputStream(bodypart.getInputStream());
                int b = ins.read();
                while (b != -1) {
                    out.write(b);
                    b = ins.read();
                }
                out.flush();
                out.close();
                ins.close();

                logger.debug("Treating attachment step 3: " + fileName);

                byte[] data = baos.toByteArray();
                logger.debug("Ready to attach attachment: " + fileName);
                addAttachmentToPage(doc1, fileName, data);
                nb++;
            } // end if
        } catch (Exception e) {
            logger.warn("Attachment " + fileName + " could not be treated", e);
        }
    } // end for all attachments
    return nb;
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
   Use depth-first search to go through MIME-Parts recursively.
   @param p Part to begin with/*from  w  ww .ja v  a 2  s. co  m*/
*/
protected void parseMIMEContent(Part p, XMLMessagePart parent_part, String msgid) throws MessagingException {
    StringBuilder content = new StringBuilder(1000);
    XMLMessagePart xml_part;
    try {
        if (p.getContentType().toUpperCase().startsWith("TEXT/HTML")) {
            /* The part is a text in HTML format. We will try to use "Tidy" to create a well-formatted
               XHTML DOM from it and then remove JavaScript and other "evil" stuff.
               For replying to such a message, it will be useful to just remove all of the tags and display
               only the text.
            */

            xml_part = parent_part.createPart("html");

            /****************************************************
             * LEAVING THESE OLD XML PARSERS COMMENTED OUT
             * until know that the new Parser tactic parses HTML properly
             * (or adequately).  See the ** comment below.
            /* Here we create a DOM tree.
            //Tidy tidy=new Tidy();
            //tidy.setUpperCaseTags(true);
            //Document htmldoc=tidy.parseDOM(p.getInputStream(),null);
            //              org.cyberneko.html.parsers.DOMParser parser =
            //                  new org.cyberneko.html.parsers.DOMParser();
            //              DOMParser parser = new DOMParser(new HTMLConfiguration());
            //              parser.parse(new InputSource(p.getInputStream()));
            //              Document htmldoc = parser.getDocument();
                    
            // instantiate a DOM implementation
            DOM dom = new com.docuverse.dom.DOM();
            // install the SAX driver for Swing HTML parser
            dom.setProperty("sax.driver", "com.docuverse.html.swing.SAXDriver");
                    
            // install HTML element factory
            dom.setFactory(new com.docuverse.dom.html.HTMLFactory());
            // ** N.B.  WITH docuverse AND NekoHTML, THE PARSER WAS
            // HTML-Specific.  We are now using generic XML parser.
            // Is that adequate?
                    
            // now just open the document
            Document htmldoc = (Document)dom.readDocument(p.getInputStream());
            */
            javax.xml.parsers.DocumentBuilder parser = javax.xml.parsers.DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document htmldoc = parser.parse(p.getInputStream());

            if (htmldoc == null) {
                log.error("Document was null!");
                // Why not throwing?
            }

            //dom.writeDocument(htmldoc,"/tmp/test.xml");

            /* Now let's look for all the malicious JavaScript and other <SCRIPT> tags,
               URLS containing the "javascript:" and tags containing "onMouseOver" and such
               stuff. */
            //              if(user.getBoolVar("filter javascript")) new JavaScriptCleaner(htmldoc);
            new JavaScriptCleaner(htmldoc);

            //dom.writeDocument(htmldoc,"/tmp/test2.xml");

            //XMLCommon.debugXML(htmldoc);
            /* HTML doesn't allow us to do such fancy stuff like different quote colors,
               perhaps this will be implemented in the future */

            /* So we just add this HTML document to the message part, which will deal with
               removing headers and tags that we don't need */
            xml_part.addContent(htmldoc);

        } else if (p.getContentType().toUpperCase().startsWith("TEXT")
                || p.getContentType().toUpperCase().startsWith("MESSAGE")) {
            /* The part is a standard message part in some incarnation of
               text (html or plain).  We should decode it and take care of
               some extra issues like recognize quoted parts, filter
               JavaScript parts and replace smileys with smiley-icons if the
               user has set wantsFancy() */

            xml_part = parent_part.createPart("text");
            // TODO:
            log.debug("text hit");

            BufferedReader in;
            if (p instanceof MimeBodyPart) {
                int size = p.getSize();
                MimeBodyPart mpb = (MimeBodyPart) p;
                InputStream is = mpb.getInputStream();

                /* Workaround for Java or Javamail Bug */
                is = new BufferedInputStream(is);
                ByteStore ba = ByteStore.getBinaryFromIS(is, size);
                in = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(ba.getBytes())));
                /* End of workaround */
                size = is.available();

            } else {
                in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            }

            log.debug("Content-Type: " + p.getContentType());

            String token = "";
            int quote_level = 0, old_quotelevel = 0;
            boolean javascript_mode = false;
            /* Read in the message part line by line */
            while ((token = in.readLine()) != null) {
                /* First decode all language and MIME dependant stuff */
                // Default to ISO-8859-1 (Western Latin 1)
                String charset = "ISO-8859-1";

                // Check whether the part contained a charset in the content-type header
                StringTokenizer tok2 = new StringTokenizer(p.getContentType(), ";=");
                String blah = tok2.nextToken();
                if (tok2.hasMoreTokens()) {
                    blah = tok2.nextToken().trim();
                    if (blah.toLowerCase().equals("charset") && tok2.hasMoreTokens()) {
                        charset = tok2.nextToken().trim();
                    }
                }

                try {
                    token = new String(token.getBytes(), charset);
                } catch (UnsupportedEncodingException ex1) {
                    log.info("Java Engine does not support charset " + charset
                            + ". Trying to convert from MIME ...");

                    try {
                        charset = MimeUtility.javaCharset(charset);
                        token = new String(token.getBytes(), charset);

                    } catch (UnsupportedEncodingException ex) {
                        log.warn("Converted charset (" + charset
                                + ") does not work. Using default charset (ouput may contain errors)");
                        token = new String(token.getBytes());
                    }
                }

                /* Here we figure out which quote level this line has, simply by counting how many
                   ">" are in front of the line, ignoring all whitespaces. */
                int current_quotelevel = Helper.getQuoteLevel(token);

                /* When we are in a different quote level than the last line, we append all we got
                   so far to the part with the old quotelevel and begin with a clean String buffer */
                if (current_quotelevel != old_quotelevel) {
                    xml_part.addContent(content.toString(), old_quotelevel);
                    old_quotelevel = current_quotelevel;
                    content = new StringBuilder(1000);
                }

                if (user.wantsBreakLines()) {
                    Enumeration enumVar = Helper.breakLine(token, user.getMaxLineLength(), current_quotelevel);

                    while (enumVar.hasMoreElements()) {
                        String s = (String) enumVar.nextElement();
                        if (user.wantsShowFancy()) {
                            content.append(Fancyfier.apply(s)).append("\n");
                        } else {
                            content.append(s).append("\n");
                        }
                    }
                } else {
                    if (user.wantsShowFancy()) {
                        content.append(Fancyfier.apply(token)).append("\n");
                    } else {
                        content.append(token).append("\n");
                    }
                }
            }
            xml_part.addContent(content.toString(), old_quotelevel);
            // Why the following code???
            content = new StringBuilder(1000);
        } else if (p.getContentType().toUpperCase().startsWith("MULTIPART/ALTERNATIVE")) {
            /* This is a multipart/alternative part. That means that we should pick one of
               the formats and display it for this part. Our current precedence list is
               to choose HTML first and then to choose plain text. */
            MimeMultipart m = (MimeMultipart) p.getContent();
            String[] preferred = { "TEXT/HTML", "TEXT" };
            boolean found = false;
            int alt = 0;
            // Walk though our preferred list of encodings. If we have found a fitting part,
            // decode it and replace it for the parent (this is what we really want with an
            // alternative!)
            /**
            findalt: while(!found && alt < preferred.length) {
            for(int i=0;i<m.getCount();i++) {
            Part p2=m.getBodyPart(i);
            if(p2.getContentType().toUpperCase().startsWith(preferred[alt])) {
                parseMIMEContent(p2,parent_part,msgid);
                found=true;
                break findalt;
            }
            }
            alt++;
            }
            **/
            /**
             * When user try to reply a mail, there may be 3 conditions:
             * 1. only TEXT exists.
             * 2. both HTML and TEXT exist.
             * 3. only HTML exists.
             *
             * We have to choose which part should we quote, that is, we must
             * decide the prority of parts to quote. Since quoting HTML is not
             * easy and precise (consider a html: <body><div><b>some text..</b>
             * </div></body>. Even we try to get text node under <body>, we'll
             * just get nothing, because "some text..." is marked up by
             * <div><b>. There is no easy way to retrieve text from html
             * unless we parse the html to analyse its semantics.
             *
             * Here is our policy for alternative part:
             * 1. Displays HTML but hides TEXT.
             * 2. When replying this mail, try to quote TEXT part. If no TEXT
             *    part exists, quote HTML in best effort(use
             *    XMLMessagePart.quoteContent() by Sebastian Schaffert.)
             */
            while (alt < preferred.length) {
                for (int i = 0; i < m.getCount(); i++) {
                    Part p2 = m.getBodyPart(i);
                    if (p2.getContentType().toUpperCase().startsWith(preferred[alt])) {
                        log.debug("Processing: " + p2.getContentType());
                        parseMIMEContent(p2, parent_part, msgid);
                        found = true;
                        break;
                    }
                }
                /**
                 * If we've selected HTML part from alternative part, the TEXT
                 * part should be hidden from display but keeping in XML for
                 * later quoting operation.
                 *
                 * Of course, this requires some modification on showmessage.xsl.
                 */
                if (found && (alt == 1)) {
                    Node textPartNode = parent_part.getPartElement().getLastChild();
                    NamedNodeMap attributes = textPartNode.getAttributes();
                    boolean hit = false;

                    for (int i = 0; i < attributes.getLength(); ++i) {
                        Node attr = attributes.item(i);
                        // If type=="TEXT", add a hidden attribute.
                        if (attr.getNodeName().toUpperCase().equals("TYPE")
                                && attr.getNodeValue().toUpperCase().equals("TEXT")) {
                            ((Element) textPartNode).setAttribute("hidden", "true");
                        }
                    }
                }
                alt++;
            }
            if (!found) {
                // If we didn't find one of our preferred encodings, choose the first one
                // simply pass the parent part because replacement is what we really want with
                // an alternative.
                parseMIMEContent(m.getBodyPart(0), parent_part, msgid);
            }

        } else if (p.getContentType().toUpperCase().startsWith("MULTIPART/")) {
            /* This is a standard multipart message. We should recursively walk thorugh all of
               the parts and decode them, appending as children to the current part */

            xml_part = parent_part.createPart("multi");

            MimeMultipart m = (MimeMultipart) p.getContent();
            for (int i = 0; i < m.getCount(); i++) {
                parseMIMEContent(m.getBodyPart(i), xml_part, msgid);
            }
        } else {
            /* Else treat the part as a binary part that the user should either download or
               get displayed immediately in case of an image */
            InputStream in = null;
            String type = "";
            if (p.getContentType().toUpperCase().startsWith("IMAGE/JPG")
                    || p.getContentType().toUpperCase().startsWith("IMAGE/JPEG")) {
                type = "jpg";
                xml_part = parent_part.createPart("image");
            } else if (p.getContentType().toUpperCase().startsWith("IMAGE/GIF")) {
                type = "gif";
                xml_part = parent_part.createPart("image");
            } else if (p.getContentType().toUpperCase().startsWith("IMAGE/PNG")) {
                type = "png";
                xml_part = parent_part.createPart("image");
            } else {
                xml_part = parent_part.createPart("binary");
            }
            int size = p.getSize();
            if (p instanceof MimeBodyPart) {
                MimeBodyPart mpb = (MimeBodyPart) p;
                log.debug("MIME Body part (image), Encoding: " + mpb.getEncoding());
                InputStream is = mpb.getInputStream();

                /* Workaround for Java or Javamail Bug */
                in = new BufferedInputStream(is);
                ByteStore ba = ByteStore.getBinaryFromIS(in, size);
                in = new ByteArrayInputStream(ba.getBytes());
                /* End of workaround */
                size = in.available();

            } else {
                log.warn("No MIME Body part!!");
                // Is this unexpected?  Consider changing log level.
                in = p.getInputStream();
            }

            ByteStore data = ByteStore.getBinaryFromIS(in, size);
            if (mime_parts_decoded == null) {
                mime_parts_decoded = new HashMap<String, ByteStore>();
            }
            String name = p.getFileName();
            if (name == null || name.equals("")) {
                // Try an other way
                String headers[] = p.getHeader("Content-Disposition");
                int pos = -1;
                if (headers.length == 1) {
                    pos = headers[0].indexOf("filename*=") + 10;
                }
                if (pos != -1) {
                    int charsetEnds = headers[0].indexOf("''", pos);
                    String charset = headers[0].substring(pos, charsetEnds);
                    String encodedFileName = headers[0].substring(charsetEnds + 2);
                    encodedFileName = "=?" + charset + "?Q?" + encodedFileName.replace('%', '=') + "?=";
                    name = MimeUtility.decodeText(encodedFileName);
                } else {
                    name = "unknown." + type;
                }
            }
            // Eliminate space characters. Should do some more things in the future
            name = name.replace(' ', '_');
            data.setContentType(p.getContentType());
            data.setContentEncoding("BINARY");
            mime_parts_decoded.put(msgid + "/" + name, data);

            /**
             * For multibytes language system, we have to separate filename into
             * 2 format: one for display (UTF-8 encoded), another for encode the
             * url of hyperlink.
             * `filename' is for display, while `hrefFileName' is for hyperlink.
             * To make use of these two attributes, `showmessage.xsl' is slightly
             * modified.
             */
            data.setName(name);
            xml_part.setAttribute("filename", name);
            // Transcode name into UTF-8 bytes then make a new ISO8859_1 string to encode URL.
            xml_part.setAttribute("hrefFileName", name);
            xml_part.setAttribute("size", size + "");
            String description = p.getDescription() == null ? "" : p.getDescription();
            xml_part.setAttribute("description", description);
            StringTokenizer tok = new StringTokenizer(p.getContentType(), ";");
            xml_part.setAttribute("content-type", tok.nextToken().toLowerCase());
        }
    } catch (java.io.IOException ex) {
        log.error("Failed to parse mime content", ex);
    } catch (MessagingException ex) {
        log.error("Failed to parse mime content", ex);
    } catch (Exception ex) {
        log.error("Failed to parse mime content", ex);
    }
}

From source file:org.apache.olingo.fit.Services.java

private InputStream exploreMultipart(final List<Attachment> attachments, final String boundary,
        final boolean continueOnError) throws IOException {

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    Response res = null;//from ww  w . j  a  v a2 s.co m
    boolean goon = true;
    for (int i = 0; i < attachments.size() && goon; i++) {
        try {
            final Attachment obj = attachments.get(i);
            bos.write(("--" + boundary).getBytes());
            bos.write(Constants.CRLF);

            final Object content = obj.getDataHandler().getContent();
            if (content instanceof MimeMultipart) {
                final ByteArrayOutputStream chbos = new ByteArrayOutputStream();
                String lastContebtID = null;
                try {
                    final Map<String, String> references = new HashMap<String, String>();

                    final String cboundary = "changeset_" + UUID.randomUUID().toString();
                    chbos.write(("Content-Type: multipart/mixed;boundary=" + cboundary).getBytes());
                    chbos.write(Constants.CRLF);
                    chbos.write(Constants.CRLF);

                    for (int j = 0; j < ((MimeMultipart) content).getCount(); j++) {
                        final MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) content).getBodyPart(j);
                        lastContebtID = part.getContentID();
                        addChangesetItemIntro(chbos, lastContebtID, cboundary);

                        res = bodyPartRequest(new MimeBodyPart(part.getInputStream()), references);
                        if (!continueOnError && (res == null || res.getStatus() >= 400)) {
                            throw new Exception("Failure processing changeset");
                        }

                        addSingleBatchResponse(res, lastContebtID, chbos);
                        references.put("$" + lastContebtID, res.getHeaderString("Location"));
                    }

                    chbos.write(("--" + cboundary + "--").getBytes());
                    chbos.write(Constants.CRLF);

                    bos.write(chbos.toByteArray());
                    IOUtils.closeQuietly(chbos);
                } catch (Exception e) {
                    LOG.warn("While processing changeset", e);
                    IOUtils.closeQuietly(chbos);

                    addItemIntro(bos, lastContebtID);

                    if (res == null || res.getStatus() < 400) {
                        addErrorBatchResponse(e, "1", bos);
                    } else {
                        addSingleBatchResponse(res, lastContebtID, bos);
                    }

                    goon = continueOnError;
                }
            } else {
                addItemIntro(bos, null);

                res = bodyPartRequest(new MimeBodyPart(obj.getDataHandler().getInputStream()),
                        Collections.<String, String>emptyMap());

                if (res.getStatus() >= 400) {
                    goon = continueOnError;
                    throw new Exception("Failure processing batch item");
                }

                addSingleBatchResponse(res, bos);
            }
        } catch (Exception e) {
            if (res == null || res.getStatus() < 400) {
                addErrorBatchResponse(e, bos);
            } else {
                addSingleBatchResponse(res, bos);
            }
        }
    }

    bos.write(("--" + boundary + "--").getBytes());

    return new ByteArrayInputStream(bos.toByteArray());
}

From source file:org.nuclos.server.ruleengine.RuleInterface.java

private void getAttachments(Multipart multipart, NuclosMail mail) throws MessagingException, IOException {
    for (int i = 0; i < multipart.getCount(); i++) {
        Part part = multipart.getBodyPart(i);
        String disposition = part.getDisposition();
        MimeBodyPart mimePart = (MimeBodyPart) part;
        logger.debug("Disposition: " + disposition + "; Part ContentType: " + mimePart.getContentType());

        if (part.getContent() instanceof Multipart) {
            logger.debug("Start child Multipart.");
            Multipart childmultipart = (Multipart) part.getContent();
            getAttachments(childmultipart, mail);
            logger.debug("Finished child Multipart.");
        } else if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            logger.debug("Attachment: " + mimePart.getFileName());
            InputStream in = mimePart.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buf = new byte[8192];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);//  w w w  .j  a  v  a 2s  .  c  o  m
            }
            mail.addAttachment(new NuclosFile(mimePart.getFileName(), out.toByteArray()));
        }
    }
}