View Javadoc

1   /*
2    * $Id: AbstractEmailFunctionalTestCase.java 22518 2011-07-22 07:00:22Z claude.mamo $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.transport.email.functional;
12  
13  import static org.junit.Assert.assertEquals;
14  import static org.junit.Assert.assertNotNull;
15  import static org.junit.Assert.assertTrue;
16  import static org.junit.Assert.fail;
17  
18  import org.mule.DefaultMuleMessage;
19  import org.mule.api.MuleContext;
20  import org.mule.api.MuleMessage;
21  import org.mule.config.i18n.LocaleMessageHandler;
22  import org.mule.module.client.MuleClient;
23  import org.mule.tck.AbstractServiceAndFlowTestCase;
24  import org.mule.tck.junit4.rule.DynamicPort;
25  import org.mule.transport.email.GreenMailUtilities;
26  import org.mule.transport.email.ImapConnector;
27  import org.mule.transport.email.MailProperties;
28  import org.mule.transport.email.Pop3Connector;
29  import org.mule.util.SystemUtils;
30  
31  import com.icegreen.greenmail.util.GreenMail;
32  import com.icegreen.greenmail.util.ServerSetup;
33  
34  import java.util.HashMap;
35  import java.util.Locale;
36  import java.util.Map;
37  
38  import javax.activation.CommandMap;
39  import javax.activation.MailcapCommandMap;
40  import javax.mail.Address;
41  import javax.mail.Message;
42  import javax.mail.internet.MimeMessage;
43  import javax.mail.internet.MimeMultipart;
44  
45  import org.junit.Rule;
46  
47  public abstract class AbstractEmailFunctionalTestCase extends AbstractServiceAndFlowTestCase
48  {
49      public static final long DELIVERY_DELAY_MS = 10000;
50  
51      protected static final String CONFIG_BASE = "-functional-test.xml";
52      protected static final boolean MIME_MESSAGE = true;
53      protected static final boolean STRING_MESSAGE = false;
54  
55      protected static final String DEFAULT_EMAIL = "bob@example.com";
56      protected static final String DEFAULT_USER = "bob";
57      protected static final String DEFAULT_MESSAGE = "Test email message";
58      protected static final String DEFAULT_PASSWORD = "password";
59  
60      private String protocol;
61      private boolean isMimeMessage;
62      private int port;    
63      protected GreenMail server;
64      private String email;
65      private String user;
66      private String message;
67      private String password;
68      private String charset;
69      private boolean addAttachments;
70      protected ServerSetup setup = null;
71      // for tests which need to send emails in addition to receiving them
72      protected ServerSetup smtpSetup = null;
73      private int smtpPort;
74      private boolean addSmtp = false;
75  
76      @Rule
77      public DynamicPort dynamicPort1 = new DynamicPort("port1");
78  
79      @Rule
80      public DynamicPort dynamicPort2 = new DynamicPort("port2");
81  
82  
83      protected AbstractEmailFunctionalTestCase(ConfigVariant variant, boolean isMimeMessage, String protocol)
84      {
85          this(variant, isMimeMessage, protocol, protocol + CONFIG_BASE, null, null);
86      }
87  
88      protected AbstractEmailFunctionalTestCase(ConfigVariant variant, boolean isMimeMessage, String protocol, Locale locale, String charset)
89      {
90          this(variant, isMimeMessage, protocol, protocol + CONFIG_BASE, locale, charset);
91      }
92  
93      protected AbstractEmailFunctionalTestCase(ConfigVariant variant, boolean isMimeMessage, String protocol, String configResources)
94      {
95          this(variant, isMimeMessage, protocol, configResources, null, null);
96      }
97  
98      protected AbstractEmailFunctionalTestCase(ConfigVariant variant, boolean isMimeMessage, String protocol, String configResources, boolean addSmtp)
99      {
100         this(variant, isMimeMessage, protocol, configResources, null, null);
101         this.addSmtp = addSmtp;
102     }    
103     
104     protected AbstractEmailFunctionalTestCase(ConfigVariant variant, boolean isMimeMessage, String protocol, String configResources, Locale locale, String charset)
105     {
106         this(variant, isMimeMessage, protocol, configResources,
107                 DEFAULT_EMAIL, DEFAULT_USER, (locale == null ? DEFAULT_MESSAGE : getMessage(locale)), DEFAULT_PASSWORD, charset);
108     }
109 
110     protected AbstractEmailFunctionalTestCase(ConfigVariant variant, boolean isMimeMessage, String protocol,
111         String configResources, String email, String user, String message, String password, String charset)
112     {
113         super(variant, configResources);
114         this.isMimeMessage = isMimeMessage;
115         this.protocol = protocol;        
116         this.email = email;
117         this.user = user;
118         this.message = message;
119         this.password = password;
120         this.charset = charset;
121     }
122     
123     @Override
124     protected MuleContext createMuleContext() throws Exception
125     {
126         this.port = dynamicPort1.getNumber();
127         this.smtpPort = dynamicPort2.getNumber();
128         startServer();
129         initDefaultCommandMap();
130 
131         return super.createMuleContext();
132     }
133 
134     /**
135      * This is required to make all tests work on JDK5.
136      */
137     private void initDefaultCommandMap()
138     {
139         if (SystemUtils.JAVA_VERSION_FLOAT < 1.6f)
140         {
141             MailcapCommandMap commandMap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
142             commandMap.addMailcap("application/xml;;  x-java-content-handler=com.sun.mail.handlers.text_plain");
143             commandMap.addMailcap("application/text;; x-java-content-handler=com.sun.mail.handlers.text_plain");
144             CommandMap.setDefaultCommandMap(commandMap);
145         }
146     }
147 
148     @Override
149     public void doTearDown()
150     {
151         server.stop();
152     }
153 
154     protected void doSend() throws Exception
155     {
156         Object msg;
157         if (isMimeMessage)
158         {
159             msg = GreenMailUtilities.toMessage(message, email, charset);
160         }
161         else
162         {
163             msg = message;
164         }
165 
166         MuleClient client = new MuleClient(muleContext);
167         Map<String, Object> props = null;
168         if (charset != null)
169         {
170             props = new HashMap<String, Object>();
171             props.put(MailProperties.CONTENT_TYPE_PROPERTY, "text/plain; charset=" + charset);
172         }
173         if (addAttachments)
174         {
175             MuleMessage muleMessage = new DefaultMuleMessage(msg, props, muleContext);
176             createOutboundAttachments(muleMessage);
177             client.dispatch("vm://send", muleMessage);
178         }
179         else
180         {
181             client.dispatch("vm://send", msg, props);
182         }
183 
184         server.waitForIncomingEmail(DELIVERY_DELAY_MS, 1);
185 
186         MimeMessage[] messages = server.getReceivedMessages();
187         assertNotNull("did not receive any messages", messages);
188         assertEquals("did not receive 1 mail", 1, messages.length);
189         verifyMessage(messages[0]);
190     }
191 
192     protected void verifyMessage(MimeMessage received) throws Exception
193     {
194         if (addAttachments)
195         {
196             assertTrue("Did not receive a multipart message",
197                 received.getContent() instanceof MimeMultipart);
198             verifyMessage((MimeMultipart) received.getContent());
199         }
200         else
201         {
202             assertTrue("Did not receive a message with String contents",
203                 received.getContent() instanceof String);
204             verifyMessage((String) received.getContent());
205         }
206 
207         Address[] recipients = received.getRecipients(Message.RecipientType.TO);
208         assertNotNull(recipients);
209         assertEquals("number of recipients", 1, recipients.length);
210         assertEquals("recipient", email, recipients[0].toString());
211     }
212 
213     protected void verifyMessage(MimeMultipart mimeMultipart) throws Exception
214     {
215         fail("multipart message was not expected");
216     }
217 
218     protected void verifyMessage(String receivedText)
219     {
220         // for some reason, something is adding a newline at the end of messages
221         // so we need to strip that out for comparison
222         assertEquals(message, receivedText.trim());
223     }
224 
225     protected void doRequest() throws Exception
226     {
227         assertEquals(1, server.getReceivedMessages().length);
228 
229         MuleClient client = new MuleClient(muleContext);
230         MuleMessage reply = client.request("vm://receive", RECEIVE_TIMEOUT);
231 
232         assertNotNull(reply);
233         Object payload = reply.getPayload();
234         if (isMimeMessage)
235         {
236             assertTrue("payload is " + payload.getClass().getName(), payload instanceof MimeMessage);
237             verifyMessage((MimeMessage) payload);
238         }
239         else
240         {
241             assertTrue(payload instanceof String);
242             verifyMessage((String) payload);
243         }
244     }
245 
246     private void startServer() throws Exception
247     {
248         logger.debug("starting server on port " + port);
249         
250         setup = new ServerSetup(port, null, protocol);
251         if(addSmtp)
252         {
253             smtpSetup = new ServerSetup(smtpPort, null, "smtp");
254             server = new GreenMail(new ServerSetup[]{setup, smtpSetup});
255         }
256         else
257         {
258             server = new GreenMail(setup);
259         }                
260         server.start();
261         if (protocol.startsWith(Pop3Connector.POP3) || protocol.startsWith(ImapConnector.IMAP))
262         {
263             GreenMailUtilities.storeEmail(server.getManagers().getUserManager(),
264                     email, user, password,
265                     GreenMailUtilities.toMessage(message, email, charset));
266         }
267         logger.debug("server started for protocol " + protocol);
268     }
269 
270     private void stopServer()
271     {
272         server.stop();
273     }
274 
275     private static String getMessage(Locale locale)
276     {
277         return LocaleMessageHandler.getString("test-data", locale, "AbstractEmailFunctionalTestCase.getMessage", new Object[] {});
278     }
279 
280     public void setAddAttachments(boolean addAttachments)
281     {
282         this.addAttachments = addAttachments;
283     }
284 
285     private void createOutboundAttachments(MuleMessage msg) throws Exception
286     {
287         msg.addOutboundAttachment("hello", "hello", "text/plain");
288         msg.addOutboundAttachment("goodbye", "<a/>", "text/xml");
289     }
290 }