Search in sources :

Example 66 with BodyPart

use of javax.mail.BodyPart in project zm-mailbox by Zimbra.

the class TnefConverter method expandTNEF.

/**
     * Performs the TNEF->MIME conversion on any TNEF body parts that
     * make up the given message.
     * @throws ServiceException
     */
private MimeMultipart expandTNEF(MimeBodyPart bp) throws MessagingException, IOException {
    if (!TNEFUtils.isTNEFMimeType(bp.getContentType()))
        return null;
    MimeMessage converted = null;
    // convert TNEF to a MimeMessage and remove it from the parent
    InputStream is = null;
    try {
        TNEFInputStream tnefis = new TNEFInputStream(is = bp.getInputStream());
        converted = TNEFMime.convert(JMSession.getSession(), tnefis);
    // XXX bburtin: nasty hack.  Don't handle OOME since JTNEF can allocate a huge byte
    // array when the TNEF file is malformed.  See bug 42649.
    // } catch (OutOfMemoryError e) {
    //    Zimbra.halt("Ran out of memory while expanding TNEF attachment", e);
    } catch (Throwable t) {
        ZimbraLog.extensions.warn("Conversion failed.  TNEF attachment will not be expanded.", t);
        return null;
    } finally {
        ByteUtil.closeStream(is);
    }
    Object convertedContent = converted.getContent();
    if (!(convertedContent instanceof MimeMultipart)) {
        ZimbraLog.extensions.debug("TNEF attachment doesn't contain valid MimeMultiPart");
        return null;
    }
    MimeMultipart convertedMulti = (MimeMultipart) convertedContent;
    // make sure that all the attachments are marked as attachments
    for (int i = 0; i < convertedMulti.getCount(); i++) {
        BodyPart subpart = convertedMulti.getBodyPart(i);
        if (subpart.getHeader("Content-Disposition") == null)
            subpart.setHeader("Content-Disposition", Part.ATTACHMENT);
    }
    // Create a MimeBodyPart for the converted data.  Currently we're throwing
    // away the top-level message because its content shows up as blank after
    // the conversion.
    MimeBodyPart convertedPart = new ZMimeBodyPart();
    convertedPart.setContent(convertedMulti);
    // If the TNEF object contains calendar data, create an iCalendar version.
    MimeBodyPart icalPart = null;
    if (DebugConfig.enableTnefToICalendarConversion) {
        try {
            TnefToICalendar calConverter = new DefaultTnefToICalendar();
            ZCalendar.DefaultContentHandler icalHandler = new ZCalendar.DefaultContentHandler();
            if (calConverter.convert(mMimeMessage, bp.getInputStream(), icalHandler)) {
                if (icalHandler.getNumCals() > 0) {
                    List<ZVCalendar> cals = icalHandler.getCals();
                    Writer writer = new StringWriter(1024);
                    ICalTok method = null;
                    for (ZVCalendar cal : cals) {
                        cal.toICalendar(writer);
                        if (method == null)
                            method = cal.getMethod();
                    }
                    writer.close();
                    icalPart = new ZMimeBodyPart();
                    icalPart.setText(writer.toString());
                    ContentType ct = new ContentType(MimeConstants.CT_TEXT_CALENDAR);
                    ct.setCharset(MimeConstants.P_CHARSET_UTF8);
                    if (method != null)
                        ct.setParameter("method", method.toString());
                    icalPart.setHeader("Content-Type", ct.toString());
                }
            }
        } catch (ServiceException e) {
            throw new MessagingException("TNEF to iCalendar conversion failure: " + e.getMessage(), e);
        } catch (Throwable t) {
            //don't allow TNEF errors to crash server
            ZimbraLog.extensions.warn("Failed to convert TNEF to iCal", t);
            throw new MessagingException("TNEF to iCalendar conversion failure");
        }
    }
    // create a multipart/alternative for the TNEF and its MIME version
    MimeMultipart altMulti = new ZMimeMultipart("alternative");
    //        altMulti.addBodyPart(bp);
    altMulti.addBodyPart(convertedPart);
    if (icalPart != null)
        altMulti.addBodyPart(icalPart);
    return altMulti;
}
Also used : ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) ContentType(com.zimbra.common.mime.ContentType) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MessagingException(javax.mail.MessagingException) TNEFInputStream(net.freeutils.tnef.TNEFInputStream) InputStream(java.io.InputStream) TNEFInputStream(net.freeutils.tnef.TNEFInputStream) DefaultTnefToICalendar(com.zimbra.cs.util.tnef.DefaultTnefToICalendar) ICalTok(com.zimbra.common.calendar.ZCalendar.ICalTok) ZCalendar(com.zimbra.common.calendar.ZCalendar) ZVCalendar(com.zimbra.common.calendar.ZCalendar.ZVCalendar) StringWriter(java.io.StringWriter) ServiceException(com.zimbra.common.service.ServiceException) MimeMessage(javax.mail.internet.MimeMessage) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimeMultipart(javax.mail.internet.MimeMultipart) TnefToICalendar(com.zimbra.cs.util.tnef.TnefToICalendar) DefaultTnefToICalendar(com.zimbra.cs.util.tnef.DefaultTnefToICalendar) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) StringWriter(java.io.StringWriter) Writer(java.io.Writer)

Example 67 with BodyPart

use of javax.mail.BodyPart in project jmeter by apache.

the class SmtpSampler method getSamplerData.

private String getSamplerData(Message message) throws MessagingException, IOException {
    StringBuilder sb = new StringBuilder();
    // throws ME
    Object content = message.getContent();
    if (content instanceof Multipart) {
        Multipart multipart = (Multipart) content;
        String contentType = multipart.getContentType();
        ContentType ct = new ContentType(contentType);
        String boundary = ct.getParameter("boundary");
        for (int i = 0; i < multipart.getCount(); i++) {
            // throws ME
            sb.append("--");
            sb.append(boundary);
            sb.append("\n");
            // throws ME
            BodyPart bodyPart = multipart.getBodyPart(i);
            // throws IOE, ME
            writeBodyPart(sb, bodyPart);
        }
        sb.append("--");
        sb.append(boundary);
        sb.append("--");
        sb.append("\n");
    } else if (content instanceof BodyPart) {
        BodyPart bodyPart = (BodyPart) content;
        // throws IOE, ME
        writeBodyPart(sb, bodyPart);
    } else if (content instanceof String) {
        sb.append(content);
    } else {
        sb.append("Content has class: ");
        sb.append(content.getClass().getCanonicalName());
    }
    return sb.toString();
}
Also used : BodyPart(javax.mail.BodyPart) Multipart(javax.mail.Multipart) ContentType(javax.mail.internet.ContentType)

Example 68 with BodyPart

use of javax.mail.BodyPart in project jmeter by apache.

the class MailReaderSampler method appendMultiPart.

private void appendMultiPart(SampleResult child, StringBuilder cdata, MimeMultipart mmp) throws MessagingException, IOException {
    String preamble = mmp.getPreamble();
    if (preamble != null) {
        cdata.append(preamble);
    }
    child.setResponseData(cdata.toString(), child.getDataEncodingNoDefault());
    int count = mmp.getCount();
    for (int j = 0; j < count; j++) {
        BodyPart bodyPart = mmp.getBodyPart(j);
        final Object bodyPartContent = bodyPart.getContent();
        final String contentType = bodyPart.getContentType();
        SampleResult sr = new SampleResult();
        sr.setSampleLabel("Part: " + j);
        sr.setContentType(contentType);
        sr.setDataEncoding(RFC_822_DEFAULT_ENCODING);
        sr.setEncodingAndType(contentType);
        sr.sampleStart();
        if (bodyPartContent instanceof InputStream) {
            sr.setResponseData(IOUtils.toByteArray((InputStream) bodyPartContent));
        } else if (bodyPartContent instanceof MimeMultipart) {
            appendMultiPart(sr, cdata, (MimeMultipart) bodyPartContent);
        } else {
            sr.setResponseData(bodyPartContent.toString(), sr.getDataEncodingNoDefault());
        }
        sr.setResponseOK();
        if (sr.getEndTime() == 0) {
            // not been set by any child samples
            sr.sampleEnd();
        }
        child.addSubResult(sr);
    }
}
Also used : BodyPart(javax.mail.BodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) InputStream(java.io.InputStream) SampleResult(org.apache.jmeter.samplers.SampleResult)

Example 69 with BodyPart

use of javax.mail.BodyPart in project stanbol by apache.

the class MessageBodyReaderUtils method fromMultipart.

/**
     * Returns content parsed from {@link MediaType#MULTIPART_FORM_DATA}.
     * It iterates over all {@link BodyPart}s and tries to create {@link RequestData}
     * instances. In case the {@link BodyPart#getContentType()} is not present or
     * can not be parsed, the {@link RequestData#getMediaType()} is set to 
     * <code>null</code>. If {@link BodyPart#getInputStream()} is not defined an
     * {@link IllegalArgumentException} is thrown. The {@link BodyPart#getFileName()}
     * is used for {@link RequestData#getName()}. The ordering of the returned
     * Content instances is the same as within the {@link MimeMultipart} instance
     * parsed from the input stream. <p>
     * This Method does NOT load the data into memory, but returns directly the
     * {@link InputStream}s as returned by the {@link BodyPart}s. Therefore
     * it is saved to be used with big attachments.<p>
     * This Method is necessary because within {@link MessageBodyReader} one
     * can not use the usual annotations as used within Resources. so this method
     * allows to access the data directly from the parameters available from the
     * {@link MessageBodyReader#readFrom(Class, Type, java.lang.annotation.Annotation[], MediaType, javax.ws.rs.core.MultivaluedMap, InputStream)}
     * method<p>
     * To test this Method with curl use:
     * <code><pre>
     * curl -v -X POST -F "content=@{dataFile};type={mimeType}" 
     *      {serviceURL}
     * </pre></code>
     * Note that between {contentParam} and the datafile MUST NOT be a '='!
     * @param mimeData the mime encoded data
     * @param mediaType the mediaType (parsed to the {@link ByteArrayDataSource}
     * constructor)
     * @return the contents parsed from the {@link BodyPart}s
     * @throws IOException an any Exception while reading the stream or 
     * {@link MessagingException} exceptions other than {@link ParseException}s
     * @throws IllegalArgumentException If a {@link InputStream} is not available
     * for any {@link BodyPart} or on {@link ParseException}s while reading the
     * MimeData from the stream.
     */
public static List<RequestData> fromMultipart(InputStream mimeData, MediaType mediaType) throws IOException, IllegalArgumentException {
    ByteArrayDataSource ds = new ByteArrayDataSource(mimeData, mediaType.toString());
    List<RequestData> contents = new ArrayList<RequestData>();
    try {
        MimeMultipart data = new MimeMultipart(ds);
        //For now search the first bodypart that fits and only debug the others
        for (int i = 0; i < data.getCount(); i++) {
            BodyPart bp = data.getBodyPart(i);
            String fileName = bp.getFileName();
            MediaType mt;
            try {
                mt = bp.getContentType() != null ? MediaType.valueOf(bp.getContentType()) : null;
            } catch (IllegalArgumentException e) {
                log.warn(String.format("Unable to parse MediaType form Mime Bodypart %s: " + " fileName %s | Disposition %s | Description %s", i + 1, fileName, bp.getDisposition(), bp.getDescription()), e);
                mt = null;
            }
            InputStream stream = bp.getInputStream();
            if (stream == null) {
                throw new IllegalArgumentException(String.format("Unable to get InputStream for Mime Bodypart %s: " + "mediaType %s fileName %s | Disposition %s | Description %s", i + 1, fileName, bp.getDisposition(), bp.getDescription()));
            } else {
                contents.add(new RequestData(mt, bp.getFileName(), stream));
            }
        }
    } catch (ParseException e) {
        throw new IllegalStateException(String.format("Unable to parse data from %s request", MediaType.MULTIPART_FORM_DATA_TYPE), e);
    } catch (MessagingException e) {
        throw new IOException("Exception while reading " + MediaType.MULTIPART_FORM_DATA_TYPE + " request", e);
    }
    return contents;
}
Also used : BodyPart(javax.mail.BodyPart) MessagingException(javax.mail.MessagingException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) MimeMultipart(javax.mail.internet.MimeMultipart) MediaType(javax.ws.rs.core.MediaType) ParseException(javax.mail.internet.ParseException) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 70 with BodyPart

use of javax.mail.BodyPart in project webservices-axiom by apache.

the class MIMESample method getPart.

public final InputStream getPart(String cid) {
    try {
        MimeMultipart mp = getMultipart();
        BodyPart part = mp.getBodyPart(cid);
        if (part == null) {
            part = mp.getBodyPart("<" + cid + ">");
        }
        if (part == null) {
            throw new IllegalArgumentException("Part " + cid + " not found");
        }
        return part.getInputStream();
    } catch (IOException ex) {
        throw new Error(ex);
    } catch (MessagingException ex) {
        throw new Error(ex);
    }
}
Also used : BodyPart(javax.mail.BodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException)

Aggregations

BodyPart (javax.mail.BodyPart)71 MimeMultipart (javax.mail.internet.MimeMultipart)52 MimeBodyPart (javax.mail.internet.MimeBodyPart)41 MessagingException (javax.mail.MessagingException)23 MimeMessage (javax.mail.internet.MimeMessage)19 Header (javax.mail.Header)15 Multipart (javax.mail.Multipart)15 DispositionNotification (com.sun.mail.dsn.DispositionNotification)13 IOException (java.io.IOException)13 HashMap (java.util.HashMap)13 InternetHeaders (javax.mail.internet.InternetHeaders)13 ByteString (com.linkedin.data.ByteString)12 DataHandler (javax.activation.DataHandler)10 Test (org.testng.annotations.Test)10 Session (javax.mail.Session)9 InternetAddress (javax.mail.internet.InternetAddress)8 Properties (java.util.Properties)7 File (java.io.File)6 InputStream (java.io.InputStream)6 FileDataSource (javax.activation.FileDataSource)6