KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > servicemix > components > email > MimeMailMarshaler


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.servicemix.components.email;
18
19 import java.io.File JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.util.Date JavaDoc;
22 import java.util.HashMap JavaDoc;
23 import java.util.Iterator JavaDoc;
24 import java.util.Set JavaDoc;
25 import java.util.StringTokenizer JavaDoc;
26
27 import javax.activation.DataHandler JavaDoc;
28 import javax.activation.DataSource JavaDoc;
29 import javax.activation.FileDataSource JavaDoc;
30 import javax.jbi.messaging.MessageExchange;
31 import javax.jbi.messaging.MessagingException;
32 import javax.jbi.messaging.NormalizedMessage;
33 import javax.mail.Address JavaDoc;
34 import javax.mail.BodyPart JavaDoc;
35 import javax.mail.Message JavaDoc;
36 import javax.mail.Multipart JavaDoc;
37 import javax.mail.Part JavaDoc;
38 import javax.mail.internet.AddressException JavaDoc;
39 import javax.mail.internet.InternetAddress JavaDoc;
40 import javax.mail.internet.MimeBodyPart JavaDoc;
41 import javax.mail.internet.MimeMessage JavaDoc;
42 import javax.mail.internet.MimeMultipart JavaDoc;
43 import javax.xml.transform.TransformerException JavaDoc;
44
45 import org.apache.commons.lang.StringUtils;
46 import org.apache.commons.logging.Log;
47 import org.apache.commons.logging.LogFactory;
48 import org.apache.servicemix.jbi.jaxp.StringSource;
49
50 /**
51  * The default marshaler from the {@link NormalizedMessage} to a Mime email using
52  * expressions for each field required on the email.
53  *
54  * @version $Revision: 429277 $
55  */

56 public class MimeMailMarshaler extends MailMarshalerSupport {
57     private static Log log = LogFactory.getLog(MimeMailPoller.class);
58
59     /**
60      * Populates the MessageExchange with values extracted from the mail message using expressions.
61      *
62      * @param exchange the JBI message exchange
63      * @param normalizedMessage the normalized message from JBI
64      * @param mimeMessage the mime email
65      * @throws javax.mail.MessagingException if the message could not be constructed or there was an error creating an address
66      */

67     public void prepareExchange(MessageExchange exchange, NormalizedMessage normalizedMessage, MimeMessage JavaDoc mimeMessage) throws javax.mail.MessagingException JavaDoc {
68         String JavaDoc from = InternetAddress.toString(mimeMessage.getFrom());
69         String JavaDoc to = InternetAddress.toString(mimeMessage.getRecipients(Message.RecipientType.TO));
70         String JavaDoc cc = InternetAddress.toString(mimeMessage.getRecipients(Message.RecipientType.CC));
71         String JavaDoc replyTo = InternetAddress.toString(mimeMessage.getReplyTo());
72         String JavaDoc sentDate = getDateFormat().format(mimeMessage.getSentDate());
73         String JavaDoc text = null;
74         String JavaDoc html = null;
75         MimeMultipart JavaDoc mp = null;
76         Object JavaDoc content = null;
77         Object JavaDoc subContent = null;
78         MimeMultipart JavaDoc subMP = null;
79
80         try {
81             content = mimeMessage.getContent();
82             if (content instanceof String JavaDoc)
83                 // simple mail
84
text = asString(content);
85             else if (content instanceof MimeMultipart JavaDoc) {
86                 // mail with attachment
87
mp = (MimeMultipart JavaDoc)content;
88                 int nbMP = mp.getCount();
89                 for (int i=0; i < nbMP; i++) {
90                     Part JavaDoc part = mp.getBodyPart(i);
91                     String JavaDoc disposition = part.getDisposition();
92                     if ((disposition != null) &&
93                         ((disposition.equals(Part.ATTACHMENT) ||
94                          (disposition.equals(Part.INLINE))))) {
95                         //Parts marked with a disposition of Part.ATTACHMENT from part.getDisposition() are clearly attachments
96
DataHandler JavaDoc att = part.getDataHandler();
97                         normalizedMessage.addAttachment(att.getName(), att);
98                     } else {
99                         MimeBodyPart JavaDoc mbp = (MimeBodyPart JavaDoc)part;
100                         if (mbp.isMimeType("text/plain")) {
101                           // Handle plain
102
text = (String JavaDoc)mbp.getContent();
103                         } else if (mbp.isMimeType("text/html")) {
104                           // Handle html contents
105
html = (String JavaDoc)mbp.getContent();
106                         } else if (mbp.isMimeType("multipart/related")){
107                             // Special case for multipart/related message type
108
subContent = mbp.getContent();
109                             if (subContent instanceof MimeMultipart JavaDoc) {
110                                 subMP = (MimeMultipart JavaDoc)subContent;
111                                 int nbsubMP = subMP.getCount();
112                                 for (int j=0; j < nbsubMP; j++) {
113                                     MimeBodyPart JavaDoc subMBP = (MimeBodyPart JavaDoc)part;
114                                     // add a property into the normalize message
115
normalizedMessage.setProperty("org.apache.servicemix.email.alternativeContent" + j, subMBP.getContent());
116                                 }
117                             }
118                         } else // strange mail...log a warning
119
log.warn("Some mail contents can not be traited and is not include into message");
120                     }
121                 }
122             } else { // strange mail...log a warning
123
log.warn("Some mail contents can not be traited and is not include into message");
124             }
125         } catch (MessagingException e) {
126             throw new javax.mail.MessagingException JavaDoc("Error while setting content on normalized message",e);
127         } catch (IOException JavaDoc e) {
128             throw new javax.mail.MessagingException JavaDoc("Error while fetching content",e);
129         }
130
131         normalizedMessage.setProperty("org.apache.servicemix.email.from", from);
132         normalizedMessage.setProperty("org.apache.servicemix.email.to", to);
133         normalizedMessage.setProperty("org.apache.servicemix.email.cc", cc);
134         normalizedMessage.setProperty("org.apache.servicemix.email.text", text);
135         normalizedMessage.setProperty("org.apache.servicemix.email.replyTo", replyTo);
136         normalizedMessage.setProperty("org.apache.servicemix.email.sentDate", sentDate);
137         normalizedMessage.setProperty("org.apache.servicemix.email.html", html);
138
139         try {
140             normalizedMessage.setContent(new StringSource(text));
141         } catch (MessagingException e) {
142             throw new javax.mail.MessagingException JavaDoc("Error while setting content on normalized message",e);
143         }
144     }
145
146     /**
147      * Populates the mime email message with values extracted from the message exchange using expressions.
148      *
149      * @param mimeMessage the mime email
150      * @param exchange the JBI message exchange
151      * @param normalizedMessage the normalized message from JBI
152      * @throws javax.mail.MessagingException if the message could not be constructed or there was an error creating an address
153      */

154     public void prepareMessage(MimeMessage JavaDoc mimeMessage, MessageExchange exchange, NormalizedMessage normalizedMessage) throws javax.mail.MessagingException JavaDoc {
155         try {
156             Address JavaDoc to = getTo(exchange, normalizedMessage);
157             if (to != null) {
158                 mimeMessage.setRecipient(Message.RecipientType.TO, to);
159             }
160             Address JavaDoc cc = getCc(exchange, normalizedMessage);
161             if (cc != null) {
162                 mimeMessage.setRecipient(Message.RecipientType.CC, cc);
163             }
164             Address JavaDoc bcc = getBcc(exchange, normalizedMessage);
165             if (bcc != null) {
166                 mimeMessage.setRecipient(Message.RecipientType.BCC, bcc);
167             }
168             Address JavaDoc from = getFrom(exchange, normalizedMessage);
169             if (from != null) {
170                 mimeMessage.setFrom(from);
171             }
172             String JavaDoc text = getText(exchange, normalizedMessage);
173             String JavaDoc html = getHtml(exchange, normalizedMessage);
174             if ((text != null) && (html == null)) {
175                 mimeMessage.setText(text);
176             }
177             else if ((text != null) && (html != null)) {
178                 MimeMultipart JavaDoc content = new MimeMultipart JavaDoc("alternative");
179                 MimeBodyPart JavaDoc textBodyPart = new MimeBodyPart JavaDoc();
180                 MimeBodyPart JavaDoc htmlBodyPart = new MimeBodyPart JavaDoc();
181                 textBodyPart.setText(text);
182                 htmlBodyPart.setContent(html, "text/html");
183                 content.addBodyPart(textBodyPart);
184                 content.addBodyPart(htmlBodyPart);
185
186                 mimeMessage.setContent(content);
187             }
188             String JavaDoc subject = getSubject(exchange, normalizedMessage);
189             if (subject != null) {
190                 mimeMessage.setSubject(subject);
191             }
192             Date JavaDoc sentDate = getSentDate(exchange, normalizedMessage);
193             if (sentDate != null) {
194                 mimeMessage.setSentDate(sentDate);
195             }
196             Address JavaDoc[] replyTo = getReplyTo(exchange, normalizedMessage);
197             if (replyTo != null) {
198                 mimeMessage.setReplyTo(replyTo);
199             }
200
201             // add attachment from message and properties
202
HashMap JavaDoc attachments = this.getAttachments(exchange, normalizedMessage);
203             if (attachments != null) {
204                 Set JavaDoc attNames = attachments.keySet();
205                 Iterator JavaDoc itAttNames = attNames.iterator();
206                 if (itAttNames.hasNext()) { // there is at least one attachment
207
// Create the message part
208
BodyPart JavaDoc messageBodyPart = new MimeBodyPart JavaDoc();
209                     // Fill the message
210
messageBodyPart.setText(text);
211                     // Create a Multipart
212
Multipart JavaDoc multipart = new MimeMultipart JavaDoc();
213                     // Add part one
214
multipart.addBodyPart(messageBodyPart);
215                     while (itAttNames.hasNext()) {
216                         String JavaDoc oneAttachmentName = (String JavaDoc)itAttNames.next();
217                         // Create another body part
218
messageBodyPart = new MimeBodyPart JavaDoc();
219                         // Set the data handler to the attachment
220
messageBodyPart.setDataHandler(new DataHandler JavaDoc((DataSource JavaDoc)attachments.get(oneAttachmentName)));
221                         // Set the filename
222
messageBodyPart.setFileName(oneAttachmentName);
223                         // Set Disposition
224
messageBodyPart.setDisposition(Part.ATTACHMENT);
225                         // Add part to multipart
226
multipart.addBodyPart(messageBodyPart);
227                     }
228                     // Put parts in message
229
mimeMessage.setContent(multipart);
230                  }
231             }
232         }
233         catch (MessagingException e) {
234             throw new javax.mail.MessagingException JavaDoc(e.getMessage(), e);
235         }
236         catch (TransformerException JavaDoc e) {
237             throw new javax.mail.MessagingException JavaDoc(e.getMessage(), e);
238         }
239     }
240
241
242     // Implementation methods
243
//-------------------------------------------------------------------------
244
protected Address JavaDoc getFrom(MessageExchange exchange, NormalizedMessage normalizedMessage) throws MessagingException, AddressException JavaDoc {
245         return asAddress(getFrom().evaluate(exchange, normalizedMessage));
246     }
247
248     protected Address JavaDoc getTo(MessageExchange exchange, NormalizedMessage normalizedMessage) throws MessagingException, AddressException JavaDoc {
249         return asAddress(getTo().evaluate(exchange, normalizedMessage));
250     }
251
252     protected Address JavaDoc getCc(MessageExchange exchange, NormalizedMessage normalizedMessage) throws MessagingException, AddressException JavaDoc {
253         return asAddress(getCc().evaluate(exchange, normalizedMessage));
254     }
255
256     protected Address JavaDoc getBcc(MessageExchange exchange, NormalizedMessage normalizedMessage) throws MessagingException, AddressException JavaDoc {
257         return asAddress(getBcc().evaluate(exchange, normalizedMessage));
258     }
259
260     protected Address JavaDoc[] getReplyTo(MessageExchange exchange, NormalizedMessage normalizedMessage) throws MessagingException, AddressException JavaDoc {
261         return asAddressArray(getReplyTo().evaluate(exchange, normalizedMessage));
262     }
263
264     protected HashMap JavaDoc getAttachments(MessageExchange exchange, NormalizedMessage normalizedMessage) {
265         HashMap JavaDoc attachments = new HashMap JavaDoc();
266         String JavaDoc filePath = "";
267         String JavaDoc oneAttachmentName = "";
268         try {
269             // get attachment from property org.apache.servicemix.email.attachment
270
String JavaDoc listAttachment = (String JavaDoc)getAttachments().evaluate(exchange, normalizedMessage);
271             if (StringUtils.isNotBlank(listAttachment)) {
272                 StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(listAttachment, ",");
273                 if (st != null) {
274                     while (st.hasMoreTokens()) {
275                         filePath = st.nextToken();
276                         File JavaDoc file = new File JavaDoc(filePath);
277                         attachments.put(file.getName(), new FileDataSource JavaDoc(file));
278                     }
279                 }
280             }
281         } catch (MessagingException e) {
282             log.warn("file not found for attachment : " + e.getMessage() + " : " + filePath);
283         }
284         // get attachment from Normalize Message
285
Set JavaDoc attNames = normalizedMessage.getAttachmentNames();
286         Iterator JavaDoc itAttNames = attNames.iterator();
287         while (itAttNames.hasNext()) {
288             oneAttachmentName = (String JavaDoc)itAttNames.next();
289             DataSource JavaDoc oneAttchmentInputString = normalizedMessage.getAttachment(oneAttachmentName).getDataSource();
290             attachments.put(oneAttachmentName, oneAttchmentInputString);
291         }
292
293         return attachments;
294     }
295
296 }
297
Popular Tags