Search in sources :

Example 11 with ByteArrayDataSource

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

the class ParsedContact method generateMimeMessage.

private static MimeMessage generateMimeMessage(List<Attachment> attachments) throws MessagingException {
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
    MimeMultipart multi = new ZMimeMultipart("mixed");
    int part = 1;
    for (Attachment attach : attachments) {
        ContentDisposition cdisp = new ContentDisposition(Part.ATTACHMENT);
        cdisp.setParameter("filename", attach.getFilename()).setParameter("field", attach.getName());
        MimeBodyPart bp = new ZMimeBodyPart();
        // it gets called before setting Content-Type and CTE headers.
        try {
            bp.setDataHandler(new DataHandler(new ByteArrayDataSource(attach.getContent(), attach.getContentType())));
        } catch (IOException e) {
            throw new MessagingException("could not generate mime part content", e);
        }
        bp.addHeader("Content-Disposition", cdisp.toString());
        bp.addHeader("Content-Type", attach.getContentType());
        bp.addHeader("Content-Transfer-Encoding", MimeConstants.ET_8BIT);
        multi.addBodyPart(bp);
        attach.setPartName(Integer.toString(part++));
    }
    mm.setContent(multi);
    mm.saveChanges();
    return mm;
}
Also used : ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MessagingException(javax.mail.MessagingException) Attachment(com.zimbra.cs.mailbox.Contact.Attachment) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) ContentDisposition(com.zimbra.common.mime.ContentDisposition) MimeMessage(javax.mail.internet.MimeMessage) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimeMultipart(javax.mail.internet.MimeMultipart) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 12 with ByteArrayDataSource

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

the class UUEncodeConverter method visitMessage.

@Override
protected boolean visitMessage(MimeMessage mm, VisitPhase visitKind) throws MessagingException {
    // do the decode in the exit phase
    if (visitKind != VisitPhase.VISIT_END)
        return false;
    MimeMultipart mmp = null;
    try {
        // only check "text/plain" parts for uudecodeable attachments
        if (!mm.isMimeType(MimeConstants.CT_TEXT_PLAIN))
            return false;
        // don't check transfer-encoded parts for uudecodeable attachments
        String cte = mm.getHeader("Content-Transfer-Encoding", null);
        if (cte != null) {
            cte = cte.trim().toLowerCase();
            if (!cte.equals(MimeConstants.ET_7BIT) && !cte.equals(MimeConstants.ET_8BIT) && !cte.equals(MimeConstants.ET_BINARY))
                return false;
        }
        List<UUDecodedFile> uufiles = null;
        // go through top-level text/plain part and extract uuencoded files
        PositionInputStream is = null;
        long size;
        try {
            is = new PositionInputStream(new BufferedInputStream(mm.getInputStream()));
            for (int c = is.read(); c != -1; ) {
                long start = is.getPosition() - 1;
                // check for uuencode header: "begin NNN filename"
                if (c == 'b' && (c = is.read()) == 'e' && (c = is.read()) == 'g' && (c = is.read()) == 'i' && (c = is.read()) == 'n' && ((c = is.read()) == ' ' || c == '\t') && Character.isDigit((c = is.read())) && Character.isDigit(c = is.read()) && Character.isDigit(c = is.read()) && ((c = is.read()) == ' ' || c == '\t')) {
                    StringBuilder sb = new StringBuilder();
                    while ((c = is.read()) != '\r' && c != '\n' && c != -1) sb.append((char) c);
                    String filename = FileUtil.trimFilename(sb.toString().trim());
                    if (c != -1 && filename.length() > 0) {
                        if (uufiles == null)
                            uufiles = new ArrayList<UUDecodedFile>(3);
                        try {
                            uufiles.add(new UUDecodedFile(is, filename, start));
                            // check to make sure that the caller's OK with altering the message
                            if (uufiles.size() == 1 && mCallback != null && !mCallback.onModification())
                                return false;
                        } catch (IOException ioe) {
                        }
                    }
                }
                // skip to the beginning of the next line
                while (c != '\r' && c != '\n' && c != -1) c = is.read();
                while (c == '\r' || c == '\n') c = is.read();
            }
            size = is.getPosition();
        } finally {
            ByteUtil.closeStream(is);
        }
        if (uufiles == null || uufiles.isEmpty())
            return false;
        // create MimeParts for the extracted files
        mmp = new ZMimeMultipart("mixed");
        for (UUDecodedFile uu : uufiles) {
            MimeBodyPart mbp = new ZMimeBodyPart();
            mbp.setHeader("Content-Type", uu.getContentType());
            mbp.setHeader("Content-Disposition", new ContentDisposition(Part.ATTACHMENT).setParameter("filename", uu.getFilename()).toString());
            mbp.setDataHandler(new DataHandler(uu.getDataSource()));
            mmp.addBodyPart(mbp);
            size -= uu.getEndOffset() - uu.getStartOffset();
        }
        // take the remaining text and put it in as the first "related" part
        InputStream isOrig = null;
        try {
            isOrig = mm.getInputStream();
            long offset = 0;
            ByteArrayOutputStream baos = new ByteArrayOutputStream((int) size);
            byte[] buffer = new byte[8192];
            for (UUDecodedFile uu : uufiles) {
                long count = uu.getStartOffset() - offset, numRead;
                while (count > 0 && (numRead = isOrig.read(buffer, 0, (int) Math.min(count, 8192))) >= 0) {
                    baos.write(buffer, 0, (int) numRead);
                    count -= numRead;
                }
                isOrig.skip(uu.getEndOffset() - uu.getStartOffset());
                offset = uu.getEndOffset();
            }
            ByteUtil.copy(isOrig, true, baos, true);
            MimeBodyPart mbp = new ZMimeBodyPart();
            mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(baos.toByteArray(), MimeConstants.CT_TEXT_PLAIN)));
            mmp.addBodyPart(mbp, 0);
        } finally {
            ByteUtil.closeStream(isOrig);
        }
    } catch (MessagingException e) {
        ZimbraLog.extensions.warn("exception while uudecoding message part; skipping part", e);
        return false;
    } catch (IOException e) {
        ZimbraLog.extensions.warn("exception while uudecoding message part; skipping part", e);
        return false;
    }
    // replace the top-level part with a new multipart/related
    mm.setContent(mmp);
    mm.setHeader("Content-Type", mmp.getContentType() + "; generated=true");
    return true;
}
Also used : ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MessagingException(javax.mail.MessagingException) BufferedInputStream(java.io.BufferedInputStream) PositionInputStream(com.zimbra.common.util.ByteUtil.PositionInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ContentDisposition(com.zimbra.common.mime.ContentDisposition) MimeMultipart(javax.mail.internet.MimeMultipart) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) BufferedInputStream(java.io.BufferedInputStream) PositionInputStream(com.zimbra.common.util.ByteUtil.PositionInputStream) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 13 with ByteArrayDataSource

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

the class CalendarMailSender method createCalendarMessage.

public static MimeMessage createCalendarMessage(Account account, Address fromAddr, Address senderAddr, List<Address> toAddrs, String subject, String desc, String descHtml, String uid, ZCalendar.ZVCalendar cal, List<Attach> attaches, boolean replyToSender) throws ServiceException {
    if (desc == null)
        desc = "";
    try {
        MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSmtpSession(account));
        MimeMultipart mpAlternatives = new ZMimeMultipart("alternative");
        if (attaches != null && !attaches.isEmpty()) {
            MimeMultipart mpMixed = new ZMimeMultipart("mixed");
            mm.setContent(mpMixed);
            MimeBodyPart mbpWrapper = new ZMimeBodyPart();
            mbpWrapper.setContent(mpAlternatives);
            mpMixed.addBodyPart(mbpWrapper);
            for (Attach attach : attaches) {
                byte[] rawData = attach.getDecodedData();
                if (rawData == null) {
                    continue;
                }
                ContentDisposition cdisp = new ContentDisposition(Part.ATTACHMENT, true);
                String ctypeAsString = attach.getContentType();
                if (ctypeAsString == null) {
                    ctypeAsString = MimeConstants.CT_APPLICATION_OCTET_STREAM;
                }
                ContentType ctype = new ContentType(ctypeAsString);
                if (attach.getFileName() != null) {
                    ctype.setParameter("name", attach.getFileName());
                    cdisp.setParameter("filename", attach.getFileName());
                }
                MimeBodyPart mbp2 = new ZMimeBodyPart();
                ByteArrayDataSource bads = new ByteArrayDataSource(rawData, ctypeAsString);
                mbp2.setDataHandler(new DataHandler(bads));
                mbp2.setHeader("Content-Type", ctype.toString());
                mbp2.setHeader("Content-Disposition", cdisp.toString());
                mbp2.setHeader("Content-Transfer-Encoding", "base64");
                mpMixed.addBodyPart(mbp2);
            }
        } else {
            mm.setContent(mpAlternatives);
        }
        // Add the text as DESCRIPTION property in the iCalendar part.
        // MS Entourage for Mac wants this.  It ignores text/plain and
        // text/html MIME parts.
        cal.addDescription(desc, null);
        // ///////
        // TEXT part (add me first!)
        MimeBodyPart textPart = new ZMimeBodyPart();
        textPart.setText(desc, MimeConstants.P_CHARSET_UTF8);
        mpAlternatives.addBodyPart(textPart);
        // HTML part is needed to keep Outlook happy as it doesn't know
        // how to deal with a message with only text/plain but no HTML.
        MimeBodyPart htmlPart = new ZMimeBodyPart();
        if (descHtml != null) {
            ContentType ct = new ContentType(MimeConstants.CT_TEXT_HTML);
            ct.setParameter(MimeConstants.P_CHARSET, MimeConstants.P_CHARSET_UTF8);
            htmlPart.setText(descHtml, MimeConstants.P_CHARSET_UTF8);
            htmlPart.setHeader("Content-Type", ct.toString());
        } else {
            htmlPart.setDataHandler(new DataHandler(new HtmlPartDataSource(desc)));
        }
        mpAlternatives.addBodyPart(htmlPart);
        // ///////
        // CALENDAR part
        MimeBodyPart icalPart = makeICalIntoMimePart(cal);
        mpAlternatives.addBodyPart(icalPart);
        // MESSAGE HEADERS
        if (subject != null) {
            mm.setSubject(subject, MimeConstants.P_CHARSET_UTF8);
        }
        if (toAddrs != null) {
            Address[] addrs = new Address[toAddrs.size()];
            toAddrs.toArray(addrs);
            mm.addRecipients(javax.mail.Message.RecipientType.TO, addrs);
        }
        if (fromAddr != null)
            mm.setFrom(fromAddr);
        if (senderAddr != null) {
            mm.setSender(senderAddr);
            if (replyToSender) {
                mm.setReplyTo(new Address[] { senderAddr });
            }
        }
        mm.setSentDate(new Date());
        mm.saveChanges();
        return mm;
    } catch (MessagingException e) {
        throw ServiceException.FAILURE("Messaging Exception while building MimeMessage from invite", e);
    }
}
Also used : ContentType(javax.mail.internet.ContentType) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MessagingException(javax.mail.MessagingException) Attach(com.zimbra.common.calendar.Attach) DataHandler(javax.activation.DataHandler) Date(java.util.Date) ContentDisposition(com.zimbra.common.mime.ContentDisposition) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimeMultipart(javax.mail.internet.MimeMultipart) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 14 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project wildfly by wildfly.

the class JaxrsMultipartProviderTestCase method testJaxRsWithNoApplication.

@Test
public void testJaxRsWithNoApplication() throws Exception {
    String result = performCall("myjaxrs/form");
    DataSource mimeData = new ByteArrayDataSource(result.getBytes(), "multipart/related");
    MimeMultipart mime = new MimeMultipart(mimeData);
    String string = (String) mime.getBodyPart(0).getContent();
    Assert.assertEquals("Hello", string);
    string = (String) mime.getBodyPart(1).getContent();
    Assert.assertEquals("World", string);
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource) Test(org.junit.Test)

Example 15 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project voldemort by voldemort.

the class CoordinatorRestAPITest method doGet.

private TestVersionedValue doGet(String key, Map<String, Object> options) {
    HttpURLConnection conn = null;
    String response = null;
    TestVersionedValue responseObj = null;
    int expectedResponseCode = 200;
    try {
        // Create the right URL and Http connection
        String base64Key = new String(Base64.encodeBase64(key.getBytes()));
        URL url = new URL(this.coordinatorURL + "/" + STORE_NAME + "/" + base64Key);
        conn = (HttpURLConnection) url.openConnection();
        // Set the right headers
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, "1000");
        conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS, Long.toString(System.currentTimeMillis()));
        // options
        if (options != null) {
            if (options.get("timeout") != null && options.get("timeout") instanceof String) {
                conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, (String) options.get("timeout"));
            }
            if (options.get("responseCode") != null && options.get("responseCode") instanceof Integer) {
                expectedResponseCode = (Integer) options.get("responseCode");
            }
        }
        // Check for the right response code
        if (conn.getResponseCode() != expectedResponseCode) {
            System.err.println("Illegal response during GET : " + conn.getResponseMessage());
            fail("Incorrect response received for a HTTP GET request :" + conn.getResponseCode());
        }
        if (conn.getResponseCode() == 404 || conn.getResponseCode() == 408) {
            return null;
        }
        // Buffer the result into a string
        ByteArrayDataSource ds = new ByteArrayDataSource(conn.getInputStream(), "multipart/mixed");
        MimeMultipart mp = new MimeMultipart(ds);
        assertEquals("The number of body parts expected is not 1", 1, mp.getCount());
        MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(0);
        VectorClock vc = RestUtils.deserializeVectorClock(part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]);
        int contentLength = Integer.parseInt(part.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]);
        byte[] bodyPartBytes = new byte[contentLength];
        part.getInputStream().read(bodyPartBytes);
        response = new String(bodyPartBytes);
        responseObj = new TestVersionedValue(response, vc);
    } catch (Exception e) {
        e.printStackTrace();
        fail("Error in sending the REST request");
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return responseObj;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) MimeMultipart(javax.mail.internet.MimeMultipart) VectorClock(voldemort.versioning.VectorClock) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) URL(java.net.URL)

Aggregations

ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)40 DataHandler (javax.activation.DataHandler)27 MimeMultipart (javax.mail.internet.MimeMultipart)18 IOException (java.io.IOException)16 DataSource (javax.activation.DataSource)15 MessagingException (javax.mail.MessagingException)14 MimeBodyPart (javax.mail.internet.MimeBodyPart)13 ByteArrayOutputStream (java.io.ByteArrayOutputStream)12 ByteArrayInputStream (java.io.ByteArrayInputStream)9 InputStream (java.io.InputStream)9 ArrayList (java.util.ArrayList)9 MimeMessage (javax.mail.internet.MimeMessage)7 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)5 List (java.util.List)5 Test (org.junit.Test)5 ContentDisposition (com.zimbra.common.mime.ContentDisposition)4 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)4 Document (ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType.Document)4 Exchange (org.apache.camel.Exchange)3 ByteString (com.linkedin.data.ByteString)2