Search in sources :

Example 51 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project nhin-d by DirectProject.

the class MDNFactory method create.

/**
     * Answers a MimeMultipartReport containing a
     * Message Delivery Notification as specified by RFC 2298.
     * 
     * @param humanText
     * @param reporting_UA_name
     * @param reporting_UA_product
     * @param original_recipient
     * @param final_recipient
     * @param original_message_id
     * @param disposition
     * @param warning
     * @param failure
     * @param extensions
     * @return MimeMultipartReport
     * @throws MessagingException
     */
public static MimeMultipartReport create(String humanText, String reporting_UA_name, String reporting_UA_product, String original_recipient, String final_recipient, String original_message_id, String error, MdnGateway gateway, Disposition disposition, String warning, String failure, Collection<String> extensions) throws MessagingException {
    if (disposition == null)
        throw new IllegalArgumentException("Disposition can not be null.");
    // Create the message parts. According to RFC 2298, there are two
    // compulsory parts and one optional part...
    MimeMultipartReport multiPart = new MimeMultipartReport();
    multiPart.setReportType("disposition-notification");
    // Part 1: The 'human-readable' part
    MimeBodyPart humanPart = new MimeBodyPart();
    humanPart.setText(humanText);
    multiPart.addBodyPart(humanPart);
    // Part 2: MDN Report Part
    // 1) reporting-ua-field
    StringBuilder mdnReport = new StringBuilder(128);
    if (reporting_UA_name != null && !reporting_UA_name.isEmpty()) {
        mdnReport.append("Reporting-UA: ");
        mdnReport.append((reporting_UA_name == null ? "" : reporting_UA_name));
        mdnReport.append("; ");
        mdnReport.append((reporting_UA_product == null ? "" : reporting_UA_product));
        mdnReport.append("\r\n");
    }
    // 2) original-recipient-field
    if (original_recipient != null && !original_recipient.isEmpty()) {
        mdnReport.append("Original-Recipient: ");
        mdnReport.append("rfc822; ");
        mdnReport.append(original_recipient);
        mdnReport.append("\r\n");
    }
    // 3) final-recipient-field
    if (final_recipient != null && !final_recipient.isEmpty()) {
        mdnReport.append("Final-Recipient: ");
        mdnReport.append("rfc822; ");
        mdnReport.append(final_recipient);
        mdnReport.append("\r\n");
    }
    // 4) original-message-id-field
    if (original_message_id != null && !original_message_id.isEmpty()) {
        mdnReport.append("Original-Message-ID: ");
        mdnReport.append(original_message_id);
        mdnReport.append("\r\n");
    }
    // 5) mdn-gateway-field
    if (gateway != null) {
        mdnReport.append("MDN-Gateway: ");
        mdnReport.append(gateway.toString());
        mdnReport.append("\r\n");
    }
    // 6) error-field
    if (error != null && !error.isEmpty()) {
        mdnReport.append("Error: ");
        mdnReport.append(error);
        mdnReport.append("\r\n");
    }
    // 7) warning-field
    if (warning != null && !warning.isEmpty()) {
        mdnReport.append("Warning: ");
        mdnReport.append(warning);
        mdnReport.append("\r\n");
    }
    // 8) failure-field
    if (failure != null && !failure.isEmpty()) {
        mdnReport.append("Failure: ");
        mdnReport.append(failure);
        mdnReport.append("\r\n");
    }
    // 8) extension-fields
    if (extensions != null && !extensions.isEmpty()) {
        for (String extension : extensions) {
            if (!extension.isEmpty()) {
                mdnReport.append(extension + (extension.contains(":") ? "" : ": "));
                mdnReport.append("\r\n");
            }
        }
    }
    mdnReport.append(disposition.toString());
    mdnReport.append("\r\n");
    MimeBodyPart mdnPart = new MimeBodyPart();
    try {
        // using a DataSource gets around some of the issues with the JAF dynamically loading content handlers that may not work, speicifically
        // the java dsn library and the DispostionNotification class which doesn't know how to handle byte arrays
        ByteArrayDataSource dataSource = new ByteArrayDataSource(new ByteArrayInputStream(mdnReport.toString().getBytes()), "message/disposition-notification");
        mdnPart.setDataHandler(new DataHandler(dataSource));
        multiPart.addBodyPart(mdnPart);
    } catch (IOException e) {
    /*no-op*/
    }
    // described in RFC 1892. It would be a useful addition!        
    return multiPart;
}
Also used : MimeMultipartReport(org.apache.mailet.base.mail.MimeMultipartReport) ByteArrayInputStream(java.io.ByteArrayInputStream) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 52 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project camel by apache.

the class MimeMultipartDataFormatTest method addAttachment.

private void addAttachment(String attContentType, String attText, String attFileName, Map<String, String> headers) throws IOException {
    DataSource ds = new ByteArrayDataSource(attText, attContentType);
    DefaultAttachment attachment = new DefaultAttachment(ds);
    if (headers != null) {
        for (String headerName : headers.keySet()) {
            attachment.addHeader(headerName, headers.get(headerName));
        }
    }
    in.addAttachmentObject(attFileName, attachment);
}
Also used : DefaultAttachment(org.apache.camel.impl.DefaultAttachment) StringContains.containsString(org.hamcrest.core.StringContains.containsString) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource)

Example 53 with ByteArrayDataSource

use of javax.mail.util.ByteArrayDataSource in project camel by apache.

the class CxfMtomProducerPayloadModeTest method testProducer.

@SuppressWarnings("unchecked")
@Test
public void testProducer() throws Exception {
    if (MtomTestHelper.isAwtHeadless(logger, null)) {
        return;
    }
    // START SNIPPET: producer
    Exchange exchange = context.createProducerTemplate().send("direct:testEndpoint", new Processor() {

        public void process(Exchange exchange) throws Exception {
            exchange.setPattern(ExchangePattern.InOut);
            List<Source> elements = new ArrayList<Source>();
            elements.add(new DOMSource(StaxUtils.read(new StringReader(MtomTestHelper.REQ_MESSAGE)).getDocumentElement()));
            CxfPayload<SoapHeader> body = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(), elements, null);
            exchange.getIn().setBody(body);
            exchange.getIn().addAttachment(MtomTestHelper.REQ_PHOTO_CID, new DataHandler(new ByteArrayDataSource(MtomTestHelper.REQ_PHOTO_DATA, "application/octet-stream")));
            exchange.getIn().addAttachment(MtomTestHelper.REQ_IMAGE_CID, new DataHandler(new ByteArrayDataSource(MtomTestHelper.requestJpeg, "image/jpeg")));
        }
    });
    // process response 
    CxfPayload<SoapHeader> out = exchange.getOut().getBody(CxfPayload.class);
    Assert.assertEquals(1, out.getBody().size());
    Map<String, String> ns = new HashMap<String, String>();
    ns.put("ns", MtomTestHelper.SERVICE_TYPES_NS);
    ns.put("xop", MtomTestHelper.XOP_NS);
    XPathUtils xu = new XPathUtils(ns);
    Element oute = new XmlConverter().toDOMElement(out.getBody().get(0));
    Element ele = (Element) xu.getValue("//ns:DetailResponse/ns:photo/xop:Include", oute, XPathConstants.NODE);
    // skip "cid:"
    String photoId = ele.getAttribute("href").substring(4);
    ele = (Element) xu.getValue("//ns:DetailResponse/ns:image/xop:Include", oute, XPathConstants.NODE);
    // skip "cid:"
    String imageId = ele.getAttribute("href").substring(4);
    DataHandler dr = exchange.getOut().getAttachment(decodingReference(photoId));
    Assert.assertEquals("application/octet-stream", dr.getContentType());
    MtomTestHelper.assertEquals(MtomTestHelper.RESP_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream()));
    dr = exchange.getOut().getAttachment(decodingReference(imageId));
    Assert.assertEquals("image/jpeg", dr.getContentType());
    BufferedImage image = ImageIO.read(dr.getInputStream());
    Assert.assertEquals(560, image.getWidth());
    Assert.assertEquals(300, image.getHeight());
// END SNIPPET: producer
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Processor(org.apache.camel.Processor) CxfPayload(org.apache.camel.component.cxf.CxfPayload) HashMap(java.util.HashMap) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) DataHandler(javax.activation.DataHandler) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DOMSource(javax.xml.transform.dom.DOMSource) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Source(javax.xml.transform.Source) BufferedImage(java.awt.image.BufferedImage) XmlConverter(org.apache.camel.converter.jaxp.XmlConverter) Exchange(org.apache.camel.Exchange) XPathUtils(org.apache.cxf.helpers.XPathUtils) StringReader(java.io.StringReader) SoapHeader(org.apache.cxf.binding.soap.SoapHeader) ArrayList(java.util.ArrayList) List(java.util.List) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) Test(org.junit.Test)

Example 54 with ByteArrayDataSource

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

the class Mime method fixBase64MimePartLineFolding.

/**
     * Some devices send wide base64 encoded message body i.e. without line folding.
     * As per RFC https://www.ietf.org/rfc/rfc2045.txt see 6.8.  Base64 Content-Transfer-Encoding
     * "The encoded output stream must be represented in lines of no more than 76 characters each."
     * 
     * To fix the issue here, re-writing the same content to message part.
     * @param mm
     * @throws MessagingException
     * @throws IOException
     */
public static void fixBase64MimePartLineFolding(MimeMessage mm) throws MessagingException, IOException {
    List<MPartInfo> mList = Mime.getParts(mm);
    for (MPartInfo mPartInfo : mList) {
        String ct = mPartInfo.getMimePart().getHeader("Content-Transfer-Encoding", ":");
        if (MimeConstants.ET_BASE64.equalsIgnoreCase(ct)) {
            InputStream io = mPartInfo.getMimePart().getInputStream();
            String ctype = mPartInfo.getMimePart().getContentType();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IOUtils.copy(io, bos);
            DataSource ds = new ByteArrayDataSource(bos.toByteArray(), ctype);
            DataHandler dh = new DataHandler(ds);
            mPartInfo.getMimePart().setDataHandler(dh);
            mPartInfo.getMimePart().setHeader("Content-Transfer-Encoding", ct);
            mPartInfo.getMimePart().setHeader("Content-Type", ctype);
        }
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) PipedInputStream(java.io.PipedInputStream) SharedFileInputStream(javax.mail.util.SharedFileInputStream) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataHandler(javax.activation.DataHandler) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) DataSource(javax.activation.DataSource)

Example 55 with ByteArrayDataSource

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

the class MessageBuilder method create.

public String create() throws MessagingException, ServiceException, IOException {
    if (toRecipient == null) {
        toRecipient = "user1";
    }
    if (from == null) {
        from = "jspiccoli";
    }
    if (date == null) {
        date = new Date();
    }
    if (contentType == null) {
        contentType = MimeConstants.CT_TEXT_PLAIN;
    }
    if (body == null) {
        body = MessageBuilder.DEFAULT_MESSAGE_BODY;
    }
    from = TestUtil.addDomainIfNecessary(from);
    toRecipient = TestUtil.addDomainIfNecessary(toRecipient);
    sender = TestUtil.addDomainIfNecessary(sender);
    MimeMessage msg = addMessageIdHeader ? new ZMimeMessage(JMSession.getSession()) : new MimeMessageWithNoId();
    msg.setRecipient(RecipientType.TO, new JavaMailInternetAddress(toRecipient));
    if (ccRecipient != null) {
        ccRecipient = TestUtil.addDomainIfNecessary(ccRecipient);
        msg.setRecipient(RecipientType.CC, new JavaMailInternetAddress(ccRecipient));
    }
    msg.setFrom(new JavaMailInternetAddress(from));
    if (sender != null) {
        msg.setSender(new JavaMailInternetAddress(sender));
    }
    msg.setSentDate(date);
    msg.setSubject(subject);
    if (attachment == null) {
        // Need to specify the data handler explicitly because JavaMail
        // doesn't know what to do with text/enriched.
        msg.setDataHandler(new DataHandler(new ByteArrayDataSource(body.getBytes(), contentType)));
    } else {
        MimeMultipart multi = new ZMimeMultipart("mixed");
        MimeBodyPart body = new ZMimeBodyPart();
        body.setDataHandler(new DataHandler(new ByteArrayDataSource(this.body.getBytes(), contentType)));
        multi.addBodyPart(body);
        MimeBodyPart attachment = new ZMimeBodyPart();
        attachment.setContent(this.attachment, attachmentContentType);
        attachment.setHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
        multi.addBodyPart(attachment);
        msg.setContent(multi);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.writeTo(out);
    return new String(out.toByteArray());
}
Also used : ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Date(java.util.Date) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) JavaMailInternetAddress(com.zimbra.common.mime.shim.JavaMailInternetAddress) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Aggregations

ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)76 DataHandler (javax.activation.DataHandler)58 InputStream (java.io.InputStream)33 IOException (java.io.IOException)25 MimeMultipart (javax.mail.internet.MimeMultipart)23 Test (org.junit.Test)19 DataSource (javax.activation.DataSource)18 ByteArrayOutputStream (java.io.ByteArrayOutputStream)17 MimeBodyPart (javax.mail.internet.MimeBodyPart)16 ByteArrayInputStream (java.io.ByteArrayInputStream)14 ArrayList (java.util.ArrayList)14 MessagingException (javax.mail.MessagingException)14 MimeMessage (javax.mail.internet.MimeMessage)12 Holder (javax.xml.ws.Holder)7 List (java.util.List)6 AttachmentImpl (org.apache.cxf.attachment.AttachmentImpl)6 Attachment (org.apache.cxf.message.Attachment)6 Date (java.util.Date)5 HashMap (java.util.HashMap)5 ContentDisposition (com.zimbra.common.mime.ContentDisposition)4