KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > suberic > pooka > gui > NewMessageProxy


1 package net.suberic.pooka.gui;
2 import javax.mail.*;
3 import javax.mail.internet.*;
4 import javax.swing.*;
5 import javax.activation.*;
6 import java.util.Hashtable JavaDoc;
7 import java.util.Vector JavaDoc;
8 import net.suberic.pooka.*;
9 import java.awt.event.ActionEvent JavaDoc;
10 import java.io.*;
11
12 import net.suberic.pooka.crypto.*;
13 import net.suberic.pooka.gui.crypto.*;
14
15 /**
16  * This class represents a new message that is being written.
17  */

18 public class NewMessageProxy extends MessageProxy {
19   Hashtable JavaDoc commands;
20
21   NewMessageCryptoInfo mCryptoInfo = null;
22
23   private static Vector JavaDoc allUnsentProxies = new Vector JavaDoc();
24
25   boolean sendLock = false;
26
27   public NewMessageProxy(NewMessageInfo newMessage) {
28     messageInfo = newMessage;
29     messageInfo.setMessageProxy(this);
30
31     mCryptoInfo = new NewMessageCryptoInfo(newMessage);
32
33     commands = new Hashtable JavaDoc();
34
35     Action[] actions = getActions();
36     if (actions != null) {
37       for (int i = 0; i < actions.length; i++) {
38         Action a = actions[i];
39         commands.put(a.getValue(Action.NAME), a);
40       }
41     }
42
43     allUnsentProxies.add(this);
44
45   }
46
47   public void openWindow() {
48     // shouldn't have to open window.
49
}
50
51   public void moveMessage(Folder targetFolder) {
52     // shouldn't have to. might want to implement this to move a message
53
// to drafts, though.
54
}
55
56   /**
57    * This sends the Message associated with this MessageProxy.
58    *
59    * If this MessageProxy has a MessageUI associated with it, it
60    * will try to load the information from it, and then send the message.
61    * Otherwise, it will just try sending the message as-is.
62    *
63    * If the Message.sendImmediately property is set, then the method will
64    * also pop up and error window if there are any problems sending the
65    * queued messages.
66    *
67    * If there is a MessageUI associated with this Proxy, and either
68    * there are no errors sending the message, or the Message is just added
69    * to the Queue and not sent yet, the Window will also be closed.
70    *
71    */

72   public void send() {
73     // thread: AwtEvent
74

75     synchronized(this) {
76       if (sendLock) {
77         Pooka.getUIFactory().showStatusMessage(Pooka.getProperty("info.sendMessage.alreadySendingMessage", "Already sending message."));
78         return;
79       } else
80         sendLock = true;
81     }
82
83     try {
84       if (getNewMessageUI() != null) {
85         getNewMessageUI().setBusy(true);
86         UserProfile profile = getNewMessageUI().getSelectedProfile();
87         InternetHeaders headers = getNewMessageUI().getMessageHeaders();
88
89         String JavaDoc messageText = getNewMessageUI().getMessageText();
90
91         String JavaDoc messageContentType = getNewMessageUI().getMessageContentType();
92
93         if (getCryptoInfo().updateRecipientInfos(profile, headers)) {
94           getNewMessageInfo().sendMessage(profile, headers, getCryptoInfo(), messageText, messageContentType);
95         }
96       }
97     } catch (MessagingException me) {
98       sendLock=false;
99       getMessageUI().showError(Pooka.getProperty("Error.sendingMessage", "Error sending message: "), me);
100       getNewMessageUI().setBusy(false);
101     }
102   }
103
104   /**
105    * Called when the send succeeds.
106    */

107   public void sendSucceeded(boolean pSaveToSentFolder) {
108     final NewMessageUI nmui = getNewMessageUI();
109     if (nmui != null) {
110       boolean closeDialog = true;
111
112       if (pSaveToSentFolder) {
113         // only close the dialog now if we don't have a sent folder to
114
// save to.
115
closeDialog = ! getNewMessageInfo().saveToSentFolder(getNewMessageUI().getSelectedProfile());
116       }
117
118       // if not saving to a sent folder, close the dialog.
119
if ((! pSaveToSentFolder) || closeDialog) {
120         Runnable JavaDoc runMe = new Runnable JavaDoc() {
121             public void run() {
122               Pooka.getUIFactory().clearStatus();
123               nmui.setBusy(false);
124               nmui.setModified(false);
125               nmui.closeMessageUI();
126             }
127           };
128         SwingUtilities.invokeLater(runMe);
129       }
130     }
131
132   }
133
134   /**
135    * Called when the send fails.
136    */

137   public void sendFailed(OutgoingMailServer pMailServer, Exception JavaDoc e) {
138     sendLock=false;
139     Pooka.getUIFactory().clearStatus();
140     final OutgoingMailServer mailServer = pMailServer;
141     final Exception JavaDoc me = e;
142     final NewMessageUI nmui = getNewMessageUI();
143     if (nmui != null) {
144       Runnable JavaDoc runMe = new Runnable JavaDoc() {
145           public void run() {
146             if (me instanceof MessagingException) {
147               if (mailServer != null) {
148                 SendFailedDialog sfd = getNewMessageUI().showSendFailedDialog(mailServer, (MessagingException) me);
149                 if (sfd.resendMessage()) {
150                   OutgoingMailServer newServer = sfd.getMailServer();
151                   if (newServer != null) {
152                     String JavaDoc action = sfd.getMailServerAction();
153                     UserProfile profile = getNewMessageUI().getSelectedProfile();
154                     if (action == SendFailedDialog.S_SESSION_DEFAULT) {
155                       profile.setTemporaryMailServer(newServer);
156                     } else if (action == SendFailedDialog.S_CHANGE_DEFAULT) {
157                       Pooka.setProperty(profile.getUserProperty() + ".mailServer", newServer.getItemID());
158                     }
159                     newServer.sendMessage(getNewMessageInfo());
160                   }
161                 } else if (sfd.getSaveToOutbox()) {
162                   try {
163                     mailServer.saveToOutbox(getNewMessageInfo());
164                   } catch (MessagingException outboxException) {
165                     getMessageUI().showError(Pooka.getProperty("error.MessageUI.sendFailed", "Failed to send Message.") + "\n" + outboxException.getMessage());
166                   }
167                 }
168               } else {
169                 getMessageUI().showError(Pooka.getProperty("error.MessageUI.sendFailed", "Failed to send Message.") + "\n" + me.getMessage());
170                 me.printStackTrace(System.out);
171               }
172             } else {
173               getMessageUI().showError(Pooka.getProperty("error.MessageUI.sendFailed", "Failed to send Message.") + "\n" + me.getMessage());
174               me.printStackTrace(System.out);
175             }
176             nmui.setBusy(false);
177           }
178         };
179       SwingUtilities.invokeLater(runMe);
180     } else {
181       Runnable JavaDoc runMe = new Runnable JavaDoc() {
182           public void run() {
183             Pooka.getUIFactory().showError(Pooka.getProperty("error.MessageUI.sendFailed", "Failed to send Message.") + "\n" + me.getMessage());
184             me.printStackTrace(System.out);
185           }
186         };
187       SwingUtilities.invokeLater(runMe);
188     }
189   }
190
191   /**
192    * Matches the currently selected UserProfile to the one set in the
193    * NewMessageInfo.
194    */

195   public void matchUserProfile() {
196     NewMessageUI nmui = getNewMessageUI();
197     if (nmui != null) {
198       try {
199         String JavaDoc profileId = (String JavaDoc) getMessageInfo().getMessageProperty(Pooka.getProperty("Pooka.userProfileProperty", "X-Pooka-UserProfile"));
200         if (profileId != null && ! profileId.equals("")) {
201           UserProfile profile = Pooka.getPookaManager().getUserProfileManager().getProfile(profileId);
202           if (profile != null)
203             nmui.setSelectedProfile(profile);
204         }
205       } catch (MessagingException me) {
206         // no big deal... we can just have the default user selected.
207
}
208     }
209   }
210
211   /**
212    * This attaches a file to a given message. Really, all it does is
213    * calls getFileToAttach(), and then sends that to attachFile().
214    */

215   public void attach() {
216     File[] f = getFileToAttach();
217     if (f != null) {
218       NewMessageUI nmui = getNewMessageUI();
219       nmui.setModified(true);
220       for (int i = 0; i < f.length; i++)
221         attachFile(f[i]);
222     }
223   }
224
225   /**
226    * This calls on the MessageUI to bring up a FileDialog to choose
227    * the file to attach to the message. If no choice is made, this
228    * method returns null.
229    */

230   public File[] getFileToAttach() {
231     return getNewMessageUI().getFiles(Pooka.getProperty("MessageUI.attachFileDialog.title", "Choose file to attach."), Pooka.getProperty("MessageUI.attachFileDialog.buttonText", "Attach"));
232   }
233
234   /**
235    * This actually attaches the File to the Message. Any errors are
236    * sent to the MessageUI to display.
237    *
238    * This also sets the 'hasAttachment' property on the MessageUI
239    * to true.
240    */

241   public void attachFile(File f) {
242     try {
243       getNewMessageInfo().attachFile(f);
244
245       getNewMessageUI().attachmentAdded(getNewMessageInfo().getAttachments().size() -1);
246     } catch (Exception JavaDoc e) {
247       getMessageUI().showError(Pooka.getProperty("error.MessageUI.unableToAttachFile", "Unable to attach file."), Pooka.getProperty("error.MessageUI.unableToAttachFile.title", "Unable to Attach File."), e);
248     }
249
250   }
251
252   /**
253    * This removes the given Attachment from the list of attachments.
254    * I figure that you're likely only to be removing attachments from
255    * the attachment list itself, so you should be able to get the
256    * correct underlying object.
257    */

258   public void detachFile(Attachment a) {
259     int index = getNewMessageInfo().removeAttachment(a);
260     if (index != -1)
261       getNewMessageUI().attachmentRemoved(index);
262   }
263
264   /**
265    * Saves this message as a draft version, if there is an Outbox
266    * configured.
267    */

268   public void saveDraft() {
269     // thread: AwtEvent
270

271     synchronized(this) {
272       if (sendLock) {
273         Pooka.getUIFactory().showStatusMessage(Pooka.getProperty("info.sendMessage.alreadySendingMessage", "Already sending message."));
274         return;
275       } else
276         sendLock = true;
277     }
278
279     try {
280       if (getNewMessageUI() != null) {
281         getNewMessageUI().setBusy(true);
282
283         final UserProfile profile = getNewMessageUI().getSelectedProfile();
284         final InternetHeaders headers = getNewMessageUI().getMessageHeaders();
285
286         final String JavaDoc messageText = getNewMessageUI().getMessageText();
287
288         final String JavaDoc messageContentType = getNewMessageUI().getMessageContentType();
289
290         OutgoingMailServer mailServer = profile.getMailServer();
291
292         final FolderInfo fi = mailServer.getOutbox();
293
294         if (fi != null) {
295           net.suberic.util.thread.ActionThread folderThread = fi.getFolderThread();
296           Action runMe = new AbstractAction() {
297               public void actionPerformed(java.awt.event.ActionEvent JavaDoc e) {
298                 try {
299                   getNewMessageInfo().saveDraft(fi, profile, headers, messageText, messageContentType);
300                   saveDraftSucceeded(fi);
301                 } catch (MessagingException me) {
302                   saveDraftFailed(me);
303                 }
304               }
305             };
306           folderThread.addToQueue(runMe, new java.awt.event.ActionEvent JavaDoc(this, 0, "saveDraft"));
307         } else {
308           saveDraftFailed(new MessagingException ("No outbox specified for default mailserver " + mailServer.getItemID()));
309         }
310       } else {
311         sendLock = false;
312       }
313     } catch (MessagingException me) {
314       sendLock=false;
315       getMessageUI().showError(Pooka.getProperty("Error.sendingMessage", "Error sending message: "), me);
316       getNewMessageUI().setBusy(false);
317     }
318
319   }
320
321   /**
322    * Called when the save draft succeeds.
323    */

324   public void saveDraftSucceeded(FolderInfo outboxFolder) {
325     final FolderInfo outbox = outboxFolder;
326     final NewMessageUI nmui = getNewMessageUI();
327     if (nmui != null) {
328       Runnable JavaDoc runMe = new Runnable JavaDoc() {
329           public void run() {
330             nmui.setBusy(false);
331             nmui.setModified(false);
332             getMessageUI().showMessageDialog("Message saved to " +outbox.getFolderID(), "Draft Saved");
333             getMessageUI().closeMessageUI();
334           }
335         };
336       SwingUtilities.invokeLater(runMe);
337     }
338     sendLock=false;
339
340   }
341
342   /**
343    * Called when the send fails.
344    */

345   public void saveDraftFailed(Exception JavaDoc e) {
346     final Exception JavaDoc me = e;
347     final NewMessageUI nmui = getNewMessageUI();
348     if (nmui != null) {
349       Runnable JavaDoc runMe = new Runnable JavaDoc() {
350           public void run() {
351             getMessageUI().showError(Pooka.getProperty("error.MessageUI.saveDraftFailed", "Failed to save message."), me);
352             nmui.setBusy(false);
353           }
354         };
355       SwingUtilities.invokeLater(runMe);
356     }
357     sendLock=false;
358   }
359
360
361   /**
362    * a convenience method which returns the current MessageUI as
363    * a NewMessageUI.
364    */

365   public NewMessageUI getNewMessageUI() {
366     if (getMessageUI() instanceof NewMessageUI)
367       return (NewMessageUI)getMessageUI();
368     else
369       return null;
370   }
371
372   /**
373    * a convenience method which returns the current MessageInfo as
374    * a NewMessageInfo.
375    */

376   public NewMessageInfo getNewMessageInfo() {
377     return (NewMessageInfo) messageInfo;
378   }
379
380   /**
381    * Returns the CryptoInfo for this proxy.
382    */

383   public NewMessageCryptoInfo getCryptoInfo() {
384     return mCryptoInfo;
385   }
386
387   /**
388    * Returns whether or not we should prompt the user to see if they really
389    * want to close the window for this message.
390    */

391   public boolean promptForClose() {
392     if (! Pooka.getProperty("Pooka.checkUnsentMessages", "false").equalsIgnoreCase("true")) {
393       return false;
394     }
395
396     NewMessageUI nmui = getNewMessageUI();
397
398     if (nmui != null) {
399       return nmui.isModified();
400     }
401
402     return false;
403   }
404
405   public Action[] defaultActions = {
406     new SendAction(),
407     new AttachAction(),
408     new SaveDraftAction(),
409     new EncryptAction(),
410     new ClearEncryptAction(),
411     new SelectEncryptionKeyAction(),
412     new SignAction(),
413     new ClearSignAction(),
414     new SelectSignatureKeyAction(),
415     new AttachKeyAction(),
416     new RemoveKeyAction()
417   };
418
419   public Action getAction(String JavaDoc name) {
420     return (Action)commands.get(name);
421   }
422
423   public Action[] getActions() {
424     return defaultActions;
425   }
426
427   public static Vector JavaDoc getUnsentProxies() {
428     return allUnsentProxies;
429   }
430
431   class SendAction extends AbstractAction {
432     SendAction() {
433       super("message-send");
434     }
435
436     public void actionPerformed(ActionEvent JavaDoc e) {
437       send();
438     }
439   }
440
441   class AttachAction extends AbstractAction {
442     AttachAction() {
443       super("message-attach-file");
444     }
445
446     public void actionPerformed(ActionEvent JavaDoc e) {
447       attach();
448     }
449   }
450
451   class SaveDraftAction extends AbstractAction {
452     SaveDraftAction() {
453       super("message-save-draft");
454     }
455
456     public void actionPerformed(ActionEvent JavaDoc e) {
457       saveDraft();
458     }
459   }
460
461
462   class EncryptAction extends AbstractAction {
463     EncryptAction() {
464       super("message-encrypt");
465     }
466
467     public void actionPerformed(ActionEvent JavaDoc e) {
468       CryptoStatusDisplay csd = getMessageUI().getCryptoStatusDisplay();
469       if (csd instanceof NewMessageCryptoDisplay) {
470         ((NewMessageCryptoDisplay) csd).setEncryptMessage(NewMessageCryptoInfo.CRYPTO_YES);
471       }
472
473       if (getCryptoInfo().getEncryptionKey() == null && getNewMessageUI().getSelectedProfile().getEncryptionKey() == null) {
474         try {
475           java.security.Key JavaDoc cryptKey = selectPublicKey(Pooka.getProperty("Pooka.crypto.publicKey.forEncrypt", "Select key to encrypt this message."), Pooka.getProperty("Pooka.crypto.publicKey.title", "Select public key"));
476           if (cryptKey != null) {
477             if (csd instanceof NewMessageCryptoDisplay) {
478               ((NewMessageCryptoDisplay) csd).setEncryptionKey(cryptKey);
479             }
480           }
481         } catch (Exception JavaDoc ex) {
482           getMessageUI().showError(ex.getMessage(), ex);
483         }
484       }
485     }
486   }
487
488   class SignAction extends AbstractAction {
489     SignAction() {
490       super("message-sign");
491     }
492
493     public void actionPerformed(ActionEvent JavaDoc e) {
494       CryptoStatusDisplay csd = getMessageUI().getCryptoStatusDisplay();
495       if (csd instanceof NewMessageCryptoDisplay) {
496         ((NewMessageCryptoDisplay) csd).setSignMessage(NewMessageCryptoInfo.CRYPTO_YES);
497       }
498
499       if (getCryptoInfo().getSignatureKey() == null && (getDefaultProfile() == null || getDefaultProfile().getEncryptionKey() == null)) {
500         try {
501           java.security.Key JavaDoc signKey = selectPrivateKey(Pooka.getProperty("Pooka.crypto.privateKey.forSig", "Select key to sign this message."), Pooka.getProperty("Pooka.crypto.privateKey.title", "Select private key"));
502           if (csd instanceof NewMessageCryptoDisplay) {
503             ((NewMessageCryptoDisplay) csd).setSignatureKey(signKey);
504           }
505         } catch (Exception JavaDoc ex) {
506           getMessageUI().showError(ex.getMessage(), ex);
507         }
508
509       }
510     }
511   }
512
513   class SelectSignatureKeyAction extends AbstractAction {
514     SelectSignatureKeyAction() {
515       super("message-select-sig-key");
516     }
517
518     public void actionPerformed(ActionEvent JavaDoc e) {
519       CryptoStatusDisplay csd = getMessageUI().getCryptoStatusDisplay();
520       if (csd instanceof NewMessageCryptoDisplay) {
521         ((NewMessageCryptoDisplay) csd).setSignMessage(NewMessageCryptoInfo.CRYPTO_YES);
522       }
523
524       try {
525         java.security.Key JavaDoc signKey = selectPrivateKey(Pooka.getProperty("Pooka.crypto.privateKey.forSig", "Select key to sign this message."), Pooka.getProperty("Pooka.crypto.privateKey.title", "Select private key"));
526         if (signKey != null) {
527           if (csd instanceof NewMessageCryptoDisplay) {
528             ((NewMessageCryptoDisplay) csd).setSignatureKey(signKey);
529           }
530         }
531       } catch (Exception JavaDoc ex) {
532         getMessageUI().showError(ex.getMessage(), ex);
533       }
534     }
535   }
536
537   class SelectEncryptionKeyAction extends AbstractAction {
538     SelectEncryptionKeyAction() {
539       super("message-select-crypt-key");
540     }
541
542     public void actionPerformed(ActionEvent JavaDoc e) {
543       CryptoStatusDisplay csd = getMessageUI().getCryptoStatusDisplay();
544       if (csd instanceof NewMessageCryptoDisplay) {
545         ((NewMessageCryptoDisplay) csd).setEncryptMessage(NewMessageCryptoInfo.CRYPTO_YES);
546       }
547
548       try {
549         java.security.Key JavaDoc cryptKey = selectPublicKey(Pooka.getProperty("Pooka.crypto.publicKey.forEncrypt", "Select key to encrypt this message."), Pooka.getProperty("Pooka.crypto.publicKey.title", "Select public key"));
550         if (cryptKey != null) {
551           if (csd instanceof NewMessageCryptoDisplay) {
552             ((NewMessageCryptoDisplay) csd).setEncryptionKey(cryptKey);
553           }
554         }
555       } catch (Exception JavaDoc ex) {
556         getMessageUI().showError(ex.getMessage(), ex);
557       }
558     }
559   }
560
561   class ClearEncryptAction extends AbstractAction {
562     ClearEncryptAction() {
563       super("message-clear-encrypt");
564     }
565
566     public void actionPerformed(ActionEvent JavaDoc e) {
567       CryptoStatusDisplay csd = getMessageUI().getCryptoStatusDisplay();
568       if (csd instanceof NewMessageCryptoDisplay) {
569         ((NewMessageCryptoDisplay) csd).setEncryptMessage(NewMessageCryptoInfo.CRYPTO_NO);((NewMessageCryptoDisplay) csd).setEncryptionKey(null);
570       }
571     }
572   }
573
574   class ClearSignAction extends AbstractAction {
575     ClearSignAction() {
576       super("message-clear-signature");
577     }
578
579     public void actionPerformed(ActionEvent JavaDoc e) {
580       CryptoStatusDisplay csd = getMessageUI().getCryptoStatusDisplay();
581
582       if (csd instanceof NewMessageCryptoDisplay) {
583         ((NewMessageCryptoDisplay) csd).setSignMessage(NewMessageCryptoInfo.CRYPTO_NO);
584         ((NewMessageCryptoDisplay) csd).setSignatureKey(null);
585       }
586     }
587   }
588
589   class AttachKeyAction extends AbstractAction {
590     AttachKeyAction() {
591       super("message-attach-crypt-key");
592     }
593
594     public void actionPerformed(ActionEvent JavaDoc e) {
595       CryptoStatusDisplay csd = getMessageUI().getCryptoStatusDisplay();
596
597       if (csd instanceof NewMessageCryptoDisplay) {
598         try {
599           java.security.Key JavaDoc cryptKey = selectPublicKey(Pooka.getProperty("Pooka.crypto.publicKey.forAttach", "Select key to attach to message."), Pooka.getProperty("Pooka.crypto.publicKey.title", "Select public key"));
600           ((NewMessageCryptoDisplay) csd).attachEncryptionKey(cryptKey);
601         } catch (Exception JavaDoc ex) {
602           getMessageUI().showError(ex.getMessage(), ex);
603         }
604       }
605     }
606   }
607
608   class RemoveKeyAction extends AbstractAction {
609     RemoveKeyAction() {
610       super("message-remove-crypt-key");
611     }
612
613     public void actionPerformed(ActionEvent JavaDoc e) {
614       CryptoStatusDisplay csd = getMessageUI().getCryptoStatusDisplay();
615
616       if (csd instanceof NewMessageCryptoDisplay) {
617         try {
618           java.security.Key JavaDoc cryptKey = selectPublicKey(Pooka.getProperty("Pooka.crypto.publicKey.forRemove", "Select key to remove from message."), Pooka.getProperty("Pooka.crypto.publicKey.title", "Remove public key"));
619           ((NewMessageCryptoDisplay) csd).removeEncryptionKey(cryptKey);
620         } catch (Exception JavaDoc ex) {
621           getMessageUI().showError(ex.getMessage(), ex);
622         }
623       }
624     }
625   }
626
627 }
628
629
630
631
632
633
634
Popular Tags