Search in sources :

Example 6 with DefaultAttachment

use of org.apache.camel.impl.DefaultAttachment in project camel by apache.

the class MailAttachmentTest method testSendAndReceiveMailWithAttachments.

@Test
public void testSendAndReceiveMailWithAttachments() throws Exception {
    // clear mailbox
    Mailbox.clearAll();
    // START SNIPPET: e1
    // create an exchange with a normal body and attachment to be produced as email
    Endpoint endpoint = context.getEndpoint("smtp://james@mymailserver.com?password=secret");
    // create the exchange with the mail message that is multipart with a file and a Hello World text/plain message.
    Exchange exchange = endpoint.createExchange();
    Message in = exchange.getIn();
    in.setBody("Hello World");
    DefaultAttachment att = new DefaultAttachment(new FileDataSource("src/test/data/logo.jpeg"));
    att.addHeader("Content-Description", "some sample content");
    in.addAttachmentObject("logo.jpeg", att);
    // create a producer that can produce the exchange (= send the mail)
    Producer producer = endpoint.createProducer();
    // start the producer
    producer.start();
    // and let it go (processes the exchange by sending the email)
    producer.process(exchange);
    // END SNIPPET: e1
    // need some time for the mail to arrive on the inbox (consumed and sent to the mock)
    Thread.sleep(2000);
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);
    Exchange out = mock.assertExchangeReceived(0);
    mock.assertIsSatisfied();
    // plain text
    assertEquals("Hello World", out.getIn().getBody(String.class));
    // attachment
    Map<String, Attachment> attachments = out.getIn().getAttachmentObjects();
    assertNotNull("Should have attachments", attachments);
    assertEquals(1, attachments.size());
    Attachment attachment = out.getIn().getAttachmentObject("logo.jpeg");
    DataHandler handler = attachment.getDataHandler();
    assertNotNull("The logo should be there", handler);
    // content type should match
    boolean match1 = "image/jpeg; name=logo.jpeg".equals(handler.getContentType());
    boolean match2 = "application/octet-stream; name=logo.jpeg".equals(handler.getContentType());
    assertTrue("Should match 1 or 2", match1 || match2);
    assertEquals("Handler name should be the file name", "logo.jpeg", handler.getName());
    assertEquals("some sample content", attachment.getHeader("content-description"));
    producer.stop();
}
Also used : Exchange(org.apache.camel.Exchange) Endpoint(org.apache.camel.Endpoint) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) Message(org.apache.camel.Message) Producer(org.apache.camel.Producer) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) FileDataSource(javax.activation.FileDataSource) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) Attachment(org.apache.camel.Attachment) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) DataHandler(javax.activation.DataHandler) Test(org.junit.Test)

Example 7 with DefaultAttachment

use of org.apache.camel.impl.DefaultAttachment in project camel by apache.

the class DefaultUndertowHttpBinding method toCamelMessage.

@Override
public Message toCamelMessage(HttpServerExchange httpExchange, Exchange exchange) throws Exception {
    Message result = new DefaultMessage();
    populateCamelHeaders(httpExchange, result.getHeaders(), exchange);
    // Map form data which is parsed by undertow form parsers
    FormData formData = httpExchange.getAttachment(FormDataParser.FORM_DATA);
    if (formData != null) {
        Map<String, Object> body = new HashMap<>();
        formData.forEach(key -> {
            formData.get(key).forEach(value -> {
                if (value.isFile()) {
                    DefaultAttachment attachment = new DefaultAttachment(new FilePartDataSource(value));
                    result.addAttachmentObject(key, attachment);
                    body.put(key, attachment.getDataHandler());
                } else if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(key, value.getValue(), exchange)) {
                    UndertowHelper.appendHeader(result.getHeaders(), key, value.getValue());
                    UndertowHelper.appendHeader(body, key, value.getValue());
                }
            });
        });
        result.setBody(body);
    } else {
        //body is extracted as byte[] then auto TypeConverter kicks in
        if (Methods.POST.equals(httpExchange.getRequestMethod()) || Methods.PUT.equals(httpExchange.getRequestMethod())) {
            result.setBody(readFromChannel(httpExchange.getRequestChannel()));
        } else {
            result.setBody(null);
        }
    }
    return result;
}
Also used : DefaultMessage(org.apache.camel.impl.DefaultMessage) FormData(io.undertow.server.handlers.form.FormData) Message(org.apache.camel.Message) DefaultMessage(org.apache.camel.impl.DefaultMessage) HashMap(java.util.HashMap) HttpString(io.undertow.util.HttpString) DefaultAttachment(org.apache.camel.impl.DefaultAttachment)

Example 8 with DefaultAttachment

use of org.apache.camel.impl.DefaultAttachment in project camel by apache.

the class AttachmentHttpBinding method populateAttachments.

@Override
protected void populateAttachments(HttpServletRequest request, HttpMessage message) {
    try {
        Collection<Part> parts = request.getParts();
        for (Part part : parts) {
            DataSource ds = new PartDataSource(part);
            Attachment attachment = new DefaultAttachment(ds);
            for (String headerName : part.getHeaderNames()) {
                for (String headerValue : part.getHeaders(headerName)) {
                    attachment.addHeader(headerName, headerValue);
                }
            }
            message.addAttachmentObject(part.getName(), attachment);
        }
    } catch (Exception e) {
        throw new RuntimeCamelException("Cannot populate attachments", e);
    }
}
Also used : Part(javax.servlet.http.Part) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) Attachment(org.apache.camel.Attachment) RuntimeCamelException(org.apache.camel.RuntimeCamelException) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) RuntimeCamelException(org.apache.camel.RuntimeCamelException) IOException(java.io.IOException) DataSource(javax.activation.DataSource)

Example 9 with DefaultAttachment

use of org.apache.camel.impl.DefaultAttachment in project camel by apache.

the class AttachmentHttpBinding method populateAttachments.

@Override
protected void populateAttachments(HttpServletRequest request, HttpMessage message) {
    Object object = request.getAttribute("org.eclipse.jetty.servlet.MultiPartFile.multiPartInputStream");
    if (object instanceof MultiPartInputStreamParser) {
        MultiPartInputStreamParser parser = (MultiPartInputStreamParser) object;
        Collection<Part> parts;
        try {
            parts = parser.getParts();
            for (Part part : parts) {
                DataSource ds = new PartDataSource(part);
                Attachment attachment = new DefaultAttachment(ds);
                for (String headerName : part.getHeaderNames()) {
                    for (String headerValue : part.getHeaders(headerName)) {
                        attachment.addHeader(headerName, headerValue);
                    }
                }
                message.addAttachmentObject(part.getName(), attachment);
            }
        } catch (Exception e) {
            throw new RuntimeCamelException("Cannot populate attachments", e);
        }
    }
}
Also used : Part(javax.servlet.http.Part) MultiPartInputStreamParser(org.eclipse.jetty.util.MultiPartInputStreamParser) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) Attachment(org.apache.camel.Attachment) RuntimeCamelException(org.apache.camel.RuntimeCamelException) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) RuntimeCamelException(org.apache.camel.RuntimeCamelException) IOException(java.io.IOException) DataSource(javax.activation.DataSource)

Example 10 with DefaultAttachment

use of org.apache.camel.impl.DefaultAttachment in project camel by apache.

the class MimeMultipartDataFormat method unmarshal.

@Override
public Object unmarshal(Exchange exchange, InputStream stream) throws IOException, MessagingException {
    MimeBodyPart mimeMessage;
    String contentType;
    Message camelMessage;
    Object content = null;
    if (headersInline) {
        mimeMessage = new MimeBodyPart(stream);
        camelMessage = exchange.getOut();
        MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
        contentType = mimeMessage.getHeader(CONTENT_TYPE, null);
        // write the MIME headers not generated by javamail as Camel headers
        Enumeration<?> headersEnum = mimeMessage.getNonMatchingHeaders(STANDARD_HEADERS);
        while (headersEnum.hasMoreElements()) {
            Object ho = headersEnum.nextElement();
            if (ho instanceof Header) {
                Header header = (Header) ho;
                camelMessage.setHeader(header.getName(), header.getValue());
            }
        }
    } else {
        // check if this a multipart at all. Otherwise do nothing
        contentType = exchange.getIn().getHeader(CONTENT_TYPE, String.class);
        if (contentType == null) {
            return stream;
        }
        try {
            ContentType ct = new ContentType(contentType);
            if (!ct.match("multipart/*")) {
                return stream;
            }
        } catch (ParseException e) {
            LOG.warn("Invalid Content-Type " + contentType + " ignored");
            return stream;
        }
        camelMessage = exchange.getOut();
        MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOHelper.copyAndCloseInput(stream, bos);
        InternetHeaders headers = new InternetHeaders();
        extractHeader(CONTENT_TYPE, camelMessage, headers);
        extractHeader(MIME_VERSION, camelMessage, headers);
        mimeMessage = new MimeBodyPart(headers, bos.toByteArray());
        bos.close();
    }
    DataHandler dh;
    try {
        dh = mimeMessage.getDataHandler();
        if (dh != null) {
            content = dh.getContent();
            contentType = dh.getContentType();
        }
    } catch (MessagingException e) {
        LOG.warn("cannot parse message, no unmarshalling done");
    }
    if (content instanceof MimeMultipart) {
        MimeMultipart mp = (MimeMultipart) content;
        content = mp.getBodyPart(0);
        for (int i = 1; i < mp.getCount(); i++) {
            BodyPart bp = mp.getBodyPart(i);
            DefaultAttachment camelAttachment = new DefaultAttachment(bp.getDataHandler());
            @SuppressWarnings("unchecked") Enumeration<Header> headers = bp.getAllHeaders();
            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                camelAttachment.addHeader(header.getName(), header.getValue());
            }
            camelMessage.addAttachmentObject(getAttachmentKey(bp), camelAttachment);
        }
    }
    if (content instanceof BodyPart) {
        BodyPart bp = (BodyPart) content;
        camelMessage.setBody(bp.getInputStream());
        contentType = bp.getContentType();
        if (contentType != null && !DEFAULT_CONTENT_TYPE.equals(contentType)) {
            camelMessage.setHeader(CONTENT_TYPE, contentType);
            ContentType ct = new ContentType(contentType);
            String charset = ct.getParameter("charset");
            if (charset != null) {
                camelMessage.setHeader(Exchange.CONTENT_ENCODING, MimeUtility.javaCharset(charset));
            }
        }
    } else {
        // If we find no body part, try to leave the message alone
        LOG.info("no MIME part found");
    }
    return camelMessage;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Message(org.apache.camel.Message) MimeMessage(javax.mail.internet.MimeMessage) ContentType(javax.mail.internet.ContentType) InternetHeaders(javax.mail.internet.InternetHeaders) MessagingException(javax.mail.MessagingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataHandler(javax.activation.DataHandler) Header(javax.mail.Header) MimeMultipart(javax.mail.internet.MimeMultipart) ParseException(javax.mail.internet.ParseException) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Aggregations

DefaultAttachment (org.apache.camel.impl.DefaultAttachment)13 Message (org.apache.camel.Message)7 FileDataSource (javax.activation.FileDataSource)5 Exchange (org.apache.camel.Exchange)5 DataHandler (javax.activation.DataHandler)4 Attachment (org.apache.camel.Attachment)4 Processor (org.apache.camel.Processor)4 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)4 DataSource (javax.activation.DataSource)3 IOException (java.io.IOException)2 BodyPart (javax.mail.BodyPart)2 Header (javax.mail.Header)2 MimeBodyPart (javax.mail.internet.MimeBodyPart)2 Part (javax.servlet.http.Part)2 RuntimeCamelException (org.apache.camel.RuntimeCamelException)2 FormData (io.undertow.server.handlers.form.FormData)1 HttpString (io.undertow.util.HttpString)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 URL (java.net.URL)1