KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencrx > mail > servlet > SimpleMimeMessage


1 /*
2  * ====================================================================
3  * Project: opencrx, http://www.opencrx.org/
4  * Name: $Id: SimpleMimeMessage.java,v 1.8 2006/03/29 15:43:31 wfro Exp $
5  * Description: openCRX EMailImporter
6  * Revision: $Revision: 1.8 $
7  * Owner: CRIXP AG, Switzerland, http://www.crixp.com
8  * Date: $Date: 2006/03/29 15:43:31 $
9  * ====================================================================
10  *
11  * This software is published under the BSD license
12  * as listed below.
13  *
14  * Copyright (c) 2004-2006, CRIXP Corp., Switzerland
15  * All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  *
21  * * Redistributions of source code must retain the above copyright
22  * notice, this list of conditions and the following disclaimer.
23  *
24  * * Redistributions in binary form must reproduce the above copyright
25  * notice, this list of conditions and the following disclaimer in
26  * the documentation and/or other materials provided with the
27  * distribution.
28  *
29  * * Neither the name of CRIXP Corp. nor the names of the contributors
30  * to openCRX may be used to endorse or promote products derived
31  * from this software without specific prior written permission
32  *
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
35  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
36  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
37  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
39  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
40  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
41  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
43  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
45  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
46  * POSSIBILITY OF SUCH DAMAGE.
47  *
48  * ------------------
49  *
50  * This product includes software developed by the Apache Software
51  * Foundation (http://www.apache.org/).
52  *
53  * This product includes software developed by contributors to
54  * openMDX (http://www.openmdx.org/)
55  */

56 package org.opencrx.mail.servlet;
57
58 import java.io.BufferedReader JavaDoc;
59 import java.io.ByteArrayOutputStream JavaDoc;
60 import java.io.IOException JavaDoc;
61 import java.io.InputStream JavaDoc;
62 import java.io.InputStreamReader JavaDoc;
63 import java.util.ArrayList JavaDoc;
64 import java.util.Collection JavaDoc;
65 import java.util.Date JavaDoc;
66 import java.util.Enumeration JavaDoc;
67 import java.util.Iterator JavaDoc;
68 import java.util.List JavaDoc;
69
70 import javax.mail.Address JavaDoc;
71 import javax.mail.Flags JavaDoc;
72 import javax.mail.Message JavaDoc;
73 import javax.mail.MessagingException JavaDoc;
74 import javax.mail.Part JavaDoc;
75 import javax.mail.internet.AddressException JavaDoc;
76 import javax.mail.internet.InternetAddress JavaDoc;
77 import javax.mail.internet.MimeBodyPart JavaDoc;
78 import javax.mail.internet.MimeMessage JavaDoc;
79 import javax.mail.internet.MimeMultipart JavaDoc;
80
81 import org.openmdx.application.log.AppLog;
82 import org.openmdx.base.exception.ServiceException;
83 import org.openmdx.kernel.id.UUIDs;
84
85 /**
86  * Helper class to provide a more simple access to the regularly used attributes
87  * of a mime message for importing emails into the openCRX system.
88  */

89 public class SimpleMimeMessage {
90   
91   /**
92    * Constructor
93    *
94    * @param theMessage
95    * the MimeMessage which has to be wrapped
96    */

97     public SimpleMimeMessage(
98         MimeMessage JavaDoc theMessage
99     ) {
100         this(theMessage, false);
101     }
102
103   /**
104    * Constructor
105    * If <code>initAttributes</code> is true, the attributes are initialized
106    * immediately by parsing the underlying MimeMessage. Therefore although
107    * the folder containing the MimeMessage may already be closed, this
108    * instance already holds the derived values for the attributes.
109    *
110    * @param theMessage
111    * the MimeMessage which has to be wrapped
112    * @param initAttributes
113    * true if the attributes should be initialized immediately, false otherwise
114    */

115     public SimpleMimeMessage(
116         MimeMessage JavaDoc theMessage,
117         boolean initAttributes
118     ) {
119         this.mimeMsg = theMessage;
120         if(initAttributes) {
121             this.getBody();
122             this.getDate();
123             this.getFrom();
124             this.getMessageID();
125             this.getPriority();
126             this.getRecipients();
127             this.getSubject();
128             this.getAllHeaderLinesAsString();
129             this.getMessageIdentity();
130         }
131     }
132
133   /**
134    * Get all the headers for this header_name. Note that certain headers may
135    * be encoded as per RFC 2047 if they contain non US-ASCII characters and
136    * these should be decoded.
137    * <p>
138    *
139    * This implementation obtains the headers from the <code>headers</code>
140    * InternetHeaders object.
141    *
142    * @param name
143    * name of header
144    * @return array of headers
145    * @see javax.mail.internet.MimeMessage
146    */

147     public String JavaDoc[] getHeader(
148         String JavaDoc name
149     ) {
150         try {
151           // extract the appropriate header element's value
152
return this.mimeMsg.getHeader(name);
153         } catch (MessagingException JavaDoc e) {
154           AppLog.warning("Could not extract header element '" + name
155               + "' of message " + getMessageID());
156           ServiceException e0 = new ServiceException(e);
157           AppLog.warning(e0.getMessage(), e0.getCause(), 1);
158         }
159         return null;
160     }
161
162   /**
163    * Extracts the complete content of all header elements of a MIME message
164    * and returns them as concatenated string using the system's line separator
165    * as separator between the elements.
166    *
167    * @return the concatenated header elements of the message
168    */

169   public String JavaDoc getAllHeaderLinesAsString() {
170
171     if(this.headerLines == null) {
172       try {
173         StringBuffer JavaDoc text = new StringBuffer JavaDoc();
174         Enumeration JavaDoc lines = this.mimeMsg.getAllHeaderLines();
175         while (lines.hasMoreElements()) {
176           text.append((String JavaDoc) lines.nextElement());
177           text.append(System.getProperty("line.separator", "\n"));
178         }
179         this.headerLines = text.toString();
180       } catch (MessagingException JavaDoc e) {
181         AppLog.warning("Could not extract header lines for message " + getMessageID());
182         ServiceException e0 = new ServiceException(e);
183         AppLog.warning(e0.getMessage(), e0.getCause(), 1);
184       }
185     }
186     return this.headerLines;
187   }
188
189   /**
190    * Extracts the body part of a MIME message, currently only message bodies
191    * of the following formats are supported:<BR>
192    * <UL>
193    * <LI>String</LI>
194    * <LI>InputStream</LI>
195    * <LI>MultiPart</LI>
196    * </UL>
197    * In case of MultiParts only parts of the mime types "text/plain" and
198    * "text/html" are currently supported.
199    * The body is returned in string format.
200    *
201    * @return
202    */

203   public String JavaDoc getBody() {
204     if (this.messageBody == null) {
205       try {
206         Object JavaDoc content = this.mimeMsg.getContent();
207         if (content instanceof String JavaDoc) {
208           this.messageBody = (String JavaDoc) content;
209           this.bodyType = this.mimeMsg.getContentType();
210         }
211         else if (content instanceof MimeMultipart JavaDoc) {
212           MimeMultipart JavaDoc multipart = (MimeMultipart JavaDoc)content;
213           for ( int i = 0; i < multipart.getCount(); i++ ) {
214             this.parsePart((MimeBodyPart JavaDoc)multipart.getBodyPart(i));
215           }
216         }
217         else if (content instanceof MimeBodyPart JavaDoc) {
218           this.parsePart((MimeBodyPart JavaDoc)content);
219         }
220         else if (content instanceof InputStream JavaDoc) {
221           String JavaDoc mimeType = mimeMsg.getContentType();
222           if (this.mimeMsg.isMimeType("text/plain") || mimeMsg.isMimeType("text/html")) {
223             this.bodyType = mimeMsg.getContentType();
224             BufferedReader JavaDoc in = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(
225                 this.mimeMsg.getInputStream())
226             );
227             StringBuffer JavaDoc msgBody = new StringBuffer JavaDoc();
228             while (in.ready()) {
229               msgBody.append(in.readLine());
230               if (in.ready()) {
231                 msgBody.append(System.getProperty("line.separator", "\n"));
232               }
233             }
234             this.messageBody = msgBody.toString();
235           }
236           else {
237             AppLog.info("Content of type '" + mimeType + "' is handled as binary type"
238                 + " for message " +getMessageID());
239           }
240         }
241         else {
242           AppLog.warning("Not a supported content format for message "
243                 + getMessageID());
244         }
245       } catch (IOException JavaDoc e) {
246         AppLog.warning("Could not read message content " + getMessageID());
247         ServiceException e0 = new ServiceException(e);
248         AppLog.warning(e0.getMessage(), e0.getCause(), 1);
249       } catch (MessagingException JavaDoc e) {
250         AppLog.warning("Could not read message content " + getMessageID());
251         ServiceException e0 = new ServiceException(e);
252         AppLog.warning(e0.getMessage(), e0.getCause(), 1);
253       }
254     }
255     return this.messageBody;
256   }
257
258   public String JavaDoc getMessageIdentity() {
259     if (this.messageIdentity == null) {
260       try {
261         // extract the message ID
262
this.messageIdentity = this.mimeMsg.getHeader(OPENCRX_MESSAGE_IDENTITY,null);
263         if(this.messageIdentity == null) {
264           this.messageIdentity = "";
265         }
266       } catch (MessagingException JavaDoc e) {
267         AppLog.warning("Could not extract message identity for message " + getMessageID());
268         ServiceException e0 = new ServiceException(e);
269         AppLog.warning(e0.getMessage(), e0.getCause(), 1);
270       }
271     }
272     return messageIdentity;
273   }
274   /**
275    * Extracts the message ID of the message and cache it locally
276    *
277    * @return the message ID of the message
278    */

279   public String JavaDoc getMessageID(
280   ) {
281     if (this.messageId == null) {
282       try {
283         // extract the message ID
284
this.messageId = this.mimeMsg.getMessageID();
285         if(this.messageId == null || this.messageId.length() == 0) {
286           this.messageId = OPENCRX_MESSAGE_ID + UUIDs.getGenerator().next();
287         }
288       } catch (MessagingException JavaDoc e) {
289         AppLog.warning("Could not extract message ID for message " + getMessageID());
290         ServiceException e0 = new ServiceException(e);
291         AppLog.warning(e0.getMessage(), e0.getCause(), 1);
292       }
293     }
294     return this.messageId;
295   }
296
297   /**
298    * Extracts the subject of the message and cache it locally. If the message
299    * contains several subject entries, these entries are concatenated using
300    * the system's line separator.
301    *
302    * @return the subject of the message
303    */

304   public String JavaDoc getSubject(
305   ) {
306     if (this.subject == null) {
307       try {
308         // extract the subject
309
// if
310
// handle a mail with no subject or with more than one subject
311
// as if subject is an empty string.
312
String JavaDoc[] subjects = this.mimeMsg.getHeader("Subject");
313         if (subjects != null && subjects.length > 0) {
314           StringBuffer JavaDoc msgSubject = new StringBuffer JavaDoc();
315           for (int i = 0; i < subjects.length; i++) {
316             msgSubject.append(subjects[i]);
317             if ((i + 1) < subjects.length) {
318               msgSubject.append(System.getProperty("line.separator", "\n"));
319             }
320           }
321           this.subject = msgSubject.toString();
322         }
323       } catch (MessagingException JavaDoc e) {
324         AppLog.warning("Could not extract subject for message " + getMessageID());
325         ServiceException e0 = new ServiceException(e);
326         AppLog.warning(e0.getMessage(), e0.getCause(), 1);
327       }
328     }
329     return this.subject;
330   }
331
332   /**
333    * Extracts date of the message it was sent and cache it locally. Returns null
334    * if no date is contained in the message.
335    *
336    * @return the subject of the message
337    */

338   public Date JavaDoc getDate(
339   ) {
340     Date JavaDoc date = null;
341     try {
342       date = this.mimeMsg.getSentDate();
343     } catch (MessagingException JavaDoc e) {
344       AppLog.warning("Could not extract the send date of message " + getMessageID());
345       ServiceException e0 = new ServiceException(e);
346       AppLog.warning(e0.getMessage(), e0.getCause(), 1);
347     }
348     return date;
349   }
350
351   /**
352    * Extracts the sender's email address from the message and cache it locally.
353    * If no address is found <code>UNSPECIFIED_ADDRESS</code> is used.
354    *
355    * @return the sender's email addresses
356    */

357   public String JavaDoc[] getFrom(
358   ) {
359     if(this.from == null) {
360       try {
361         // Get FROM EMailAddress
362
Address JavaDoc[] headerFromAddresses = this.mimeMsg.getFrom();
363         this.from = getAddresses(headerFromAddresses);
364       } catch (MessagingException JavaDoc e) {
365         e.printStackTrace();
366         AppLog.warning("Could not extract the sender's 'from' address of message " + getMessageID());
367         ServiceException e0 = new ServiceException(e);
368         AppLog.warning(e0.getMessage(), e0.getCause(), 1);
369       }
370     }
371     return this.from;
372   }
373
374   /**
375    * Extracts the recipients of type Message.RecipientType.TO ("To") of
376    * the message and cache it locally.
377    *
378    * @return the recipients' email addresses
379    */

380   public String JavaDoc[] getRecipients(
381   ) {
382     return this.getRecipients(Message.RecipientType.TO);
383   }
384
385   /**
386    * Extracts the recipients of the given type of the message and cache it locally.
387    *
388    * @param type the type for which the addresses are needed, i.e. either
389    * "To", "Cc" or "Bcc"
390    * @return the recipients' email addresses
391    */

392   public String JavaDoc[] getRecipients(
393       Message.RecipientType JavaDoc type
394   ) {
395     if(Message.RecipientType.TO.toString().equalsIgnoreCase(type.toString())) {
396       if(this.to == null) {
397         this.to = getRecipientsByType(type);
398       }
399       return this.to;
400     }
401     else if (Message.RecipientType.CC.toString().equalsIgnoreCase(type.toString())) {
402       if (this.cc == null) {
403         this.cc = getRecipientsByType(type);
404       }
405       return this.cc;
406     }
407     else if (Message.RecipientType.BCC.toString().equalsIgnoreCase(type.toString())) {
408       if(this.bcc == null) {
409         this.bcc = getRecipientsByType(type);
410       }
411       return this.bcc;
412     }
413     return null;
414   }
415
416   /**
417    * Extract the priority from the email message. Note that if no header
418    * element is found this indicates a "normal" priority. Note that rfc822
419    * does not define a standard header field for priority. The name of the
420    * "priority" header field depends on your mail client used. "Importance"
421    * with values high, normal and low "Priority" with values Urgent and
422    * Non-Urgent "X-Priority" with values 1=high and 5=low These values are
423    * mapped to:
424    * <UL>
425    * <LI>ACTIVITY_PRIORITY_LOW,
426    * <LI>ACTIVITY_PRIORITY_NORMAL and
427    * <LI>ACTIVITY_PRIORITY_HIGH
428    * </UL>
429    * respectively.
430    *
431    * @return the subject of the message
432    */

433   public short getPriority(
434   ) {
435     String JavaDoc priority = "normal";
436     short priorityAsShort = PRIORITY_NORMAL;
437     try {
438       String JavaDoc[] values = this.mimeMsg.getHeader("Importance");
439       if (values != null && values.length > 0) {
440         priority = values[0];
441       }
442       values = this.mimeMsg.getHeader("X-Priority");
443       if (values != null && values.length > 0) {
444         priority = values[0];
445       }
446       values = this.mimeMsg.getHeader("Priority");
447       if (values != null && values.length > 0) {
448         priority = values[0];
449       }
450     } catch (MessagingException JavaDoc e) {
451       AppLog.warning("Could not extract message priority for message " + getMessageID());
452       ServiceException e0 = new ServiceException(e);
453       AppLog.warning(e0.getMessage(), e0.getCause(), 1);
454     }
455     if (priority.equalsIgnoreCase("normal") || priority.equalsIgnoreCase("3")) {
456       priorityAsShort = PRIORITY_NORMAL;
457     } else if (priority.equalsIgnoreCase("high")
458         || priority.equalsIgnoreCase("1")
459         || priority.equalsIgnoreCase("Urgent")) {
460       priorityAsShort = PRIORITY_HIGH;
461     } else if (priority.equalsIgnoreCase("low")
462         || priority.equalsIgnoreCase("5")
463         || priority.equalsIgnoreCase("Non-Urgent")) {
464       priorityAsShort = PRIORITY_LOW;
465     }
466     return priorityAsShort;
467   }
468
469   /**
470    * Checks whether the message contains plain text.
471    *
472    * @return true if the message contains plain text, false otherwise
473    */

474   public boolean isPlainText(
475   ) {
476       return this.bodyType.startsWith("text/plain");
477   }
478
479
480   /**
481    * Checks whether the message contains HTML text.
482    *
483    * @return true if the message contains HTML text, false otherwise
484    */

485   public boolean isHtmlText(
486   ) {
487       return this.bodyType.startsWith("text/html");
488   }
489
490
491   /**
492    * Checks whether the message contains binary attachments.
493    *
494    * @return true, if the message contains some binary attachments
495    */

496   public boolean containsAttachments(
497   ) {
498     return this.content.size() > 0;
499   }
500
501
502   /**
503    * Checks whether the message contains binary attachments.
504    *
505    * @return true, if the message contains some binary attachments
506    */

507   public boolean containsNestedMessage(
508   ) {
509     return this.containsNestedMessageAttachment;
510   }
511
512
513   /**
514    * Checks whether the message contains an openCRX identity.
515    *
516    * @return true if the message contains an openCRX identity, false otherwise
517    */

518   public boolean hasIdentity(
519   ) {
520       return !(this.messageIdentity == null || this.messageIdentity.length() == 0);
521   }
522
523
524   /**
525    * Returns a collection of the attachments or null if the message
526    * does not contain any.
527    *
528    * @return collection of the attachments or null otherwise
529    */

530   public Collection JavaDoc getContents(
531   ) {
532       return this.content.size() > 0
533           ? this.content
534           : null;
535   }
536
537   /**
538    * Returns a collection of the text attachments or null if the message
539    * does not contain any.
540    *
541    * @return collection of the text attachments or null otherwise
542    */

543   public Collection JavaDoc getTextContents(
544   ) {
545     ArrayList JavaDoc textContents = new ArrayList JavaDoc();
546     if(this.content.size() > 0) {
547       Iterator JavaDoc binContents = this.content.iterator();
548       while (binContents.hasNext()) {
549         MessageContent contentElem = (MessageContent) binContents.next();
550         if(contentElem.getContent() instanceof String JavaDoc) {
551           textContents.add(contentElem);
552         }
553       }
554     }
555     return textContents.size() > 0
556         ? textContents
557         : null;
558   }
559
560   /**
561    * Returns a collection of the binary attachments or null if the message
562    * does not contain any.
563    *
564    * @return collection of the binary attachments or null otherwise
565    */

566   public Collection JavaDoc getBinaryContents(
567   ) {
568     ArrayList JavaDoc binaryContents = new ArrayList JavaDoc();
569     if(this.content.size() > 0) {
570       Iterator JavaDoc binContents = this.content.iterator();
571       while (binContents.hasNext()) {
572         MessageContent contentElem = (MessageContent) binContents.next();
573         if(!(contentElem.getContent() instanceof String JavaDoc)) {
574           binaryContents.add(contentElem);
575         }
576       }
577     }
578     return binaryContents.size() > 0
579         ? binaryContents
580         : null;
581   }
582
583   /* (non-Javadoc)
584    * @see java.lang.Object#toString()
585    */

586   public String JavaDoc toString(
587   ) {
588     StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
589     buffer.append("send date='").append(getDate());
590     buffer.append("', from={'");
591     if(this.from == null) {
592       this.getFrom();
593     }
594     if(this.from != null) {
595       for (int i = 0; i < this.from.length; i++) {
596         buffer.append(this.from[i]).append("',");
597       }
598     }
599     else {
600       buffer.append("',");
601     }
602     buffer.append("}, to={'");
603     if(this.to == null) {
604       this.getRecipients(Message.RecipientType.TO);
605     }
606     if(this.to != null) {
607       for (int i = 0; i < this.to.length; i++) {
608         buffer.append(this.to[i]).append("',");
609       }
610     }
611     else {
612       buffer.append("',");
613     }
614     buffer.append("}, cc={'");
615     if(this.cc == null) {
616       this.getRecipients(Message.RecipientType.CC);
617     }
618     if(this.cc != null) {
619       for (int i = 0; i < this.cc.length; i++) {
620         buffer.append(this.cc[i]).append("',");
621       }
622     }
623     buffer.append("}, bcc={'");
624     if(this.bcc == null) {
625       this.getRecipients(Message.RecipientType.BCC);
626     }
627     if(this.bcc != null) {
628       for (int i = 0; i < this.bcc.length; i++) {
629         buffer.append(this.bcc[i]).append("',");
630       }
631     }
632     else {
633       buffer.append("',");
634     }
635     buffer.append("}', messageId='").append(this.getMessageID());
636     buffer.append("', subject='").append(this.getSubject());
637     buffer.append("', priority='").append(this.getPriority());
638     buffer.append("', body='").append(this.getBody()).append("'");
639     if(this.containsAttachments()) {
640       Iterator JavaDoc contents = this.content.iterator();
641       while(contents.hasNext()) {
642         MessageContent contentElem = (MessageContent) contents.next();
643         buffer.append(" [included content element '" + contentElem.toString() + "' included.] ");
644       }
645     }
646 // buffer.append("', header lines='").append(getAllHeaderLinesAsString()).append("'");
647
return buffer.toString();
648   }
649
650   /**
651    * @param headerAddresses
652    * @throws AddressException
653    */

654   private String JavaDoc[] getAddresses(
655       Address JavaDoc[] headerAddresses
656   ) throws AddressException JavaDoc {
657     String JavaDoc addresses[] = null;
658     if (headerAddresses != null && headerAddresses.length > 0) {
659       addresses = new String JavaDoc[headerAddresses.length];
660       for (int i = 0; i < headerAddresses.length; i++) {
661         if (headerAddresses[0] instanceof InternetAddress JavaDoc) {
662           addresses[i] = ((InternetAddress JavaDoc)headerAddresses[i]).getAddress();
663         } else {
664           InternetAddress JavaDoc temp = new InternetAddress JavaDoc(headerAddresses[i].toString());
665           addresses[i] = temp.getAddress();
666         }
667       }
668     } else {
669       addresses = new String JavaDoc[]{UNSPECIFIED_ADDRESS};
670     }
671     return addresses;
672   }
673
674   /**
675    * @param mailPart
676    */

677   private void parsePart(
678       MimeBodyPart JavaDoc part
679   ) {
680     try {
681       String JavaDoc disposition = part.getDisposition();
682       if ( disposition == null ) {
683         if (part.isMimeType("text/plain") || part.isMimeType("text/html")) {
684           if (this.messageBody == null) {
685             this.messageBody = (String JavaDoc)part.getContent();
686             this.bodyType = part.getContentType();
687           }
688           else {
689             MessageContent cont = new MessageContent(part.getContentID(), part.getContentType(), part.getContent());
690             this.content.add(cont);
691           }
692         }
693       }
694       else if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) ) {
695         if(AppLog.isTraceOn()) {
696           AppLog.trace("Reading Attachment for message " + getMessageID()
697               + ", (type='" + part.getContentType() + "'");
698         }
699         Object JavaDoc partContent = part.getContent();
700         InputStream JavaDoc is = null;
701         // if it is a wrapped message, try to create a SimpleMimeMessage
702
// and cache it.
703
if (partContent instanceof MimeMessage JavaDoc) {
704 // ByteArrayOutputStream bos = new ByteArrayOutputStream();
705
// ((MimeMessage)partContent).writeTo(bos);
706
// MessageContent cont = new MessageContent(part.getFileName(), part.getContentType(), bos.toByteArray());
707
SimpleMimeMessage nestedMsg = new SimpleMimeMessage((MimeMessage JavaDoc)partContent, true);
708           MessageContent cont = new MessageContent(part.getFileName(), part.getContentType(), nestedMsg);
709           content.add(cont);
710           // update the flag for easier checks
711
containsNestedMessageAttachment = true;
712           if(AppLog.isTraceOn()) {
713             AppLog.trace("attached MimeMessage imported '" + part.getFileName() + "'");
714           }
715         }
716         else if (partContent instanceof MimeMultipart JavaDoc) {
717           MimeMultipart JavaDoc multipart = (MimeMultipart JavaDoc)partContent;
718           for ( int i = 0; i < multipart.getCount(); i++ ) {
719             parsePart((MimeBodyPart JavaDoc)multipart.getBodyPart(i));
720           }
721         }
722         else {
723           if (partContent instanceof InputStream JavaDoc) {
724             is = (InputStream JavaDoc) partContent;
725           }
726           else {
727             is = part.getInputStream();
728           }
729           ByteArrayOutputStream JavaDoc bos = new ByteArrayOutputStream JavaDoc();
730           int readByte = is.read();
731           while (readByte != -1) {
732             bos.write(readByte);
733             readByte = is.read();
734           }
735           MessageContent cont = new MessageContent(part.getFileName(), part.getContentType(), bos.toByteArray());
736           content.add(cont);
737           if(AppLog.isTraceOn()) {
738             AppLog.trace("attachment of type '" + part.getContentType()
739               + "', filename '" + part.getFileName() + "' read");
740           }
741         }
742       }
743       else {
744         // Should not occur: either an attachment, inlined part or only
745
// a text based body is possible
746
AppLog.warning("Unsupported message part for message " + getMessageID());
747       }
748     } catch (IOException JavaDoc e) {
749       AppLog.warning("Could not read message content part " + getMessageID());
750       ServiceException e0 = new ServiceException(e);
751       AppLog.warning(e0.getMessage(), e0.getCause(), 1);
752     } catch (MessagingException JavaDoc e) {
753       AppLog.warning("Could not read message content part" + getMessageID());
754       ServiceException e0 = new ServiceException(e);
755       AppLog.warning(e0.getMessage(), e0.getCause(), 1);
756     }
757   }
758   
759   /**
760    * Extracts the recipients of the given type of the message and cache it locally.
761    *
762    * @param type the type for which the addresses are needed, i.e. either
763    * "To", "Cc" or "Bcc"
764    * @return the recipients' email addresses
765    */

766   private String JavaDoc[] getRecipientsByType(
767       Message.RecipientType JavaDoc type
768   ) {
769     String JavaDoc recipients[] = null;
770     try {
771       // Get the messages' recipients
772
Address JavaDoc headerToAddresses[] = this.mimeMsg.getRecipients(type);
773       recipients = getAddresses(headerToAddresses);
774     } catch (MessagingException JavaDoc e) {
775       AppLog.warning("Could not extract the addresses of message " + getMessageID() +
776           " of type '" + type.toString() + "'");
777       ServiceException e0 = new ServiceException(e);
778       AppLog.warning(e0.getMessage(), e0.getCause(), 1);
779     }
780     return recipients;
781   }
782
783   //-------------------------------------------------------------------------
784
public void markAsDeleted(
785   ) {
786       try {
787           this.mimeMsg.setFlag(
788               Flags.Flag.DELETED,
789               true
790           );
791       }
792       catch(MessagingException JavaDoc e) {}
793   }
794   
795   // -----------------------------------------------------------------------
796
// Members
797
// -----------------------------------------------------------------------
798
public static final String JavaDoc OPENCRX_MESSAGE_ID = "openCRX:MsgID:";
799   public static final String JavaDoc OPENCRX_MESSAGE_IDENTITY = "X-openCrxMsgIdentity";
800   public static final String JavaDoc UNSPECIFIED_ADDRESS = "NO_ADDRESS_SPECIFIED";
801
802   public static final short PRIORITY_LOW = 1;
803   public static final short PRIORITY_NORMAL = 2;
804   public static final short PRIORITY_HIGH = 3;
805   public static final short PRIORITY_URGENT = 4;
806   public static final short PRIORITY_IMMEDIATE = 5;
807   
808   private final MimeMessage JavaDoc mimeMsg;
809
810   /* the openCRX identity */
811   private String JavaDoc messageIdentity = null;
812
813   /* the messageId */
814   private String JavaDoc messageId = null;
815
816   /* the subject of the message */
817   private String JavaDoc subject = null;
818
819   /* message body as string */
820   private String JavaDoc messageBody = null;
821   
822   private String JavaDoc bodyType = null;
823
824   /* parts of some binary type */
825   private List JavaDoc content = new ArrayList JavaDoc();
826
827   /* all header lines */
828   private String JavaDoc headerLines = null;
829   
830   /* addresses of recipients */
831   private String JavaDoc from[] = null;
832   private String JavaDoc to[] = null;
833   private String JavaDoc cc[] = null;
834   private String JavaDoc bcc[] = null;
835
836   /* indicates whether message contains nested message attachment */
837   private boolean containsNestedMessageAttachment = false;
838   
839 }
840
Popular Tags