Example usage for javax.mail BodyPart getFileName

List of usage examples for javax.mail BodyPart getFileName

Introduction

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

Prototype

public String getFileName() throws MessagingException;

Source Link

Document

Get the filename associated with this part, if possible.

Usage

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  .  jav 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.mule.service.http.impl.service.server.grizzly.HttpParser.java

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;//from  w w  w.  jav a  2  s.co m
    List<HttpPart> parts = Lists.newArrayList();

    try {
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }

            if (partName == null && mimeMultipart.getContentType().contains(MULTIPART_RELATED.toString())) {
                String[] contentIdHeader = part.getHeader(CONTENT_ID);
                if (contentIdHeader != null && contentIdHeader.length > 0) {
                    partName = contentIdHeader[0];
                }
            }

            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}

From source file:org.nuxeo.ecm.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  w w w . ja va  2  s. c  om*/
    FileBlob blob = new FileBlob(tmp, ctype, null, fname, null);
    RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() {
        @Override
        public void cleanup(HttpServletRequest req) {
            tmp.delete();
        }
    });
    return blob;
}

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

public static Blob readBlob(HttpServletRequest request, BodyPart part) throws MessagingException, IOException {
    String ctype = part.getContentType();
    String fname = part.getFileName();
    InputStream pin = part.getInputStream();
    final File tmp = Framework.createTempFile("nx-automation-upload-", ".tmp");
    FileUtils.copyToFile(pin, tmp);//from ww  w .j av a2 s  . co  m
    Blob blob = Blobs.createBlob(tmp, ctype, null, fname);
    RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() {
        @Override
        public void cleanup(HttpServletRequest req) {
            tmp.delete();
        }
    });
    return blob;
}

From source file:org.mule.module.http.internal.HttpParser.java

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;//from w w w.  j a va  2s  . c om
    List<HttpPart> parts = Lists.newArrayList();

    try {
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION_PART_HEADER);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }
            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}

From source file:org.apache.hupa.server.utils.MessageUtils.java

/**
 * Extract the attachments present in a mime message
 *
 * @param logger/*  ww w  . j  a va 2 s .  c om*/
 * @param content
 * @return A list of body parts of the attachments
 * @throws MessagingException
 * @throws IOException
 */
static public List<BodyPart> extractMessageAttachments(Log logger, Object content)
        throws MessagingException, IOException {
    ArrayList<BodyPart> ret = new ArrayList<BodyPart>();
    if (content instanceof Multipart) {
        Multipart part = (Multipart) content;
        for (int i = 0; i < part.getCount(); i++) {
            BodyPart bodyPart = part.getBodyPart(i);
            String fileName = bodyPart.getFileName();
            String[] contentId = bodyPart.getHeader("Content-ID");
            if (bodyPart.isMimeType("multipart/*")) {
                ret.addAll(extractMessageAttachments(logger, bodyPart.getContent()));
            } else {
                if (contentId != null || fileName != null) {
                    ret.add(bodyPart);
                }
            }
        }
    } else {
        logger.error("Unknown content: " + content.getClass().getName());
    }
    return ret;
}

From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public static List<Attachment> getMessageAttachments(MimeMessage message) {

    List<Attachment> attachments = new LinkedList<>();

    try {//from   w ww.  j a v  a2  s .com

        Multipart multipartMessage = (Multipart) message.getContent();

        for (int i = 0; i < multipartMessage.getCount(); i++) {
            BodyPart bodyPart = multipartMessage.getBodyPart(i);

            if (bodyPart.getDisposition() != null
                    && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                byte[] content = IOUtils.toByteArray(bodyPart.getInputStream());
                attachments.add(new Attachment(bodyPart.getContentType(), bodyPart.getFileName(),
                        Base64.encodeBase64String(content)));
            }
        }

    } catch (Exception e) {
        // do nothing
    }

    return attachments;

}

From source file:mx.uaq.facturacion.enlace.EmailParserUtils.java

/**
 * Parses any {@link Multipart} instances that contain text or Html attachments,
 * {@link InputStream} instances, additional instances of {@link Multipart}
 * or other attached instances of {@link javax.mail.Message}.
 *
 * Will create the respective {@link EmailFragment}s representing those attachments.
 *
 * Instances of {@link javax.mail.Message} are delegated to
 * {@link #handleMessage(File, javax.mail.Message, List)}. Further instances
 * of {@link Multipart} are delegated to
 * {@link #handleMultipart(File, Multipart, javax.mail.Message, List)}.
 *
 * @param directory Must not be null//from ww w. j a v a 2 s  .co  m
 * @param multipart Must not be null
 * @param mailMessage Must not be null
 * @param emailFragments Must not be null
 */
public static void handleMultipart(File directory, Multipart multipart, javax.mail.Message mailMessage,
        List<EmailFragment> emailFragments) {

    Assert.notNull(directory, "The directory must not be null.");
    Assert.notNull(multipart, "The multipart object to be parsed must not be null.");
    Assert.notNull(mailMessage, "The mail message to be parsed must not be null.");
    Assert.notNull(emailFragments, "The collection of emailfragments must not be null.");

    final int count;

    try {
        count = multipart.getCount();

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(String.format("Number of enclosed BodyPart objects: %s.", count));
        }

    } 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;
        String filename;
        final String disposition;
        final String subject;

        try {

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

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

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

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(String.format(
                    "BodyPart - Content Type: '%s', filename: '%s', disposition: '%s', subject: '%s'",
                    new Object[] { contentType, filename, disposition, subject }));
        }

        if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
            LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", 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) {

            if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
                emailFragments.add(new EmailFragment(directory, i + "-" + filename, content));
                LOGGER.info(String.format("Handdling attachment '%s', type: '%s'", filename, contentType));
            } else {

                final String textFilename;
                final ContentType ct;

                try {
                    ct = new ContentType(contentType);
                } catch (ParseException e) {
                    throw new IllegalStateException("Error while parsing content type '" + contentType + "'.",
                            e);
                }

                if ("text/plain".equalsIgnoreCase(ct.getBaseType())) {
                    textFilename = "message.txt";
                } else if ("text/html".equalsIgnoreCase(ct.getBaseType())) {
                    textFilename = "message.html";
                } else {
                    textFilename = "message.other";
                }

                emailFragments.add(new EmailFragment(directory, textFilename, content));
            }

        } else if (content instanceof InputStream) {

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

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

            emailFragments.add(new EmailFragment(directory, filename, bis.toByteArray()));

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

From source file:de.bht.fpa.mail.s000000.common.mail.imapsync.MessageConverter.java

private static void handleInputStream(InputStream content, BodyPart bodyPart, MessageBuilder messageBuilder) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {/*  www. ja va 2s  .c  o m*/
        int thisLine;
        while ((thisLine = content.read()) != -1) {
            bos.write(thisLine);
        }
        bos.flush();
        byte[] bytes = bos.toByteArray();
        bos.close();

        String encodeBase64String = new String(Base64.encodeBase64(bytes));
        // @formatter:off
        messageBuilder
                .attachment(newAttachmentBuilder().fileName(bodyPart.getFileName()).body(encodeBase64String));
        // @formatter:on
    } catch (Exception e) {
        // ignore
        return;
    }
}

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()));
                }// w  ww  .  j a v  a2 s  .  c  om
            }
        }
    } else if (part.isMimeType("message/rfc822")) {
        saveAttachment((Part) part.getContent(), destDir);
    }
}