KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > email > MailMessageAdapter


1 /*
2  * $Id: MailMessageAdapter.java 3798 2006-11-04 04:07:14Z aperepel $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.providers.email;
12
13 import java.io.BufferedInputStream JavaDoc;
14 import java.io.BufferedReader JavaDoc;
15 import java.io.InputStream JavaDoc;
16 import java.io.InputStreamReader JavaDoc;
17 import java.util.Date JavaDoc;
18 import java.util.Enumeration JavaDoc;
19 import java.util.HashMap JavaDoc;
20 import java.util.Map JavaDoc;
21
22 import javax.mail.Header JavaDoc;
23 import javax.mail.Message JavaDoc;
24 import javax.mail.Multipart JavaDoc;
25 import javax.mail.Part JavaDoc;
26
27 import org.apache.commons.io.IOUtils;
28 import org.apache.commons.io.output.ByteArrayOutputStream;
29 import org.apache.commons.lang.SystemUtils;
30 import org.mule.config.i18n.Messages;
31 import org.mule.providers.AbstractMessageAdapter;
32 import org.mule.umo.MessagingException;
33 import org.mule.umo.provider.MessageTypeNotSupportedException;
34 import org.mule.util.StringUtils;
35
36 /**
37  * <code>MailMessageAdapter</code> is a wrapper for a javax.mail.Message.
38  */

39 public class MailMessageAdapter extends AbstractMessageAdapter
40 {
41     /**
42      * Serial version
43      */

44     private static final long serialVersionUID = -6013198455030918360L;
45
46     public static final String JavaDoc ATTACHMENT_HEADERS_PROPERTY_POSTFIX = "Headers";
47
48     private Part JavaDoc messagePart = null;
49     private byte[] contentBuffer;
50
51     public MailMessageAdapter(Object JavaDoc message) throws MessagingException
52     {
53         setMessage(message);
54     }
55
56     /*
57      * (non-Javadoc)
58      *
59      * @see org.mule.providers.UMOMessageAdapter#getPayload()
60      */

61     public Object JavaDoc getPayload()
62     {
63         return messagePart;
64     }
65
66     /*
67      * (non-Javadoc)
68      *
69      * @see org.mule.providers.UMOMessageAdapter#getPayloadAsBytes()
70      */

71     public byte[] getPayloadAsBytes() throws Exception JavaDoc
72     {
73         if (contentBuffer == null)
74         {
75             String JavaDoc contentType = messagePart.getContentType();
76
77             if (contentType.startsWith("text/"))
78             {
79                 getPayloadAsString();
80             }
81             else
82             {
83                 InputStream JavaDoc is = messagePart.getInputStream();
84                 // If the stream is not already buffered, wrap a BufferedInputStream
85
// around it.
86
if (!(is instanceof BufferedInputStream JavaDoc))
87                 {
88                     is = new BufferedInputStream JavaDoc(is);
89                 }
90
91                 ByteArrayOutputStream baos = new ByteArrayOutputStream(32768);
92                 IOUtils.copy(is, baos);
93                 contentBuffer = baos.toByteArray();
94             }
95         }
96         return contentBuffer;
97     }
98
99     /**
100      * Converts the message implementation into a String representation
101      *
102      * @param encoding The encoding to use when transforming the message (if
103      * necessary). The parameter is used when converting from a byte array
104      * @return String representation of the message payload
105      * @throws Exception Implementation may throw an endpoint specific exception
106      */

107     public String JavaDoc getPayloadAsString(String JavaDoc encoding) throws Exception JavaDoc
108     {
109         if (contentBuffer == null)
110         {
111             String JavaDoc contentType = messagePart.getContentType();
112
113             if (contentType.startsWith("text/"))
114             {
115                 InputStream JavaDoc is = messagePart.getInputStream();
116                 // If the stream is not already buffered, wrap a BufferedInputStream
117
// around it.
118
if (!(is instanceof BufferedInputStream JavaDoc))
119                 {
120                     is = new BufferedInputStream JavaDoc(is);
121                 }
122
123                 BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is));
124                 StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(32768);
125
126                 String JavaDoc line = reader.readLine();
127                 buffer.append(line).append(SystemUtils.LINE_SEPARATOR);
128                 while (line != null)
129                 {
130                     line = reader.readLine();
131                     buffer.append(line).append(SystemUtils.LINE_SEPARATOR);
132                 }
133
134                 contentBuffer = buffer.toString().getBytes();
135             }
136             else
137             {
138                 contentBuffer = getPayloadAsBytes();
139             }
140         }
141         return new String JavaDoc(contentBuffer, encoding);
142     }
143
144     /*
145      * (non-Javadoc)
146      *
147      * @see org.mule.providers.UMOMessageAdapter#setMessage(java.lang.Object)
148      */

149     protected void setMessage(Object JavaDoc message) throws MessagingException
150     {
151         Message JavaDoc msg;
152         if (message instanceof Message JavaDoc)
153         {
154             msg = (Message JavaDoc)message;
155         }
156         else
157         {
158             throw new MessageTypeNotSupportedException(message, MailMessageAdapter.class);
159         }
160
161         try
162         {
163             Object JavaDoc content = msg.getContent();
164
165             if (content instanceof Multipart JavaDoc)
166             {
167                 this.messagePart = ((Multipart JavaDoc)content).getBodyPart(0);
168                 logger.debug("Received Multipart message");
169
170                 for (int i = 1; i < ((Multipart JavaDoc)content).getCount(); i++)
171                 {
172                     Part JavaDoc part = ((Multipart JavaDoc)content).getBodyPart(i);
173                     String JavaDoc name = part.getFileName();
174                     if (name == null)
175                     {
176                         name = String.valueOf(i - 1);
177                     }
178                     addAttachment(name, part.getDataHandler());
179                     addAttachmentHeaders(name, part);
180                 }
181             }
182             else
183             {
184                 messagePart = msg;
185             }
186
187             // Set message attrributes as properties
188
setProperty(MailProperties.TO_ADDRESSES_PROPERTY,
189                 MailUtils.mailAddressesToString(msg.getRecipients(Message.RecipientType.TO)));
190             setProperty(MailProperties.CC_ADDRESSES_PROPERTY,
191                 MailUtils.mailAddressesToString(msg.getRecipients(Message.RecipientType.CC)));
192             setProperty(MailProperties.BCC_ADDRESSES_PROPERTY,
193                 MailUtils.mailAddressesToString(msg.getRecipients(Message.RecipientType.BCC)));
194             setProperty(MailProperties.REPLY_TO_ADDRESSES_PROPERTY,
195                 MailUtils.mailAddressesToString(msg.getReplyTo()));
196             setProperty(MailProperties.FROM_ADDRESS_PROPERTY, MailUtils.mailAddressesToString(msg.getFrom()));
197             setProperty(MailProperties.SUBJECT_PROPERTY, StringUtils.defaultIfEmpty(msg.getSubject(),
198                 "(no subject)"));
199             setProperty(MailProperties.CONTENT_TYPE_PROPERTY, StringUtils.defaultIfEmpty(
200                 msg.getContentType(), "text/plain"));
201
202             Date JavaDoc sentDate = msg.getSentDate();
203             if (sentDate == null)
204             {
205                 sentDate = new Date JavaDoc();
206             }
207             setProperty(MailProperties.SENT_DATE_PROPERTY, sentDate);
208
209             for (Enumeration JavaDoc e = msg.getAllHeaders(); e.hasMoreElements();)
210             {
211                 Header JavaDoc h = (Header JavaDoc)e.nextElement();
212                 setProperty(h.getName(), h.getValue());
213             }
214
215         }
216         catch (Exception JavaDoc e)
217         {
218             throw new MessagingException(new org.mule.config.i18n.Message(Messages.FAILED_TO_CREATE_X,
219                 "Message Adapter"), e);
220         }
221     }
222
223     protected void addAttachmentHeaders(String JavaDoc name, Part JavaDoc part) throws javax.mail.MessagingException JavaDoc
224     {
225         Map JavaDoc headers = new HashMap JavaDoc(4);
226         for (Enumeration JavaDoc e = part.getAllHeaders(); e.hasMoreElements();)
227         {
228             Header JavaDoc h = (Header JavaDoc)e.nextElement();
229             headers.put(h.getName(), h.getValue());
230         }
231         if (headers.size() > 0)
232         {
233             setProperty(name + ATTACHMENT_HEADERS_PROPERTY_POSTFIX, headers);
234         }
235     }
236 }
237
Popular Tags