Author: davsclaus
Date: Sat May  3 09:29:26 2008
New Revision: 653094

URL: http://svn.apache.org/viewvc?rev=653094&view=rev
Log:
CAMEL-335
- Added unit test for mail attachments to be used for wiki documentation

Added:
    activemq/camel/trunk/components/camel-mail/src/test/data/
    activemq/camel/trunk/components/camel-mail/src/test/data/logo.jpeg   (with 
props)
    
activemq/camel/trunk/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailAttachmentTest.java
Modified:
    
activemq/camel/trunk/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java
    
activemq/camel/trunk/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailMessage.java

Modified: 
activemq/camel/trunk/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java
URL: 
http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java?rev=653094&r1=653093&r2=653094&view=diff
==============================================================================
--- 
activemq/camel/trunk/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java
 (original)
+++ 
activemq/camel/trunk/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailBinding.java
 Sat May  3 09:29:26 2008
@@ -18,20 +18,19 @@
 
 import java.util.Iterator;
 import java.util.Map;
-import java.util.Set;
-
 import javax.activation.DataHandler;
 import javax.mail.Address;
-import javax.mail.BodyPart;
 import javax.mail.Message;
 import javax.mail.MessagingException;
+import javax.mail.BodyPart;
 import javax.mail.Part;
 import javax.mail.internet.InternetAddress;
-import javax.mail.internet.MimeBodyPart;
 import javax.mail.internet.MimeMessage;
+import javax.mail.internet.MimeBodyPart;
 import javax.mail.internet.MimeMultipart;
 
 import org.apache.camel.Exchange;
+import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.converter.ObjectConverter;
 
 /**
@@ -42,46 +41,39 @@
  */
 public class MailBinding {
 
-    public void populateMailMessage(MailEndpoint endpoint, MimeMessage 
mimeMessage, Exchange exchange) {
-        try {
-            appendHeadersFromCamel(mimeMessage, exchange, exchange.getIn());
+    public void populateMailMessage(MailEndpoint endpoint, MimeMessage 
mimeMessage, Exchange exchange)
+        throws MessagingException {
 
-            // set the recipients (receives) of the mail
-            Map<Message.RecipientType, String> recipients = 
endpoint.getConfiguration().getRecipients();
-            if (recipients.containsKey(Message.RecipientType.TO)) {
-                mimeMessage.setRecipients(Message.RecipientType.TO, 
recipients.get(Message.RecipientType.TO));
-            }
-            if (recipients.containsKey(Message.RecipientType.CC)) {
-                mimeMessage.setRecipients(Message.RecipientType.CC, 
recipients.get(Message.RecipientType.CC));
-            }
-            if (recipients.containsKey(Message.RecipientType.BCC)) {
-                mimeMessage.setRecipients(Message.RecipientType.BCC, 
recipients.get(Message.RecipientType.BCC));
-            }
+        appendHeadersFromCamel(mimeMessage, exchange, exchange.getIn());
 
-            // must have at least one recipients otherwise we do not know 
where to send the mail
-            if (mimeMessage.getAllRecipients() == null) {
-                throw new IllegalArgumentException("The mail message does not 
have any recipients set.");
-            }
+        // set the recipients (receivers) of the mail
+        Map<Message.RecipientType, String> recipients = 
endpoint.getConfiguration().getRecipients();
+        if (recipients.containsKey(Message.RecipientType.TO)) {
+            mimeMessage.setRecipients(Message.RecipientType.TO, 
recipients.get(Message.RecipientType.TO));
+        }
+        if (recipients.containsKey(Message.RecipientType.CC)) {
+            mimeMessage.setRecipients(Message.RecipientType.CC, 
recipients.get(Message.RecipientType.CC));
+        }
+        if (recipients.containsKey(Message.RecipientType.BCC)) {
+            mimeMessage.setRecipients(Message.RecipientType.BCC, 
recipients.get(Message.RecipientType.BCC));
+        }
 
-            if (empty(mimeMessage.getFrom())) {
-                // lets default the address to the endpoint destination
-                String from = endpoint.getConfiguration().getFrom();
-                mimeMessage.setFrom(new InternetAddress(from));
-            }
+        // must have at least one recipients otherwise we do not know where to 
send the mail
+        if (mimeMessage.getAllRecipients() == null) {
+            throw new IllegalArgumentException("The mail message does not have 
any recipients set.");
+        }
 
-            if (exchange.getIn().getAttachments() != null && 
exchange.getIn().getAttachments().size() > 0) {
-                appendAttachmentsFromCamel(mimeMessage, exchange, 
exchange.getIn());
-            } else {
-                mimeMessage.setText(exchange.getIn().getBody(String.class));
-            }
-        } catch (Exception e) {
-            throw new RuntimeMailException("Failed to populate body due to: " 
+ e.getMessage()
-                                           + ". Exchange: " + exchange, e);
+        if (empty(mimeMessage.getFrom())) {
+            // lets default the address to the endpoint destination
+            String from = endpoint.getConfiguration().getFrom();
+            mimeMessage.setFrom(new InternetAddress(from));
         }
-    }
 
-    protected boolean empty(Address[] addresses) {
-        return addresses == null || addresses.length == 0;
+        if (exchange.getIn().hasAttachments()) {
+            appendAttachmentsFromCamel(mimeMessage, exchange, 
exchange.getIn());
+        } else {
+            mimeMessage.setText(exchange.getIn().getBody(String.class));
+        }
     }
 
     /**
@@ -91,8 +83,8 @@
         try {
             return message.getContent();
         } catch (Exception e) {
-            throw new RuntimeMailException("Failed to extract body due to: " + 
e.getMessage()
-                                           + ". Exchange: " + exchange + ". 
Message: " + message, e);
+            throw new RuntimeCamelException("Failed to extract body due to: " 
+ e.getMessage()
+                + ". Exchange: " + exchange + ". Message: " + message, e);
         }
     }
 
@@ -100,9 +92,10 @@
      * Appends the Mail headers from the Camel [EMAIL PROTECTED] MailMessage}
      */
     protected void appendHeadersFromCamel(MimeMessage mimeMessage, Exchange 
exchange,
-                                          org.apache.camel.Message 
camelMessage) throws MessagingException {
-        Set<Map.Entry<String, Object>> entries = 
camelMessage.getHeaders().entrySet();
-        for (Map.Entry<String, Object> entry : entries) {
+                                          org.apache.camel.Message 
camelMessage)
+        throws MessagingException {
+
+        for (Map.Entry<String, Object> entry : 
camelMessage.getHeaders().entrySet()) {
             String headerName = entry.getKey();
             Object headerValue = entry.getValue();
             if (headerValue != null) {
@@ -130,8 +123,6 @@
                                               org.apache.camel.Message 
camelMessage)
         throws MessagingException {
 
-        // TODO: Use spring mail support to add the attachment
-
         // Create a Multipart
         MimeMultipart multipart = new MimeMultipart();
 
@@ -141,20 +132,17 @@
         textBodyPart.setContent(exchange.getIn().getBody(String.class), 
"text/plain");
         multipart.addBodyPart(textBodyPart);
 
-        BodyPart messageBodyPart;
-
-        Set<Map.Entry<String, DataHandler>> entries = 
camelMessage.getAttachments().entrySet();
-        for (Map.Entry<String, DataHandler> entry : entries) {
-            String attName = entry.getKey();
-            DataHandler attValue = entry.getValue();
-            if (attValue != null) {
-                if (shouldOutputAttachment(camelMessage, attName, attValue)) {
+        for (Map.Entry<String, DataHandler> entry : 
camelMessage.getAttachments().entrySet()) {
+            String attachmentFilename = entry.getKey();
+            DataHandler handler = entry.getValue();
+            if (handler != null) {
+                if (shouldOutputAttachment(camelMessage, attachmentFilename, 
handler)) {
                     // Create another body part
-                    messageBodyPart = new MimeBodyPart();
+                    BodyPart messageBodyPart = new MimeBodyPart();
                     // Set the data handler to the attachment
-                    messageBodyPart.setDataHandler(attValue);
+                    messageBodyPart.setDataHandler(handler);
                     // Set the filename
-                    messageBodyPart.setFileName(attName);
+                    messageBodyPart.setFileName(attachmentFilename);
                     // Set Disposition
                     messageBodyPart.setDisposition(Part.ATTACHMENT);
                     // Add part to multipart
@@ -162,30 +150,31 @@
                 }
             }
         }
+
         // Put parts in message
         mimeMessage.setContent(multipart);
     }
 
     /**
-     * Converts the given object value to a String
-     */
-    protected String asString(Exchange exchange, Object value) {
-        return 
exchange.getContext().getTypeConverter().convertTo(String.class, value);
-    }
-
-    /**
      * Strategy to allow filtering of headers which are put on the Mail message
      */
-    protected boolean shouldOutputHeader(org.apache.camel.Message 
camelMessage, String headerName,
-                                         Object headerValue) {
+    protected boolean shouldOutputHeader(org.apache.camel.Message 
camelMessage, String headerName, Object headerValue) {
         return true;
     }
 
     /**
      * Strategy to allow filtering of attachments which are put on the Mail 
message
      */
-    protected boolean shouldOutputAttachment(org.apache.camel.Message 
camelMessage, String headerName,
-                                             DataHandler headerValue) {
+    protected boolean shouldOutputAttachment(org.apache.camel.Message 
camelMessage, String attachmentFilename, DataHandler handler) {
         return true;
     }
+
+    private static boolean empty(Address[] addresses) {
+        return addresses == null || addresses.length == 0;
+    }
+
+    private static String asString(Exchange exchange, Object value) {
+        return 
exchange.getContext().getTypeConverter().convertTo(String.class, value);
+    }
+
 }

Modified: 
activemq/camel/trunk/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailMessage.java
URL: 
http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailMessage.java?rev=653094&r1=653093&r2=653094&view=diff
==============================================================================
--- 
activemq/camel/trunk/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailMessage.java
 (original)
+++ 
activemq/camel/trunk/components/camel-mail/src/main/java/org/apache/camel/component/mail/MailMessage.java
 Sat May  3 09:29:26 2008
@@ -29,6 +29,7 @@
 
 import org.apache.camel.impl.DefaultMessage;
 import org.apache.camel.util.CollectionHelper;
+import org.apache.camel.RuntimeCamelException;
 
 /**
  * Represents a [EMAIL PROTECTED] org.apache.camel.Message} for working with 
Mail
@@ -82,7 +83,7 @@
             try {
                 answer = mailMessage.getHeader(name);
             } catch (MessagingException e) {
-                throw new MessageHeaderAccessException(name, e);
+                throw new RuntimeCamelException("Error accessing header: " + 
name, e);
             }
         }
         if (answer == null) {
@@ -110,21 +111,16 @@
     @Override
     protected void populateInitialHeaders(Map<String, Object> map) {
         if (mailMessage != null) {
-            Enumeration names;
-            try {
-                names = mailMessage.getAllHeaders();
-            } catch (MessagingException e) {
-                throw new MessageHeaderNamesAccessException(e);
-            }
             try {
+                Enumeration names = mailMessage.getAllHeaders();
                 while (names.hasMoreElements()) {
                     Header header = (Header)names.nextElement();
                     String value = header.getValue();
                     String name = header.getName();
                     CollectionHelper.appendValue(map, name, value);
                 }
-            } catch (Exception e) {
-                throw new MessageHeaderNamesAccessException(e);
+            } catch (MessagingException e) {
+                throw new RuntimeCamelException("Error accessing headers due 
to: " + e.getMessage(), e);
             }
         }
     }
@@ -133,9 +129,9 @@
     protected void populateInitialAttachments(Map<String, DataHandler> map) {
         if (mailMessage != null) {
             try {
-                extractAttachments(map);
-            } catch (MessagingException ex) {
-                throw new RuntimeMailException("Error populating the initial 
mail message attachments", ex);
+                extractAttachments(mailMessage, map);
+            } catch (Exception e) {
+                throw new RuntimeCamelException("Error populating the initial 
mail message attachments", e);
             }
         }
     }
@@ -149,48 +145,32 @@
     }
 
     /**
-     * Parses the attachments of the mail message and puts them to the message
+     * Parses the attachments of the given mail message and adds them to the 
map
      *
-     * @param map       the attachments map
-     * @throws javax.mail.MessagingException
+     * @param  message  the mail message with attachments
+     * @param  map      the map to add found attachments (attachmentFilename 
is the key)
      */
-    protected void extractAttachments(Map<String, DataHandler> map) throws 
javax.mail.MessagingException {
-        // TODO: Reuse spring mail support to handle the attachment
-        // now convert the mail attachments and put it to the msg
-        Multipart mp;
-        Object content;
-
-        try {
-            content = this.mailMessage.getContent();
-
-            if (content instanceof Multipart) {
-                // mail with attachment
-                mp = (Multipart)content;
-                int nbMP = mp.getCount();
-                for (int i = 0; i < nbMP; i++) {
-                    Part part = mp.getBodyPart(i);
-                    String disposition = part.getDisposition();
-
-                    if (disposition != null
-                        && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || 
disposition
-                            .equalsIgnoreCase(Part.INLINE))) {
+    protected static void extractAttachments(Message message, Map<String, 
DataHandler> map)
+        throws javax.mail.MessagingException, IOException {
+        
+        Object content = message.getContent();
+        if (content instanceof Multipart) {
+            // mail with attachment
+            Multipart mp = (Multipart)content;
+            for (int i = 0; i < mp.getCount(); i++) {
+                Part part = mp.getBodyPart(i);
+                String disposition = part.getDisposition();
+                if (disposition != null) {
+                    if (disposition.equalsIgnoreCase(Part.ATTACHMENT) || 
disposition.equalsIgnoreCase(Part.INLINE)) {
                         // only add named attachments
                         if (part.getFileName() != null) {
-                            // Parts marked with a disposition of
-                            // Part.ATTACHMENT
-                            // from part.getDisposition() are clearly
-                            // attachments
-                            DataHandler att = part.getDataHandler();
-                            // this is clearly a attachment
-                            CollectionHelper.appendValue(map, 
part.getFileName(), att);
+                            // Parts marked with a disposition of 
Part.ATTACHMENT are clearly attachments
+                            CollectionHelper.appendValue(map, 
part.getFileName(), part.getDataHandler());
                         }
                     }
                 }
             }
-        } catch (MessagingException e) {
-            throw new javax.mail.MessagingException("Error while setting 
content on normalized message", e);
-        } catch (IOException e) {
-            throw new javax.mail.MessagingException("Error while fetching 
content", e);
         }
     }
+
 }

Added: activemq/camel/trunk/components/camel-mail/src/test/data/logo.jpeg
URL: 
http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-mail/src/test/data/logo.jpeg?rev=653094&view=auto
==============================================================================
Binary file - no diff available.

Propchange: activemq/camel/trunk/components/camel-mail/src/test/data/logo.jpeg
------------------------------------------------------------------------------
    svn:mime-type = application/octet-stream

Added: 
activemq/camel/trunk/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailAttachmentTest.java
URL: 
http://svn.apache.org/viewvc/activemq/camel/trunk/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailAttachmentTest.java?rev=653094&view=auto
==============================================================================
--- 
activemq/camel/trunk/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailAttachmentTest.java
 (added)
+++ 
activemq/camel/trunk/components/camel-mail/src/test/java/org/apache/camel/component/mail/MailAttachmentTest.java
 Sat May  3 09:29:26 2008
@@ -0,0 +1,87 @@
+/**
+ * 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 java.util.Map;
+import javax.activation.DataHandler;
+import javax.activation.FileDataSource;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.Message;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Producer;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+
+/**
+ * Unit test for Camel attachments and Mail attachments.
+ */
+public class MailAttachmentTest extends ContextTestSupport {
+
+    public void testSendAndRecieveMailWithAttachments() throws Exception {
+        // START SNIPPET: e1
+
+        // create an exchange with a normal body and attachment to be produced 
as email
+        Endpoint endpoint = context.getEndpoint("smtp://[EMAIL PROTECTED]");
+
+        // 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")));
+
+        // 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(1000);
+
+        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, DataHandler> attachments = out.getIn().getAttachments();
+        assertNotNull("Should have attachments", attachments);
+        assertEquals(1, attachments.size());
+
+        DataHandler handler = out.getIn().getAttachment("logo.jpeg");
+        assertNotNull("The logo should be there", handler);
+        assertEquals("image/jpeg; name=logo.jpeg", handler.getContentType());
+
+        producer.stop();
+    }
+
+    protected RouteBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+            public void configure() throws Exception {
+                from("pop3://[EMAIL PROTECTED]").to("mock:result");
+            }
+        };
+    }
+}


Reply via email to