You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by da...@apache.org on 2015/04/13 08:00:31 UTC

[1/4] camel git commit: 8569 Ability to easily extract email attachments

Repository: camel
Updated Branches:
  refs/heads/master eaa84ef8d -> f91b5a8d8


8569 Ability to easily extract email attachments

Code + unit for feature request 8569-Ability to easily extract email attachments

Added an option to SplitAttachmentsExpression to have the attachments be split into
new messages with a byte[] body that contains the attachment, instead of a single
attachment on a clone of the message.

NOTE: Default behaviour is retained (i.e. splitting into cloned messages each with a
single attachment).


Project: http://git-wip-us.apache.org/repos/asf/camel/repo
Commit: http://git-wip-us.apache.org/repos/asf/camel/commit/b97c2ba5
Tree: http://git-wip-us.apache.org/repos/asf/camel/tree/b97c2ba5
Diff: http://git-wip-us.apache.org/repos/asf/camel/diff/b97c2ba5

Branch: refs/heads/master
Commit: b97c2ba5bae3c5a17f1f006247c6cbec5c01b48e
Parents: 93a613d
Author: Simon van der Sluis <si...@edmi.co.nz>
Authored: Mon Apr 13 09:53:40 2015 +1200
Committer: Claus Ibsen <da...@apache.org>
Committed: Mon Apr 13 07:54:21 2015 +0200

----------------------------------------------------------------------
 .../mail/ExtractAttachmentsExpression.java      |  83 --------------
 .../mail/SplitAttachmentsExpression.java        | 111 ++++++++++++++++---
 .../mail/MailExtractAttachmentsTest.java        | 101 -----------------
 .../mail/MailSplitAttachmentsTest.java          |  65 +++++++++--
 4 files changed, 154 insertions(+), 206 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/b97c2ba5/components/camel-mail/src/main/java/org/apache/camel/component/mail/ExtractAttachmentsExpression.java
----------------------------------------------------------------------
diff --git a/components/camel-mail/src/main/java/org/apache/camel/component/mail/ExtractAttachmentsExpression.java b/components/camel-mail/src/main/java/org/apache/camel/component/mail/ExtractAttachmentsExpression.java
deleted file mode 100644
index 510b52c..0000000
--- a/components/camel-mail/src/main/java/org/apache/camel/component/mail/ExtractAttachmentsExpression.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.camel.component.mail;
-
-import javax.activation.DataHandler;
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import com.sun.mail.util.BASE64DecoderStream;
-import org.apache.camel.Exchange;
-import org.apache.camel.Message;
-import org.apache.camel.RuntimeCamelException;
-import org.apache.camel.impl.DefaultMessage;
-import org.apache.camel.support.ExpressionAdapter;
-
-/**
- * A {@link org.apache.camel.Expression} which can be used to split a {@link MailMessage}
- * per attachment. For example if a mail message has 5 attachments, then this
- * expression will return a <tt>List&lt;Message&gt;</tt> that contains 5 {@link Message}
- * where the body of each Message is a byte[] containing an attachment.
- */
-public class ExtractAttachmentsExpression extends ExpressionAdapter {
-
-    @Override
-    public Object evaluate(Exchange exchange) {
-        // must use getAttachments to ensure attachments is initially populated
-        if (exchange.getIn().getAttachments().isEmpty()) {
-            return null;
-        }
-
-        try {
-            return convertMimeparts(exchange.getIn());
-        } catch (Exception e) {
-            throw new RuntimeCamelException("Unable to extract attachments from MimeMultipart message", e);
-        }
-    }
-
-    private List<Message> convertMimeparts(Message inMessage) throws Exception {
-        List<Message> outMessages = new ArrayList<>();
-        for (Map.Entry<String, DataHandler> entry : inMessage.getAttachments().entrySet()) {
-            final Message outMessage = new DefaultMessage();
-            final String key = entry.getKey();
-            outMessage.setHeader("CamelSplitAttachmentName", key);
-            Object attachment = inMessage.getAttachment(key).getContent();
-            if (attachment instanceof InputStream) {
-                outMessage.setBody(readMimePart((InputStream) attachment));
-                outMessages.add(outMessage);
-            }
-        }
-        return outMessages;
-    }
-
-    private byte[] readMimePart(InputStream mimePartStream) throws Exception {
-        //  mimePartStream could be base64 encoded, or not, but we dont need to worry about it as
-        // camel is smart enough to wrap it in a decoder stream (eg Base64DecoderStream) when required
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        int len;
-        byte[] buf = new byte[1024];
-        while ((len = mimePartStream.read(buf, 0, 1024)) != -1) {
-            bos.write(buf, 0, len);
-        }
-        mimePartStream.close();
-        return bos.toByteArray();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/b97c2ba5/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java
----------------------------------------------------------------------
diff --git a/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java b/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java
index 9ad24ed..f4221c8 100644
--- a/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java
+++ b/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java
@@ -16,6 +16,8 @@
  */
 package org.apache.camel.component.mail;
 
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
@@ -23,16 +25,48 @@ import javax.activation.DataHandler;
 
 import org.apache.camel.Exchange;
 import org.apache.camel.Message;
+import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.impl.DefaultMessage;
 import org.apache.camel.support.ExpressionAdapter;
 
 /**
  * A {@link org.apache.camel.Expression} which can be used to split a {@link MailMessage}
  * per attachment. For example if a mail message has 5 attachments, then this
- * expression will return a <tt>List&lt;Message&gt;</tt> that contains 5 {@link Message}
- * and each have a single attachment from the source {@link MailMessage}.
+ * expression will return a <tt>List&lt;Message&gt;</tt> that contains 5 {@link Message}.
+ * The message can be split 2 ways:
+ * <table>
+ *   <tr>
+ *     <td>As an attachment</td>
+ *     <td>
+ *       The message is split into cloned messages, each has only one attachment.  The mail attachment in each message
+ *       remains unprocessed.
+ *     </td>
+ *   </tr>
+ *   <tr>
+ *     <td>As a byte[]</td>
+ *     <td>
+ *       The attachments are split into new messages as the body. This allows the split messages to be easily used by
+ *       other processors / routes, as many other camel components can work on the byte[], e.g. it can be written to disk
+ *       using camel-file.
+ *     </td>
+ *   </tr>
+ * </table>
+ *
+ * In both cases the attachment name is written to a the camel header &quot;CamelSplitAttachmentId&quot;
  */
 public class SplitAttachmentsExpression extends ExpressionAdapter {
 
+    public static final String HEADER_NAME = "CamelSplitAttachmentId";
+
+    private boolean extractAttachments = false;
+
+    public SplitAttachmentsExpression() {
+    }
+
+    public SplitAttachmentsExpression(boolean extractAttachments) {
+        this.extractAttachments = extractAttachments;
+    }
+
     @Override
     public Object evaluate(Exchange exchange) {
         // must use getAttachments to ensure attachments is initial populated
@@ -40,19 +74,68 @@ public class SplitAttachmentsExpression extends ExpressionAdapter {
             return null;
         }
 
-        // we want to provide a list of messages with 1 attachment per mail
-        List<Message> answer = new ArrayList<Message>();
-
-        for (Map.Entry<String, DataHandler> entry : exchange.getIn().getAttachments().entrySet()) {
-            final Message copy = exchange.getIn().copy();
-            final String key = entry.getKey();
-            Map<String, DataHandler> attachments = copy.getAttachments();
-            attachments.clear();
-            attachments.put(key, entry.getValue());
-            copy.setHeader("CamelSplitAttachmentId", key);
-            answer.add(copy);
+        try {
+            List<Message> answer = new ArrayList<Message>();
+            Message inMessage = exchange.getIn();
+            for (Map.Entry<String, DataHandler> entry : inMessage.getAttachments().entrySet()) {
+                Message attachmentMessage;
+                if (extractAttachments) {
+                    attachmentMessage = extractAttachment(inMessage, entry.getKey());
+                } else {
+                    attachmentMessage = splitAttachment(inMessage, entry.getKey(), entry.getValue());
+                }
+
+                if (attachmentMessage != null) {
+                    answer.add(attachmentMessage);
+                }
+            }
+
+            return answer;
+        } catch (Exception e) {
+            throw new RuntimeCamelException("Unable to split attachments from MimeMultipart message", e);
+        }
+    }
+
+    private Message splitAttachment(Message inMessage, String attachmentName, DataHandler attachmentHandler) {
+        final Message copy = inMessage.copy();
+         Map<String, DataHandler> attachments = copy.getAttachments();
+        attachments.clear();
+        attachments.put(attachmentName, attachmentHandler);
+        copy.setHeader(HEADER_NAME, attachmentName);
+        return copy;
+    }
+
+    private Message extractAttachment(Message inMessage, String attachmentName) throws Exception {
+        final Message outMessage = new DefaultMessage();
+        outMessage.setHeader(HEADER_NAME, attachmentName);
+        Object attachment = inMessage.getAttachment(attachmentName).getContent();
+        if (attachment instanceof InputStream) {
+            outMessage.setBody(readMimePart((InputStream) attachment));
+            return outMessage;
         }
+        return null;
+    }
+
+
+    private byte[] readMimePart(InputStream mimePartStream) throws Exception {
+        //  mimePartStream could be base64 encoded, or not, but we don't need to worry about it as
+        // camel is smart enough to wrap it in a decoder stream (eg Base64DecoderStream) when required
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        int len;
+        byte[] buf = new byte[1024];
+        while ((len = mimePartStream.read(buf, 0, 1024)) != -1) {
+            bos.write(buf, 0, len);
+        }
+        mimePartStream.close();
+        return bos.toByteArray();
+    }
+
+
+    public boolean isExtractAttachments() {
+        return extractAttachments;
+    }
 
-        return answer;
+    public void setExtractAttachments(boolean extractAttachments) {
+        this.extractAttachments = extractAttachments;
     }
 }

http://git-wip-us.apache.org/repos/asf/camel/blob/b97c2ba5/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java
----------------------------------------------------------------------
diff --git a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java
deleted file mode 100644
index b57e38d..0000000
--- a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.camel.component.mail;
-
-import javax.activation.DataHandler;
-import javax.activation.FileDataSource;
-
-import org.apache.camel.Endpoint;
-import org.apache.camel.Exchange;
-import org.apache.camel.Message;
-import org.apache.camel.Producer;
-import org.apache.camel.builder.RouteBuilder;
-import org.apache.camel.component.mock.MockEndpoint;
-import org.apache.camel.test.junit4.CamelTestSupport;
-import org.apache.commons.io.IOUtils;
-import org.junit.Test;
-import org.jvnet.mock_javamail.Mailbox;
-
-/**
- * Tests for extracting email attachments.
- *
- * @author simonvandersluis
- */
-public class MailExtractAttachmentsTest extends CamelTestSupport {
-
-  @Test
-  public void testExtractAttachments() throws Exception {
-
-    // clear mailbox
-    Mailbox.clearAll();
-
-    // 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");
-    in.addAttachment("logo.jpeg", new DataHandler(new FileDataSource("src/test/data/logo.jpeg")));
-    in.addAttachment("license.txt", new DataHandler(new FileDataSource("src/main/resources/META-INF/LICENSE.txt")));
-
-    Producer producer = endpoint.createProducer();
-    producer.start();
-    producer.process(exchange);
-
-    Thread.sleep(2000);
-
-    MockEndpoint mock = getMockEndpoint("mock:split");
-    mock.expectedMessageCount(2);
-
-    mock.assertIsSatisfied();
-
-    Message first = mock.getReceivedExchanges().get(0).getIn();
-    Message second = mock.getReceivedExchanges().get(1).getIn();
-
-    // check it's no longer an attachment, but is the message body
-    assertEquals(0, first.getAttachments().size());
-    assertEquals(0, second.getAttachments().size());
-
-    assertEquals("logo.jpeg", first.getHeader("CamelSplitAttachmentName"));
-    assertEquals("license.txt", second.getHeader("CamelSplitAttachmentName"));
-
-    byte[] expected1 = IOUtils.toByteArray(new FileDataSource("src/test/data/logo.jpeg").getInputStream());
-    byte[] expected2 = IOUtils.toByteArray(new FileDataSource("src/main/resources/META-INF/LICENSE.txt").getInputStream());
-
-    assertArrayEquals(expected1, (byte[]) first.getBody());
-    assertArrayEquals(expected2, (byte[]) second.getBody());
-  }
-
-  @Override
-  protected RouteBuilder createRouteBuilder() throws Exception {
-    return new RouteBuilder() {
-      @Override
-      public void configure() throws Exception {
-        // START SNIPPET: e1
-        from("pop3://james@mymailserver.com?password=secret&consumer.delay=1000")
-                .to("log:email")
-                        // use the SplitAttachmentsExpression which will split the message per attachment
-                .split(new ExtractAttachmentsExpression())
-                        // each message going to this mock has a single attachment
-                .to("mock:split")
-                .end();
-        // END SNIPPET: e1
-      }
-    };
-  }
-}

http://git-wip-us.apache.org/repos/asf/camel/blob/b97c2ba5/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java
----------------------------------------------------------------------
diff --git a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java
index 4625e7c..c66eff9 100644
--- a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java
+++ b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailSplitAttachmentsTest.java
@@ -26,29 +26,39 @@ import org.apache.camel.Producer;
 import org.apache.camel.builder.RouteBuilder;
 import org.apache.camel.component.mock.MockEndpoint;
 import org.apache.camel.test.junit4.CamelTestSupport;
+import org.apache.commons.io.IOUtils;
+import org.junit.Before;
 import org.junit.Test;
 import org.jvnet.mock_javamail.Mailbox;
 
 /**
- *
+ *  Tests the {@link SplitAttachmentsExpression}.
  */
 public class MailSplitAttachmentsTest extends CamelTestSupport {
 
-    @Test
-    public void testSplitAttachments() throws Exception {
+    private Endpoint endpoint;
+    private SplitAttachmentsExpression splitAttachmentsExpression;
+    private Exchange exchange;
 
-        // clear mailbox
+    @Before
+    public void clearMailBox() {
         Mailbox.clearAll();
+    }
 
-        // create an exchange with a normal body and attachment to be produced as email
-        Endpoint endpoint = context.getEndpoint("smtp://james@mymailserver.com?password=secret");
 
+    @Before
+    public void setup() {
         // create the exchange with the mail message that is multipart with a file and a Hello World text/plain message.
-        Exchange exchange = endpoint.createExchange();
+        endpoint = context.getEndpoint("smtp://james@mymailserver.com?password=secret");
+        exchange = endpoint.createExchange();
         Message in = exchange.getIn();
         in.setBody("Hello World");
         in.addAttachment("logo.jpeg", new DataHandler(new FileDataSource("src/test/data/logo.jpeg")));
         in.addAttachment("license.txt", new DataHandler(new FileDataSource("src/main/resources/META-INF/LICENSE.txt")));
+    }
+
+    @Test
+    public void testSplitAttachments() throws Exception {
 
         Producer producer = endpoint.createProducer();
         producer.start();
@@ -77,8 +87,47 @@ public class MailSplitAttachmentsTest extends CamelTestSupport {
         assertTrue("Should have license.txt file attachment", license);
     }
 
+
+    @Test
+    public void testExtractAttachments() throws Exception {
+
+        // set the expression to extract the attachments as byte[]s
+        splitAttachmentsExpression.setExtractAttachments(true);
+
+
+        Producer producer = endpoint.createProducer();
+        producer.start();
+        producer.process(exchange);
+
+        Thread.sleep(2000);
+
+        MockEndpoint mock = getMockEndpoint("mock:split");
+        mock.expectedMessageCount(2);
+
+        mock.assertIsSatisfied();
+
+        Message first = mock.getReceivedExchanges().get(0).getIn();
+        Message second = mock.getReceivedExchanges().get(1).getIn();
+
+        // check it's no longer an attachment, but is the message body
+        assertEquals(0, first.getAttachments().size());
+        assertEquals(0, second.getAttachments().size());
+
+        assertEquals("logo.jpeg", first.getHeader("CamelSplitAttachmentId"));
+        assertEquals("license.txt", second.getHeader("CamelSplitAttachmentId"));
+
+        byte[] expected1 = IOUtils.toByteArray(new FileDataSource("src/test/data/logo.jpeg").getInputStream());
+        byte[] expected2 = IOUtils.toByteArray(new FileDataSource("src/main/resources/META-INF/LICENSE.txt").getInputStream());
+
+        assertArrayEquals(expected1, (byte[]) first.getBody());
+        assertArrayEquals(expected2, (byte[]) second.getBody());
+    }
+
     @Override
     protected RouteBuilder createRouteBuilder() throws Exception {
+
+        splitAttachmentsExpression = new SplitAttachmentsExpression(false);
+
         return new RouteBuilder() {
             @Override
             public void configure() throws Exception {
@@ -86,7 +135,7 @@ public class MailSplitAttachmentsTest extends CamelTestSupport {
                 from("pop3://james@mymailserver.com?password=secret&consumer.delay=1000")
                     .to("log:email")
                     // use the SplitAttachmentsExpression which will split the message per attachment
-                    .split(new SplitAttachmentsExpression())
+                    .split(splitAttachmentsExpression)
                         // each message going to this mock has a single attachment
                         .to("mock:split")
                     .end();


[2/4] camel git commit: Correct copyright in MailExtractAttachmentsTest

Posted by da...@apache.org.
Correct copyright in MailExtractAttachmentsTest


Project: http://git-wip-us.apache.org/repos/asf/camel/repo
Commit: http://git-wip-us.apache.org/repos/asf/camel/commit/93a613d2
Tree: http://git-wip-us.apache.org/repos/asf/camel/tree/93a613d2
Diff: http://git-wip-us.apache.org/repos/asf/camel/diff/93a613d2

Branch: refs/heads/master
Commit: 93a613d2022ccbe8edd66f2afc54cce3da53c209
Parents: a0e7002
Author: Simon van der Sluis <si...@edmi.co.nz>
Authored: Mon Mar 30 17:05:58 2015 +1300
Committer: Claus Ibsen <da...@apache.org>
Committed: Mon Apr 13 07:54:21 2015 +0200

----------------------------------------------------------------------
 .../mail/MailExtractAttachmentsTest.java        | 24 ++++++++++++--------
 1 file changed, 15 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/93a613d2/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java
----------------------------------------------------------------------
diff --git a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java
index 7ed1ae7..b57e38d 100644
--- a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java
+++ b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java
@@ -1,12 +1,18 @@
-/*
- * Copyright (c) 2015 EDMI NZ
- * All rights reserved.
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
- * This software is the confidential and proprietary information of EDMI. 
- * ("Confidential Information").  You shall not
- * disclose such Confidential Information and shall use it only in
- * accordance with the terms of the license agreement you entered into
- * with EDMI.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 package org.apache.camel.component.mail;
 
@@ -25,7 +31,7 @@ import org.junit.Test;
 import org.jvnet.mock_javamail.Mailbox;
 
 /**
- * Tests
+ * Tests for extracting email attachments.
  *
  * @author simonvandersluis
  */


[3/4] camel git commit: 8569 Ability to easily extract email attachments

Posted by da...@apache.org.
8569 Ability to easily extract email attachments

Code + unit for feature request 8569-Ability to easily extract email attachments


Project: http://git-wip-us.apache.org/repos/asf/camel/repo
Commit: http://git-wip-us.apache.org/repos/asf/camel/commit/a0e7002a
Tree: http://git-wip-us.apache.org/repos/asf/camel/tree/a0e7002a
Diff: http://git-wip-us.apache.org/repos/asf/camel/diff/a0e7002a

Branch: refs/heads/master
Commit: a0e7002aca8f82397c249dadb46b79de6617ae16
Parents: eaa84ef
Author: Simon van der Sluis <si...@edmi.co.nz>
Authored: Mon Mar 30 11:42:37 2015 +1300
Committer: Claus Ibsen <da...@apache.org>
Committed: Mon Apr 13 07:54:21 2015 +0200

----------------------------------------------------------------------
 components/camel-mail/pom.xml                   |  6 ++
 .../mail/ExtractAttachmentsExpression.java      | 83 +++++++++++++++++
 .../mail/MailExtractAttachmentsTest.java        | 95 ++++++++++++++++++++
 3 files changed, 184 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/a0e7002a/components/camel-mail/pom.xml
----------------------------------------------------------------------
diff --git a/components/camel-mail/pom.xml b/components/camel-mail/pom.xml
index 5eef5a3..c69d445 100644
--- a/components/camel-mail/pom.xml
+++ b/components/camel-mail/pom.xml
@@ -93,6 +93,12 @@
             <artifactId>mockito-core</artifactId>
             <scope>test</scope>
         </dependency>
+        <dependency>
+          <groupId>commons-io</groupId>
+          <artifactId>commons-io</artifactId>
+          <version>${commons-io-version}</version>
+          <scope>test</scope>
+        </dependency>
     </dependencies>
 
 </project>

http://git-wip-us.apache.org/repos/asf/camel/blob/a0e7002a/components/camel-mail/src/main/java/org/apache/camel/component/mail/ExtractAttachmentsExpression.java
----------------------------------------------------------------------
diff --git a/components/camel-mail/src/main/java/org/apache/camel/component/mail/ExtractAttachmentsExpression.java b/components/camel-mail/src/main/java/org/apache/camel/component/mail/ExtractAttachmentsExpression.java
new file mode 100644
index 0000000..510b52c
--- /dev/null
+++ b/components/camel-mail/src/main/java/org/apache/camel/component/mail/ExtractAttachmentsExpression.java
@@ -0,0 +1,83 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.mail;
+
+import javax.activation.DataHandler;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import com.sun.mail.util.BASE64DecoderStream;
+import org.apache.camel.Exchange;
+import org.apache.camel.Message;
+import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.impl.DefaultMessage;
+import org.apache.camel.support.ExpressionAdapter;
+
+/**
+ * A {@link org.apache.camel.Expression} which can be used to split a {@link MailMessage}
+ * per attachment. For example if a mail message has 5 attachments, then this
+ * expression will return a <tt>List&lt;Message&gt;</tt> that contains 5 {@link Message}
+ * where the body of each Message is a byte[] containing an attachment.
+ */
+public class ExtractAttachmentsExpression extends ExpressionAdapter {
+
+    @Override
+    public Object evaluate(Exchange exchange) {
+        // must use getAttachments to ensure attachments is initially populated
+        if (exchange.getIn().getAttachments().isEmpty()) {
+            return null;
+        }
+
+        try {
+            return convertMimeparts(exchange.getIn());
+        } catch (Exception e) {
+            throw new RuntimeCamelException("Unable to extract attachments from MimeMultipart message", e);
+        }
+    }
+
+    private List<Message> convertMimeparts(Message inMessage) throws Exception {
+        List<Message> outMessages = new ArrayList<>();
+        for (Map.Entry<String, DataHandler> entry : inMessage.getAttachments().entrySet()) {
+            final Message outMessage = new DefaultMessage();
+            final String key = entry.getKey();
+            outMessage.setHeader("CamelSplitAttachmentName", key);
+            Object attachment = inMessage.getAttachment(key).getContent();
+            if (attachment instanceof InputStream) {
+                outMessage.setBody(readMimePart((InputStream) attachment));
+                outMessages.add(outMessage);
+            }
+        }
+        return outMessages;
+    }
+
+    private byte[] readMimePart(InputStream mimePartStream) throws Exception {
+        //  mimePartStream could be base64 encoded, or not, but we dont need to worry about it as
+        // camel is smart enough to wrap it in a decoder stream (eg Base64DecoderStream) when required
+        ByteArrayOutputStream bos = new ByteArrayOutputStream();
+        int len;
+        byte[] buf = new byte[1024];
+        while ((len = mimePartStream.read(buf, 0, 1024)) != -1) {
+            bos.write(buf, 0, len);
+        }
+        mimePartStream.close();
+        return bos.toByteArray();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/camel/blob/a0e7002a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java
----------------------------------------------------------------------
diff --git a/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java
new file mode 100644
index 0000000..7ed1ae7
--- /dev/null
+++ b/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailExtractAttachmentsTest.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2015 EDMI NZ
+ * All rights reserved.
+ *
+ * This software is the confidential and proprietary information of EDMI. 
+ * ("Confidential Information").  You shall not
+ * disclose such Confidential Information and shall use it only in
+ * accordance with the terms of the license agreement you entered into
+ * with EDMI.
+ */
+package org.apache.camel.component.mail;
+
+import javax.activation.DataHandler;
+import javax.activation.FileDataSource;
+
+import org.apache.camel.Endpoint;
+import org.apache.camel.Exchange;
+import org.apache.camel.Message;
+import org.apache.camel.Producer;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.test.junit4.CamelTestSupport;
+import org.apache.commons.io.IOUtils;
+import org.junit.Test;
+import org.jvnet.mock_javamail.Mailbox;
+
+/**
+ * Tests
+ *
+ * @author simonvandersluis
+ */
+public class MailExtractAttachmentsTest extends CamelTestSupport {
+
+  @Test
+  public void testExtractAttachments() throws Exception {
+
+    // clear mailbox
+    Mailbox.clearAll();
+
+    // 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");
+    in.addAttachment("logo.jpeg", new DataHandler(new FileDataSource("src/test/data/logo.jpeg")));
+    in.addAttachment("license.txt", new DataHandler(new FileDataSource("src/main/resources/META-INF/LICENSE.txt")));
+
+    Producer producer = endpoint.createProducer();
+    producer.start();
+    producer.process(exchange);
+
+    Thread.sleep(2000);
+
+    MockEndpoint mock = getMockEndpoint("mock:split");
+    mock.expectedMessageCount(2);
+
+    mock.assertIsSatisfied();
+
+    Message first = mock.getReceivedExchanges().get(0).getIn();
+    Message second = mock.getReceivedExchanges().get(1).getIn();
+
+    // check it's no longer an attachment, but is the message body
+    assertEquals(0, first.getAttachments().size());
+    assertEquals(0, second.getAttachments().size());
+
+    assertEquals("logo.jpeg", first.getHeader("CamelSplitAttachmentName"));
+    assertEquals("license.txt", second.getHeader("CamelSplitAttachmentName"));
+
+    byte[] expected1 = IOUtils.toByteArray(new FileDataSource("src/test/data/logo.jpeg").getInputStream());
+    byte[] expected2 = IOUtils.toByteArray(new FileDataSource("src/main/resources/META-INF/LICENSE.txt").getInputStream());
+
+    assertArrayEquals(expected1, (byte[]) first.getBody());
+    assertArrayEquals(expected2, (byte[]) second.getBody());
+  }
+
+  @Override
+  protected RouteBuilder createRouteBuilder() throws Exception {
+    return new RouteBuilder() {
+      @Override
+      public void configure() throws Exception {
+        // START SNIPPET: e1
+        from("pop3://james@mymailserver.com?password=secret&consumer.delay=1000")
+                .to("log:email")
+                        // use the SplitAttachmentsExpression which will split the message per attachment
+                .split(new ExtractAttachmentsExpression())
+                        // each message going to this mock has a single attachment
+                .to("mock:split")
+                .end();
+        // END SNIPPET: e1
+      }
+    };
+  }
+}


[4/4] camel git commit: CAMEL-8569: Fixed CS

Posted by da...@apache.org.
CAMEL-8569: Fixed CS


Project: http://git-wip-us.apache.org/repos/asf/camel/repo
Commit: http://git-wip-us.apache.org/repos/asf/camel/commit/f91b5a8d
Tree: http://git-wip-us.apache.org/repos/asf/camel/tree/f91b5a8d
Diff: http://git-wip-us.apache.org/repos/asf/camel/diff/f91b5a8d

Branch: refs/heads/master
Commit: f91b5a8d86986908d62fc1906db49651c2b5cdfe
Parents: b97c2ba
Author: Claus Ibsen <da...@apache.org>
Authored: Mon Apr 13 08:03:22 2015 +0200
Committer: Claus Ibsen <da...@apache.org>
Committed: Mon Apr 13 08:03:22 2015 +0200

----------------------------------------------------------------------
 .../apache/camel/component/mail/SplitAttachmentsExpression.java  | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/camel/blob/f91b5a8d/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java
----------------------------------------------------------------------
diff --git a/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java b/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java
index f4221c8..df24c06 100644
--- a/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java
+++ b/components/camel-mail/src/main/java/org/apache/camel/component/mail/SplitAttachmentsExpression.java
@@ -58,7 +58,7 @@ public class SplitAttachmentsExpression extends ExpressionAdapter {
 
     public static final String HEADER_NAME = "CamelSplitAttachmentId";
 
-    private boolean extractAttachments = false;
+    private boolean extractAttachments;
 
     public SplitAttachmentsExpression() {
     }
@@ -98,7 +98,7 @@ public class SplitAttachmentsExpression extends ExpressionAdapter {
 
     private Message splitAttachment(Message inMessage, String attachmentName, DataHandler attachmentHandler) {
         final Message copy = inMessage.copy();
-         Map<String, DataHandler> attachments = copy.getAttachments();
+        Map<String, DataHandler> attachments = copy.getAttachments();
         attachments.clear();
         attachments.put(attachmentName, attachmentHandler);
         copy.setHeader(HEADER_NAME, attachmentName);