KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > scioworks > imap > business > beans > IWMessageImpl


1 /* -----------------------------------------------------------------------------
2  * Copyright (c) 2001, Low Kin Onn
3  * All rights reserved.
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  *
8  * Redistributions of source code must retain the above copyright notice, this
9  * list of conditions and the following disclaimer.
10  *
11  * Redistributions in binary form must reproduce the above copyright notice,
12  * this list of conditions and the following disclaimer in the documentation
13  * and/or other materials provided with the distribution.
14  *
15  * Neither name of the Scioworks Pte. Ltd. nor the names of its contributors
16  * may beused to endorse or promote products derived from this software without
17  * specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
23  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  *
30  * -----------------------------------------------------------------------------
31  */

32
33 package scioworks.imap.business.beans;
34
35 import java.io.*;
36 import java.util.Date JavaDoc;
37 import java.util.Vector JavaDoc;
38 import java.util.StringTokenizer JavaDoc;
39
40 import javax.mail.*;
41 import javax.mail.internet.*;
42 import javax.activation.*;
43
44
45 import scioworks.imap.spec.*;
46
47
48 import scioworks.imap.business.util.MessagingUtilImpl;
49
50 import scioworks.imap.spec.beans.*;
51 import scioworks.imap.spec.ImapWebException;
52 import scioworks.imap.spec.ImapWebConstant;
53
54 public class IWMessageImpl extends PublicObject implements IWMessage {
55
56   int fLineWidth;
57   static final String JavaDoc fLineSeparator = "\n";
58
59   public IWMessageImpl() {
60     super();
61     fLineWidth = 72;
62   }
63
64   public IWMessageImpl(int lineWidth) {
65     super();
66     this.fLineWidth = lineWidth;
67   }
68
69   /**
70    * This method will extract the message body from a message
71    */

72   public String JavaDoc getMessageBody(Message mesg)
73       throws ImapWebException {
74
75     try {
76       String JavaDoc msg_body = new String JavaDoc();
77       Object JavaDoc o = mesg.getContent();
78
79       //Keep on looping until we find a String part
80
while (!(o instanceof String JavaDoc)){
81         //we assume this is a multipart
82
Multipart mp = (Multipart) o;
83         o = mp.getBodyPart(0).getContent();
84       }
85
86       //if here that means we found a String part
87
return (String JavaDoc) o;
88
89     } catch (MessagingException e) {
90       throw new ImapWebException("Error getting message body.", e);
91
92     } catch (IOException e) {
93       throw new ImapWebException("Error getting message body.", e);
94     }
95
96   }
97
98 /*
99   private void processPart(Multipart forwardMultipart, Part part)
100       throws MessagingException, IOException {
101
102     //if this is a multipart, recursively call processPart
103     if (part.isMimeType("multipart/*")){
104       Multipart mp = ((Multipart)part.getContent());
105       int count = mp.getCount();
106       for (int i = 0; i < count; i++){
107         processPart(forwardMultipart, mp.getBodyPart(i));
108      }
109
110     //if this is a rfc822 message, recursively call processPart
111     } else if (part.isMimeType("message/rfc822")) {
112       processPart(forwardMultipart, (Part) part.getContent());
113
114     //this is a singular part that can be processed
115     } else {
116       Object obj = part.getContent();
117       if (obj instanceof String) {
118             MimeBodyPart mbp = new MimeBodyPart();
119             mbp.setDisposition(MimeBodyPart.ATTACHMENT);
120             mbp.setText((String) obj);
121             forwardMultipart.addBodyPart(mbp);
122       } else {
123         forwardMultipart.addBodyPart((BodyPart) part);
124       }
125     }
126   }
127 */

128
129
130   /**
131    * Return the message given by folder and uid. Calling method is responsible
132    * for creating and closing the folder object.
133    */

134   public Message getMessage(Folder folder, long uid)
135       throws ImapWebException {
136     try {
137
138       UIDFolder ufolder = (UIDFolder) folder;
139
140       // open the folder for read and write
141
folder.open(Folder.READ_WRITE);
142
143       // get the message
144
Message msg = ufolder.getMessageByUID(uid);
145
146       // mark the msg as seen
147
msg.setFlag(Flags.Flag.SEEN, true);
148
149       return msg;
150
151     } catch (MessagingException e) {
152       throw new ImapWebException("Error getting message.", e);
153     }
154   }
155
156   /**
157    * Return a <b>copy</b> of the message given by folder name and uid.
158    * Closing of folder is handled internally by this method.
159    */

160   public Message getMessage(Store imapStore,
161       String JavaDoc folderName, long uid) throws ImapWebException {
162     try {
163
164       Folder folder = imapStore.getFolder(folderName);
165
166       UIDFolder ufolder = (UIDFolder) folder;
167
168       // open the folder for read and write
169
folder.open(Folder.READ_WRITE);
170
171       // get the message
172
MimeMessage msg = new MimeMessage((MimeMessage) ufolder.getMessageByUID(uid));
173
174       // mark the msg as seen
175
msg.setFlag(Flags.Flag.SEEN, true);
176
177       folder.close(false);
178
179       return msg;
180
181     } catch (MessagingException e) {
182       throw new ImapWebException("Error getting message.", e);
183     }
184   }
185
186   public Message forwardMessage(Session imapSession, Store imapStore,
187       String JavaDoc folderName, long uid, boolean isInline)
188       throws ImapWebException {
189     try {
190       Folder folder = imapStore.getFolder(folderName);
191
192       // open the folder for read
193
folder.open(Folder.READ_ONLY);
194
195       UIDFolder ufolder = (UIDFolder) folder;
196
197       // get the message
198
Message origMsg = ufolder.getMessageByUID(uid);
199
200       // create a reply object
201
MimeMessage forwardMsg = new MimeMessage(imapSession);
202
203       if (origMsg.getSubject().startsWith("Fwd:")) {
204         forwardMsg.setSubject(origMsg.getSubject());
205       } else {
206         forwardMsg.setSubject("Fwd: " + origMsg.getSubject());
207       }
208
209       if (isInline) {
210         MessagingUtilImpl messagingUtilImpl = new MessagingUtilImpl();
211    
212         forwardMsg.setText(fLineSeparator +
213                          "--- " + origMsg.getFrom()[0].toString() + " wrote:" +
214                          fLineSeparator +
215                            messagingUtilImpl.formatMsgBody(this.getMessageBody(origMsg), fLineWidth ));
216       
217       
218       } else {
219         forwardMsg.setText(fLineSeparator + "--- Forwarded message attached");
220       }
221
222       // close the folder
223
folder.close(false);
224
225       return forwardMsg;
226
227     } catch (MessagingException e) {
228       throw new ImapWebException("Error setting message forward.", e);
229     }
230
231   }
232
233   public Message replyMessage(Session imapSession, Store imapStore,
234       String JavaDoc folderName, long uid, boolean replyAll, boolean quoteOrig)
235       throws ImapWebException {
236     try {
237       Folder folder = imapStore.getFolder(folderName);
238
239       // open the folder for read
240
folder.open(Folder.READ_ONLY);
241
242       UIDFolder ufolder = (UIDFolder) folder;
243
244       // get the message
245
Message origMsg = ufolder.getMessageByUID(uid);
246
247       // create a reply object
248
Message replyMsg = origMsg.reply(replyAll);
249
250       if (quoteOrig) {
251          MessagingUtilImpl messagingUtilImpl = new MessagingUtilImpl();
252         replyMsg.setText("--- " + origMsg.getFrom()[0].toString() + " wrote:" + fLineSeparator +
253                          messagingUtilImpl.formatMsgBody(this.getMessageBody(origMsg), fLineWidth ));
254       }
255
256       // close the folder
257
folder.close(false);
258
259       return replyMsg;
260
261     } catch (MessagingException e) {
262       throw new ImapWebException("Error setting message reply.", e);
263     }
264   }
265
266
267   /**
268    * Creates and send a message as per the given parameter.
269    * Does <b>not</b> handle attachements
270    */

271   public void sendMessage(Store imapStore, Session imapSession, URLName imapURL,
272       String JavaDoc imapDomain,
273       String JavaDoc to, String JavaDoc subject, String JavaDoc cc, String JavaDoc bcc, String JavaDoc message,
274       Vector JavaDoc attachments, boolean isInline, boolean saveCopy,
275       boolean isForwardAttach, String JavaDoc origFolderName, long origUid)
276       throws ImapWebException {
277
278     Message msg = new MimeMessage(imapSession);
279
280     InternetAddress[] toAddrs = null;
281     InternetAddress[] ccAddrs = null;
282     InternetAddress[] bccAddrs = null;
283
284     try {
285
286         if (!to.equals("")) {
287         toAddrs = InternetAddress.parse(to, false);
288         msg.setRecipients(Message.RecipientType.TO, toAddrs);
289         } else {
290         throw new MessagingException("No \"To\" address specified");
291         }
292
293         if (!cc.equals("")) {
294         ccAddrs = InternetAddress.parse(cc, false);
295         msg.setRecipients(Message.RecipientType.CC, ccAddrs);
296         }
297
298       if (!bcc.equals("")) {
299         bccAddrs = InternetAddress.parse(bcc, false);
300         msg.setRecipients(Message.RecipientType.BCC, bccAddrs);
301       }
302
303         if (!subject.equals("")) {
304         msg.setSubject(subject);
305         }
306
307         msg.setFrom(new InternetAddress(imapURL.getUsername() + "@" +
308                                       imapDomain));
309
310       // sent the sent date
311
msg.setSentDate(new Date JavaDoc());
312
313       if (message.equals("")) {
314         message = " ";
315       }
316
317       if ((attachments.size() == 0) && !isForwardAttach) {
318         // no attachments
319
msg.setText(message);
320
321       } else {
322
323         // multiparts
324

325         // create the Multipart for adding parts to it
326
Multipart mp = new MimeMultipart();
327
328         // create and fill the first message part
329
MimeBodyPart mbp1 = new MimeBodyPart();
330         mbp1.setDisposition(MimeBodyPart.INLINE);
331         mbp1.setText(message);
332         mp.addBodyPart(mbp1);
333
334         FileRecord fr;
335         for (int i=0; i<attachments.size(); i++) {
336           fr = (FileRecord) attachments.elementAt(i);
337           try {
338
339             MimeBodyPart mbp2 = new MimeBodyPart();
340             FileDataSource fds = new FileDataSource(fr.getTmpFilename());
341             mbp2.setDataHandler(new DataHandler(fds));
342             if (isInline) {
343               mbp2.setDisposition(MimeBodyPart.INLINE);
344             } else {
345               mbp2.setDisposition(MimeBodyPart.ATTACHMENT);
346             }
347             mbp2.setFileName(fr.getFilename());
348
349             mp.addBodyPart(mbp2);
350
351           } catch (MessagingException e) {
352             System.err.println("Error attaching file: "+fr.getTmpFilename());
353             e.printStackTrace();
354           }
355         }
356
357         if (isForwardAttach) {
358
359           try {
360             Folder origFolder = imapStore.getFolder(origFolderName);
361
362             // open the folder for read
363
origFolder.open(Folder.READ_ONLY);
364
365             UIDFolder ufolder = (UIDFolder) origFolder;
366
367             // create a copy of the message
368
MimeMessage origMessage = new MimeMessage((MimeMessage) ufolder.getMessageByUID(origUid));
369
370             // close the folder
371
origFolder.close(false);
372
373             BodyPart bodypart = new MimeBodyPart();
374             bodypart.setContent(origMessage, "message/rfc822");
375             mp.addBodyPart(bodypart);
376
377 // processPart(mp, origMessage);
378

379           } catch (MessagingException e) {
380             System.err.println("Error attaching original message.");
381             e.printStackTrace();
382           }
383
384         }
385
386         // add the Multipart to the message
387
msg.setContent(mp);
388
389       }
390
391         Transport.send(msg);
392
393       if (saveCopy) {
394         Folder sentFolder = imapStore.getFolder(ImapWebConstant.singleton().folderSent());
395         // check if sent folder exists
396
if (!sentFolder.exists()) {
397           // not exists, create a new one
398
sentFolder.create(Folder.HOLDS_MESSAGES);
399         }
400
401         MimeMessage[] messages = new MimeMessage[1];
402         messages[0] = (MimeMessage)msg;
403         sentFolder.appendMessages(messages);
404       }
405
406     } catch (AddressException e) {
407       throw new ImapWebException("Error creating email.", e);
408
409     } catch (MessagingException e) {
410       throw new ImapWebException("Error creating email.", e);
411     }
412   }
413
414   public void deleteMessage(Store imapStore,
415       String JavaDoc folderName, long[] uidArr) throws ImapWebException {
416
417     try {
418       // get the trash folder
419
Folder trashFolder = imapStore.getFolder(ImapWebConstant.singleton().folderTrash());
420
421       if (!trashFolder.exists()) {
422         // trash folder not exist, create one
423
trashFolder.create(Folder.HOLDS_MESSAGES);
424       }
425
426       // get the folder that contains the messages to be deleted
427
Folder folder = imapStore.getFolder(folderName);
428
429       UIDFolder ufolder = (UIDFolder) folder;
430
431       // open the folder for read and write
432
folder.open(Folder.READ_WRITE);
433
434       // get the messages to be deleted
435
Message[] messages = ufolder.getMessagesByUID(uidArr);
436
437       // Check if this is the trash folder
438
if (!folderName.equals(ImapWebConstant.singleton().folderTrash())) {
439         // this not the trash folder, copy the messages to trash
440
folder.copyMessages(messages, trashFolder);
441       }
442
443       // mark the messages for expunge
444
for (int i=0; i<messages.length; i++) {
445         messages[i].setFlag(Flags.Flag.DELETED, true);
446       }
447
448       // close the folder and expunge the deleted messages
449
folder.close(true);
450
451     } catch (MessagingException e) {
452       throw new ImapWebException("Error deleting messages.", e);
453     }
454   }
455
456   public void moveMessage(Store imapStore, String JavaDoc folderName,
457       long[] uidArr, String JavaDoc targetFolderName) throws ImapWebException {
458
459     try {
460       // get the folder that contains the messages to be deleted
461
Folder folder = imapStore.getFolder(folderName);
462
463       UIDFolder ufolder = (UIDFolder) folder;
464
465       // open the folder for read and write
466
folder.open(Folder.READ_WRITE);
467
468       // get the messages to be deleted
469
Message[] messages = ufolder.getMessagesByUID(uidArr);
470
471       // get the target folder
472
Folder targetFolder = imapStore.getFolder(targetFolderName);
473
474       if (!targetFolder.exists()) {
475         // target folder not exist, create one
476
targetFolder.create(Folder.HOLDS_MESSAGES);
477       }
478
479       // copy to the target folder
480
folder.copyMessages(messages, targetFolder);
481
482       // mark the messages for expunge
483
for (int i=0; i<messages.length; i++) {
484         messages[i].setFlag(Flags.Flag.DELETED, true);
485       }
486
487       // close the folder and expunge the moved messages
488
folder.close(true);
489
490     } catch (MessagingException e) {
491       throw new ImapWebException("Error deleting messages.", e);
492     }
493   }
494
495
496   public Part getMessagePart(Session imapSession, Store imapStore,
497       String JavaDoc folderName, long uid, String JavaDoc partIdList) throws ImapWebException {
498     try {
499
500       Folder folder = imapStore.getFolder(folderName);
501
502       UIDFolder ufolder = (UIDFolder) folder;
503
504       // open the folder for read and write
505
folder.open(Folder.READ_ONLY);
506
507       // get the message
508
MimeMessage msg = new MimeMessage((MimeMessage) ufolder.getMessageByUID(uid));
509
510       folder.close(false);
511
512       StringTokenizer JavaDoc strtok = new StringTokenizer JavaDoc(partIdList, ".");
513       String JavaDoc partId;
514       Part part = msg;
515       while (strtok.hasMoreTokens()) {
516         partId = strtok.nextToken();
517         if (part.isMimeType("multipart/*")) {
518           part = ((Multipart)part.getContent()).getBodyPart(Integer.parseInt(partId));
519        } else if (part.isMimeType("message/rfc822")) {
520           MimeMessage mm = (MimeMessage) part.getContent();
521           part = ((Multipart)mm.getContent()).getBodyPart(Integer.parseInt(partId));
522        }
523
524       }
525
526       return part;
527
528     } catch (IOException e) {
529       throw new ImapWebException("Error getting part.", e);
530
531     } catch (MessagingException e) {
532       throw new ImapWebException("Error getting part.", e);
533     }
534   }
535
536   public Vector JavaDoc getFolderNames(Store imapStore, String JavaDoc currentFolder)
537       throws ImapWebException {
538
539     Vector JavaDoc res = new Vector JavaDoc();
540     try {
541       Folder[] folders = imapStore.getDefaultFolder().list();
542       String JavaDoc fname;
543       for (int i=0; i<folders.length; i++) {
544         if (folders[i].getName().equals(currentFolder) ||
545             folders[i].getName().equals(ImapWebConstant.singleton().folderTrash()) ||
546             folders[i].getName().equals(ImapWebConstant.singleton().folderSent()) )
547         {
548           continue;
549         } else {
550           res.addElement(folders[i].getName());
551         }
552       }
553     } catch (MessagingException e) {
554       throw new ImapWebException("Error getting folder names.", e);
555     }
556     return res;
557   }
558
559   public void createFolder(Store imapStore, String JavaDoc name)
560       throws ImapWebException {
561     try {
562       // get the current folder
563
Folder folder = imapStore.getFolder(name);
564
565       if (folder.exists()) {
566         // target folder exists
567
throw new ImapWebException("A folder with this name already exists.");
568
569       } else {
570         // target folder not exist, create one
571
folder.create(Folder.HOLDS_MESSAGES);
572       }
573     } catch (MessagingException e) {
574       throw new ImapWebException("Error creating new folder." , e);
575     }
576   }
577
578   public void renameFolder(Store imapStore, String JavaDoc folderName, String JavaDoc name)
579       throws ImapWebException {
580     try {
581       // get the current folder
582
Folder folder = imapStore.getFolder(folderName);
583
584       // get the target folder
585
Folder targetFolder = imapStore.getFolder(name);
586
587       if (!targetFolder.exists()) {
588         // target folder not exist, create one
589
targetFolder.create(Folder.HOLDS_MESSAGES);
590       }
591
592       // rename to the target foldr
593
folder.renameTo(targetFolder);
594
595     } catch (MessagingException e) {
596       throw new ImapWebException("Error creating new folder." , e);
597     }
598   }
599
600   public void removeFolder(Store imapStore, String JavaDoc folderName)
601       throws ImapWebException {
602     try {
603       // get the current folder
604
Folder folder = imapStore.getFolder(folderName);
605
606       if (folder.getMessageCount() == 0) {
607         // empty folder, can remove
608
folder.delete(false);
609
610       } else {
611         // not empty, throw error
612
throw new ImapWebException("Folders must be empty before it can be removed.");
613       }
614
615     } catch (MessagingException e) {
616       throw new ImapWebException("Error creating new folder." , e);
617     }
618   }
619
620 }
Popular Tags