KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > suberic > pooka > NewMessageInfo


1 package net.suberic.pooka;
2 import javax.mail.*;
3 import java.util.*;
4 import java.io.*;
5 import javax.activation.*;
6 import javax.mail.internet.*;
7
8 import net.suberic.pooka.crypto.*;
9 import net.suberic.crypto.*;
10 import net.suberic.pooka.gui.NewMessageCryptoInfo;
11
12 import java.security.Key JavaDoc;
13
14 /**
15  * A MessageInfo representing a new message.
16  */

17 public class NewMessageInfo extends MessageInfo {
18
19   // the full map of messages to be sent, if there are different versions
20
// of the message that go to different recipients.
21
Map mSendMessageMap = null;
22   // the default UserProfile for this Message, if there is one.
23
UserProfile mProfile = null;
24
25   /**
26    * Creates a NewMessageInfo to wrap the given Message.
27    */

28   public NewMessageInfo(Message newMessage) {
29     message = newMessage;
30     attachments = new AttachmentBundle();
31     attachmentsLoaded=true;
32   }
33
34   /**
35    * Sends the new message, using the given Profile, the given
36    * InternetHeaders, the given messageText, the given ContentType, and
37    * the attachments already set for this object.
38    */

39   public void sendMessage(UserProfile profile, InternetHeaders headers, NewMessageCryptoInfo cryptoInfo, String JavaDoc messageText, String JavaDoc messageContentType) throws MessagingException {
40
41     try {
42       net.suberic.pooka.gui.PookaUIFactory factory = Pooka.getUIFactory();
43
44       MimeMessage mMsg = (MimeMessage) message;
45
46       factory.showStatusMessage(Pooka.getProperty("info.sendMessage.settingHeaders", "Setting headers..."));
47
48       Enumeration individualHeaders = headers.getAllHeaders();
49       while(individualHeaders.hasMoreElements()) {
50         Header currentHeader = (Header) individualHeaders.nextElement();
51         mMsg.setHeader(currentHeader.getName(), currentHeader.getValue());
52       }
53
54       mMsg.setHeader("X-Mailer", Pooka.getProperty("Pooka.xmailer", "Pooka"));
55
56       if (Pooka.getProperty("Pooka.lineWrap", "").equalsIgnoreCase("true"))
57         messageText=net.suberic.pooka.MailUtilities.wrapText(messageText);
58
59       // move this to another thread now.
60

61       factory.showStatusMessage(Pooka.getProperty("info.sendMessage.changingThreads", "Sending to message thread..."));
62
63       final UserProfile sProfile = profile;
64       final MimeMessage sMimeMessage = mMsg;
65       final String JavaDoc sMessageText = messageText;
66       final String JavaDoc sMessageContentType = messageContentType;
67       final NewMessageCryptoInfo sCryptoInfo = cryptoInfo;
68
69       OutgoingMailServer mailServer = null;
70       if (profile != null)
71         mailServer = profile.getMailServer();
72
73       if (mailServer != null) {
74
75         final OutgoingMailServer sMailServer = mailServer;
76         mailServer.mailServerThread.addToQueue(new javax.swing.AbstractAction JavaDoc() {
77             public void actionPerformed(java.awt.event.ActionEvent JavaDoc ae) {
78               internal_sendMessage(sProfile, sMimeMessage, sMessageText, sMessageContentType, sCryptoInfo, sMailServer);
79             }
80           }, new java.awt.event.ActionEvent JavaDoc(this, 0, "message-send"));
81       } else {
82         // oh well.
83
internal_sendMessage(sProfile, sMimeMessage, sMessageText, sMessageContentType, sCryptoInfo, null);
84       }
85
86     } catch (MessagingException me) {
87       throw me;
88     } catch (Throwable JavaDoc t) {
89       String JavaDoc cause = t.getMessage();
90       if (cause == null)
91         cause = t.toString();
92
93       MessagingException me = new MessagingException(cause);
94       me.initCause(t);
95       throw me;
96     }
97   }
98
99   /**
100    * Does the part of message sending that should really not happen on
101    * the AWTEventThread.
102    */

103   private void internal_sendMessage(UserProfile profile, MimeMessage mMsg, String JavaDoc messageText, String JavaDoc messageContentType, NewMessageCryptoInfo cryptoInfo, OutgoingMailServer mailServer) {
104     net.suberic.pooka.gui.PookaUIFactory factory = Pooka.getUIFactory();
105
106     try {
107       factory.showStatusMessage(Pooka.getProperty("info.sendMessage.attachingKeys", "Attaching crypto keys (if any)..."));
108
109       // see if we need to add any keys.
110
List keyParts = cryptoInfo.createAttachedKeyParts();
111
112       factory.showStatusMessage(Pooka.getProperty("info.sendMessage.addingMessageText", "Parsing message text..."));
113       if (keyParts.size() > 0 || (attachments.getAttachments() != null && attachments.getAttachments().size() > 0)) {
114         MimeBodyPart mbp = new MimeBodyPart();
115         mbp.setContent(messageText, messageContentType);
116         MimeMultipart multipart = new MimeMultipart();
117         multipart.addBodyPart(mbp);
118
119         if (attachments.getAttachments() != null) {
120           // i should really use the text parsing code for this, but...
121
String JavaDoc attachmentMessage=Pooka.getProperty("info.sendMessage.addingAttachment.1", "Adding attachment ");
122           String JavaDoc ofMessage = Pooka.getProperty("info.sendMessage.addingAttachment.2", " of ");
123           int attachmentCount = attachments.getAttachments().size();
124           for (int i = 0; i < attachmentCount; i++) {
125             factory.showStatusMessage(attachmentMessage + i + ofMessage + attachmentCount);
126             Attachment currentAttachment = (Attachment) attachments.getAttachments().get(i);
127             if (currentAttachment instanceof MBPAttachment)
128               multipart.addBodyPart(((MBPAttachment) currentAttachment).getMimeBodyPart());
129             else {
130               MimeBodyPart attachmentMbp = new MimeBodyPart();
131               //attachmentMbp.setContent(currentAttachment.getContent(), currentAttachment.getMimeType().toString());
132

133               DataHandler dh = currentAttachment.getDataHandler();
134               attachmentMbp.setFileName(currentAttachment.getName());
135               attachmentMbp.setDescription(currentAttachment.getName());
136               attachmentMbp.setDataHandler( dh );
137               attachmentMbp.setHeader("Content-Type", currentAttachment.getMimeType().toString());
138
139               multipart.addBodyPart(attachmentMbp);
140             }
141           }
142         }
143
144         for (int i = 0; i < keyParts.size(); i++) {
145           multipart.addBodyPart((MimeBodyPart) keyParts.get(i));
146         }
147
148         factory.showStatusMessage(Pooka.getProperty("info.sendMessage.savingChangesToMessage", "Saving changes to message..."));
149         multipart.setSubType("mixed");
150         getMessage().setContent(multipart);
151         getMessage().saveChanges();
152       } else {
153         factory.showStatusMessage(Pooka.getProperty("info.sendMessage.savingChangesToMessage", "Saving changes to message..."));
154         getMessage().setContent(messageText, messageContentType);
155       }
156
157       getMessage().setSentDate(new java.util.Date JavaDoc(System.currentTimeMillis()));
158
159       // do encryption stuff, if necessary.
160

161       // sigh
162

163       factory.showStatusMessage(Pooka.getProperty("info.sendMessage.encryptMessage", "Handing encryption..."));
164
165       mSendMessageMap = cryptoInfo.createEncryptedMessages((MimeMessage) getMessage());
166
167       if (mSendMessageMap.keySet().size() < 1) {
168         throw new MessagingException("failed to send message--no encrypted or unencrypted messages created.");
169       }
170
171       if (mSendMessageMap.keySet().size() == 1) {
172         message = (Message) mSendMessageMap.keySet().iterator().next();
173       }
174
175       boolean sent = false;
176       if (mailServer != null) {
177         factory.showStatusMessage(Pooka.getProperty("info.sendMessage.sendingMessage", "Sending message to mailserver..."));
178         mailServer.sendMessage(this);
179         sent = true;
180       }
181
182       /*
183         if (! sent) {
184         if (profile != null) {
185         URLName urlName = profile.getSendMailURL();
186         String sendPrecommand = profile.getSendPrecommand();
187         factory.showStatusMessage(Pooka.getProperty("info.sendMessage.sendingMessage", "Sending message to mailserver..."));
188         Pooka.getMainPanel().getMailQueue().sendMessage(this, urlName, sendPrecommand);
189         sent = true;
190         }
191         }
192       */

193
194       if (! sent) {
195         throw new MessagingException(Pooka.getProperty("error.noSMTPServer", "Error sending Message: No mail server configured."));
196       }
197     } catch (MessagingException me) {
198       ((net.suberic.pooka.gui.NewMessageProxy)getMessageProxy()).sendFailed(null, me);
199     } catch (Throwable JavaDoc t) {
200       String JavaDoc cause = t.getMessage();
201       if (cause == null)
202         cause = t.toString();
203
204       MessagingException me = new MessagingException(cause);
205       me.initCause(t);
206       ((net.suberic.pooka.gui.NewMessageProxy)getMessageProxy()).sendFailed(mailServer, me);
207     }
208   }
209
210   /**
211    * Converts the given address line into an address line suitable for
212    * this NewMessageInfo. Specifically, this goes through each address
213    * in the list and adds the UserProfile's defaultDomain to each entry
214    * which doesn't have a domain already.
215    */

216   public String JavaDoc convertAddressLine(String JavaDoc oldLine, UserProfile p) throws javax.mail.internet.AddressException JavaDoc {
217     StringBuffer JavaDoc returnValue = new StringBuffer JavaDoc();
218     InternetAddress[] addresses = InternetAddress.parse(oldLine, false);
219     for (int i = 0; i < addresses.length; i++) {
220       String JavaDoc currentAddress = addresses[i].getAddress();
221       if (currentAddress.lastIndexOf('@') < 0) {
222         currentAddress = currentAddress + "@" + p.getDefaultDomain();
223         addresses[i].setAddress(currentAddress);
224       }
225
226       returnValue.append(addresses[i].toString());
227       if (i+1 < addresses.length)
228         returnValue.append(", ");
229     }
230
231     return returnValue.toString();
232   }
233
234   /**
235    * Saves the NewMessageInfo to the sentFolder associated with the
236    * given Profile, if any. Note that if there is a sent folder to
237    * save to, this method will likely just place an action in the
238    * queue.
239    *
240    * @return if there is a sent folder to save to.
241    */

242   public boolean saveToSentFolder(UserProfile profile) {
243     final FolderInfo sentFolder = profile.getSentFolder();
244     if (sentFolder != null) {
245       try {
246         final Message newMessage = new MimeMessage((MimeMessage) getMessage());
247
248         sentFolder.getFolderThread().addToQueue(new net.suberic.util.thread.ActionWrapper(new javax.swing.AbstractAction JavaDoc() {
249             public void actionPerformed(java.awt.event.ActionEvent JavaDoc actionEvent) {
250               net.suberic.pooka.gui.PookaUIFactory factory = Pooka.getUIFactory();
251
252               try {
253                 if (sentFolder.getFolder() == null) {
254                   factory.showStatusMessage(Pooka.getProperty("info.sendMessage.openingSentFolder", "Opening sent folder..."));
255                   sentFolder.openFolder(Folder.READ_WRITE);
256                 }
257
258                 if (sentFolder.getFolder() == null) {
259                   throw new MessagingException("failed to load sent folder " + sentFolder);
260                 }
261
262                 newMessage.setSentDate(java.util.Calendar.getInstance().getTime());
263                 factory.showStatusMessage(Pooka.getProperty("info.sendMessage.savingToSentFolder", "Saving message to sent folder..."));
264
265                 sentFolder.getFolder().appendMessages(new Message[] {newMessage});
266               } catch (MessagingException me) {
267                 me.printStackTrace();
268                 Pooka.getUIFactory().showError(Pooka.getProperty("Error.SaveFile.toSentFolder", "Error saving file to sent folder."), Pooka.getProperty("error.SaveFile.toSentFolder.title", "Error storing message."));
269               } finally {
270                 ((net.suberic.pooka.gui.NewMessageProxy)getMessageProxy()).sendSucceeded(false);
271               }
272             }
273           }, sentFolder.getFolderThread()), new java.awt.event.ActionEvent JavaDoc(this, 1, "message-send"));
274       } catch (MessagingException me) {
275         me.printStackTrace();
276         Pooka.getUIFactory().showError(Pooka.getProperty("Error.SaveFile.toSentFolder", "Error saving file to sent folder."), Pooka.getProperty("error.SaveFile.toSentFolder.title", "Error storing message."));
277
278       }
279       return true;
280     }
281
282     return false;
283   }
284
285   /**
286    * Adds an attachment to this message.
287    */

288   public void addAttachment(Attachment attachment) {
289     attachments.addAttachment(attachment, false);
290   }
291
292   /**
293    * Removes an attachment from this message.
294    */

295   public int removeAttachment(Attachment part) {
296     if (attachments != null) {
297       int index = attachments.getAttachments().indexOf(part);
298       attachments.removeAttachment(part);
299       return index;
300     }
301
302     return -1;
303   }
304
305   /**
306    * Attaches the given File to the message.
307    */

308   public void attachFile(File f) throws MessagingException {
309     attachFile(f, null);
310   }
311
312   /**
313    * Attaches the given File to the message using the given content type.
314    */

315   public void attachFile(File f, String JavaDoc contentType) throws MessagingException {
316     // borrowing liberally from ICEMail here.
317

318     UpdatableMBP mbp = new UpdatableMBP();
319
320     FileDataSource fds = new FileDataSource(f);
321
322     DataHandler dh = new DataHandler(fds);
323
324     mbp.setFileName(f.getName());
325
326     if (Pooka.getMimeTypesMap().getContentType(f).startsWith("text"))
327       mbp.setDisposition(Part.INLINE);
328     else
329       mbp.setDisposition(Part.ATTACHMENT);
330
331     mbp.setDescription(f.getName());
332
333     mbp.setDataHandler( dh );
334
335     if (contentType == null) {
336       String JavaDoc type = dh.getContentType();
337
338       mbp.setHeader("Content-Type", type);
339     } else {
340       mbp.setHeader("Content-Type", contentType);
341     }
342
343     mbp.updateMyHeaders();
344
345     addAttachment(new MBPAttachment(mbp));
346   }
347
348   /**
349    * Returns the given header on the wrapped Message.
350    */

351   public String JavaDoc getHeader(String JavaDoc headerName, String JavaDoc delimeter) throws MessagingException {
352     return ((MimeMessage)getMessage()).getHeader(headerName, delimeter);
353   }
354
355   /**
356    * Gets the text part of the wrapped message.
357    */

358   public String JavaDoc getTextPart(boolean showFullHeaders) {
359     try {
360       Object JavaDoc content = message.getContent();
361       if (content instanceof String JavaDoc)
362         return (String JavaDoc) content;
363       else if (content instanceof Multipart) {
364         AttachmentBundle bundle = MailUtilities.parseAttachments((Multipart) content);
365         return bundle.getTextPart(false, false, 10000, getTruncationMessage());
366       } else
367         return null;
368     } catch (java.io.IOException JavaDoc ioe) {
369       // since this is a NewMessageInfo, there really shouldn't be an
370
// IOException
371
return null;
372     } catch (MessagingException me) {
373       // since this is a NewMessageInfo, there really shouldn't be a
374
// MessagingException
375
return null;
376     }
377   }
378
379   /**
380    * Marks the message as a draft message and then saves it to the outbox
381    * folder given.
382    */

383   public void saveDraft(FolderInfo outboxFolder, UserProfile profile, InternetHeaders headers, String JavaDoc messageText, String JavaDoc messageContentType) throws MessagingException {
384     net.suberic.pooka.gui.PookaUIFactory factory = Pooka.getUIFactory();
385
386     MimeMessage mMsg = (MimeMessage) message;
387
388     factory.showStatusMessage(Pooka.getProperty("info.sendMessage.settingHeaders", "Setting headers..."));
389
390     Enumeration individualHeaders = headers.getAllHeaders();
391     while(individualHeaders.hasMoreElements()) {
392       Header currentHeader = (Header) individualHeaders.nextElement();
393       mMsg.setHeader(currentHeader.getName(), currentHeader.getValue());
394     }
395
396     if (Pooka.getProperty("Pooka.lineWrap", "").equalsIgnoreCase("true"))
397       messageText=net.suberic.pooka.MailUtilities.wrapText(messageText);
398
399     factory.showStatusMessage(Pooka.getProperty("info.sendMessage.addingMessageText", "Parsing message text..."));
400     if (attachments.getAttachments() != null && attachments.getAttachments().size() > 0) {
401       MimeBodyPart mbp = new MimeBodyPart();
402       mbp.setContent(messageText, messageContentType);
403       MimeMultipart multipart = new MimeMultipart();
404       multipart.addBodyPart(mbp);
405
406       // i should really use the text parsing code for this, but...
407
String JavaDoc attachmentMessage=Pooka.getProperty("info.sendMessage.addingAttachment.1", "Adding attachment ");
408       String JavaDoc ofMessage = Pooka.getProperty("info.sendMessage.addingAttachment.2", " of ");
409       int attachmentCount = attachments.getAttachments().size();
410       for (int i = 0; i < attachmentCount; i++) {
411         factory.showStatusMessage(attachmentMessage + i + ofMessage + attachmentCount);
412         multipart.addBodyPart(((MBPAttachment)attachments.getAttachments().elementAt(i)).getMimeBodyPart());
413       }
414
415       factory.showStatusMessage(Pooka.getProperty("info.sendMessage.savingChangesToMessage", "Saving changes to message..."));
416       multipart.setSubType("mixed");
417       getMessage().setContent(multipart);
418       getMessage().saveChanges();
419     } else {
420       factory.showStatusMessage(Pooka.getProperty("info.sendMessage.savingChangesToMessage", "Saving changes to message..."));
421       getMessage().setContent(messageText, messageContentType);
422     }
423
424     getMessage().setSentDate(new java.util.Date JavaDoc(System.currentTimeMillis()));
425
426     getMessage().setFlag(Flags.Flag.DRAFT, true);
427     outboxFolder.appendMessages(new MessageInfo[] { this });
428   }
429
430   /**
431    * The full map of Messages to be sent, which in turn map to the
432    * recipients they will go to. If there is no Address array as the
433    * value in the map, then the message goes out to all recipients in
434    * the headers.
435    */

436   public Map getSendMessageMap() {
437     return mSendMessageMap;
438   }
439
440   /**
441    * The full map of Messages to be sent, which in turn map to the
442    * recipients they will go to. If there is no Address array as the
443    * value in the map, then the message goes out to all recipients in
444    * the headers.
445    */

446   void setSendMessageMap(Map pSendMessageMap) {
447     mSendMessageMap = pSendMessageMap;
448   }
449
450   /**
451    * As specified by interface net.suberic.pooka.UserProfileContainer.
452    *
453    * If
454    */

455   public UserProfile getDefaultProfile() {
456     if (mProfile == null)
457       return super.getDefaultProfile();
458     else
459       return mProfile;
460   }
461
462   /**
463    * Sets the default UserProfile for this NewMessageInfo. Note that
464    * this UserProfile is not necessarily the one that the message will be
465    * sent using; rather, it's the one that will be selected in the UI
466    * by default.
467    */

468   public void setDefaultProfile(UserProfile pProfile) {
469     mProfile = pProfile;
470   }
471
472
473 }
474
Popular Tags