KickJava   Java API By Example, From Geeks To Geeks.

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


1 package net.suberic.pooka;
2 import net.suberic.pooka.gui.*;
3 import net.suberic.pooka.resource.*;
4 import net.suberic.pooka.messaging.*;
5 import net.suberic.util.VariableBundle;
6 import net.suberic.util.gui.IconManager;
7 import net.suberic.util.gui.propedit.PropertyEditorFactory;
8 import net.suberic.util.gui.propedit.PropertyEditorManager;
9
10 import java.awt.*;
11 import javax.swing.*;
12 import javax.help.*;
13 import java.util.logging.*;
14
15 /**
16  * This manages all startup options for Pooka.
17  */

18 public class StartupManager {
19
20   // the PookaManager that we're using to startup. for convenience.
21
PookaManager mPookaManager = null;
22
23   JFrame mFrame = null;
24
25   // settings
26
public boolean mOpenFolders = true;
27   public boolean mUseHttp = false;
28   public boolean mUseLocalFiles = true;
29   public boolean mFullStartup = true;
30   String JavaDoc mToAddress = null;
31   String JavaDoc mFromProfile = null;
32
33   boolean mShuttingDown = false;
34
35   /**
36    * Creates a new StartupManager.
37    */

38   public StartupManager(PookaManager pPookaManager) {
39     mPookaManager = pPookaManager;
40   }
41
42   /**
43    * Runs Pooka.
44    */

45   public void runPooka(String JavaDoc argv[]) {
46     mStartTime = System.currentTimeMillis();
47
48     Pooka.loadInitialResources();
49
50     updateTime("intial resources parsed.");
51
52     parseArgs(argv);
53
54     updateTime("args parsed.");
55
56     Pooka.loadResources(mUseLocalFiles, mUseHttp);
57
58     mPookaManager.setLogManager(new PookaLogManager());
59
60     updateTime("resources loaded.");
61
62     if (! checkJavaVersion()) {
63       versionError();
64       System.exit(-1);
65     }
66
67     System.setProperty("swing.aatext", "true");
68
69     // check to see if there's already a Pooka instance running.
70
if (!checkRunningInstance()) {
71       if (mFullStartup) {
72         startupPooka();
73       } else {
74         startupMinimal();
75       }
76     }
77   }
78
79   /**
80    * Does a full startup of Pooka.
81    */

82   public void startupPooka() {
83     net.suberic.pooka.gui.PookaStartup startup = new net.suberic.pooka.gui.PookaStartup();
84     startup.show();
85
86     updateTime("startup invoked.");
87
88     loadManagers(startup);
89
90     startupMainPookaWindow(startup);
91   }
92
93   /**
94    * Starts up the main Pooka window.
95    */

96   public void startupMainPookaWindow(net.suberic.pooka.gui.PookaStartup pStartup) {
97
98     final net.suberic.pooka.gui.PookaStartup startup = pStartup;
99     mFrame = new JFrame("Pooka");
100     final JFrame finalFrame = mFrame;
101
102     mPookaManager.setFolderTracker(new net.suberic.pooka.thread.FolderTracker());
103     mPookaManager.getFolderTracker().start();
104     updateTime("started folderTracker");
105
106     mPookaManager.setSearchThread(new net.suberic.util.thread.ActionThread(Pooka.getProperty("thread.searchThread", "Search Thread ")));
107     mPookaManager.getSearchThread().start();
108     updateTime("started search thread");
109
110     if (Pooka.getUIFactory() == null) {
111       if (Pooka.getProperty("Pooka.guiType", "Desktop").equalsIgnoreCase("Preview"))
112         mPookaManager.setUIFactory(new PookaPreviewPaneUIFactory());
113       else
114         mPookaManager.setUIFactory(new PookaDesktopPaneUIFactory());
115     } else if (Pooka.getUIFactory() instanceof net.suberic.pooka.gui.PookaMinimalUIFactory) {
116       if (Pooka.getProperty("Pooka.guiType", "Desktop").equalsIgnoreCase("Preview"))
117         mPookaManager.setUIFactory(new PookaPreviewPaneUIFactory(Pooka.getUIFactory()));
118       else
119         mPookaManager.setUIFactory(new PookaDesktopPaneUIFactory(Pooka.getUIFactory()));
120     }
121
122     if (startup != null)
123       startup.setStatus("Pooka.startup.configuringWindow");
124
125     // do all of this on the awt event thread.
126
Runnable JavaDoc createPookaUI = new Runnable JavaDoc() {
127         public void run() {
128           finalFrame.setBackground(Color.lightGray);
129           finalFrame.getContentPane().setLayout(new BorderLayout());
130           MainPanel panel = new MainPanel(finalFrame);
131           mPookaManager.setMainPanel(panel);
132           finalFrame.getContentPane().add("Center", panel);
133
134           updateTime("created main panel");
135           if (startup != null)
136             startup.setStatus("Pooka.startup.starting");
137
138           panel.configureMainPanel();
139
140           updateTime("configured main panel");
141
142
143           //finalFrame.getContentPane().add("North", panel.getMainToolbar());
144

145           finalFrame.setJMenuBar(panel.getMainMenu());
146           finalFrame.getContentPane().add("South", panel.getInfoPanel());
147           finalFrame.pack();
148           finalFrame.setSize(Integer.parseInt(Pooka.getProperty("Pooka.hsize", "800")), Integer.parseInt(Pooka.getProperty("Pooka.vsize", "600")));
149
150           int x = Integer.parseInt(Pooka.getProperty("Pooka.lastX", "10"));
151           int y = Integer.parseInt(Pooka.getProperty("Pooka.lastY", "10"));
152
153           finalFrame.setLocation(x, y);
154           updateTime("configured frame");
155           if (startup != null)
156             startup.hide();
157           finalFrame.setVisible(true);
158           updateTime("showed frame");
159
160           mPookaManager.getUIFactory().setShowing(true);
161
162           if (Pooka.getProperty("Store", "").equals("")) {
163             if (panel.getContentPanel() instanceof MessagePanel) {
164               SwingUtilities.invokeLater(new Runnable JavaDoc() {
165                   public void run() {
166                     //new FirstRunWizard().start();
167
}
168                 });
169             }
170           } else if (mOpenFolders && Pooka.getProperty("Pooka.openSavedFoldersOnStartup", "false").equalsIgnoreCase("true")) {
171             panel.getContentPanel().openSavedFolders(mPookaManager.getResources().getPropertyAsVector("Pooka.openFolderList", ""));
172           }
173           panel.refreshActiveMenus();
174         }
175       };
176
177     try {
178       javax.swing.SwingUtilities.invokeAndWait(createPookaUI);
179     } catch (Exception JavaDoc e) {
180       System.err.println("caught exception creating ui: " + e);
181       e.printStackTrace();
182     }
183   }
184
185   /**
186    * Stops the main Pooka window.
187    */

188   public void stopMainPookaWindow(Object JavaDoc pSource) {
189     checkUnsentMessages();
190
191     //checkUncachedMessages();
192

193     net.suberic.pooka.thread.FolderTracker ft = mPookaManager.getFolderTracker();
194     if (ft != null)
195       ft.setStopped(true);
196
197     net.suberic.util.thread.ActionThread searchThread = mPookaManager.getSearchThread();
198     if (searchThread != null)
199       mPookaManager.getSearchThread().setStop(true);
200
201     closeAllStores(pSource);
202
203     // wait to set the foldertracker as null until after we've closed all
204
// the stores.
205
mPookaManager.setFolderTracker(null);
206
207     Pooka.getResources().saveProperties();
208
209     try {
210       SwingUtilities.invokeAndWait(new Runnable JavaDoc() {
211           public void run() {
212             Pooka.getMainPanel().getParentFrame().setVisible(false);
213             Pooka.getMainPanel().getParentFrame().dispose();
214           }
215         });
216     } catch (Exception JavaDoc e) {
217     }
218
219   }
220
221   /**
222    * Checks for any unsent messages.
223    */

224   void checkUnsentMessages() {
225     java.util.List JavaDoc allServers = mPookaManager.getOutgoingMailManager().getOutgoingMailServerList();
226     // first stop all the servers.
227
java.util.Iterator JavaDoc iter = allServers.iterator();
228     while (iter.hasNext()) {
229       OutgoingMailServer oms = (OutgoingMailServer) iter.next();
230       oms.stopServer();
231     }
232
233     int counter = 0;
234     iter = allServers.iterator();
235     String JavaDoc waitingMessage = Pooka.getProperty("info.exit.waiting.send", "Waiting {0,number} seconds to send unsent messages...");
236
237     while (iter.hasNext()) {
238       OutgoingMailServer oms = (OutgoingMailServer) iter.next();
239       /*
240         while (oms.isSending() && counter < 5) {
241         Object[] args = new Object[] { new Integer(5 - counter) };
242         Pooka.getUIFactory().showStatusMessage(java.text.MessageFormat.format(waitingMessage, args));
243         // wait for 5 seconds for all threads to exit.
244         try {
245         Thread.currentThread().sleep(1000);
246         } catch (Exception e) { }
247         counter++;
248         }
249       */

250       while (oms.isSending()) {
251         Pooka.getUIFactory().showStatusMessage(Pooka.getProperty("info.exit.waiting.send.noCounter", "Waiting to finish sending unsent messages..."));
252         try {
253           Thread.currentThread().sleep(1000);
254         } catch (Exception JavaDoc e) { }
255       }
256     }
257
258
259   }
260
261   /**
262    * Closes all stores.
263    */

264   void closeAllStores(Object JavaDoc pSource) {
265     mPookaManager.getStoreManager().cleanup();
266     java.util.Vector JavaDoc v = mPookaManager.getStoreManager().getStoreList();
267     final java.util.HashMap JavaDoc doneMap = new java.util.HashMap JavaDoc();
268
269     for (int i = 0; i < v.size(); i++) {
270       // FIXME: we should check to see if there are any messages
271
// to be deleted, and ask the user if they want to expunge the
272
// deleted messages.
273
final StoreInfo currentStore = (StoreInfo)v.elementAt(i);
274       net.suberic.util.thread.ActionThread storeThread = currentStore.getStoreThread();
275       if (storeThread != null) {
276         doneMap.put(currentStore, new Boolean JavaDoc(false));
277         storeThread.addToQueue(new net.suberic.util.thread.ActionWrapper(new javax.swing.AbstractAction JavaDoc() {
278
279             public void actionPerformed(java.awt.event.ActionEvent JavaDoc actionEvent) {
280               try {
281                 if (currentStore.isConnected()) {
282                   currentStore.closeAllFolders(false, true);
283                   currentStore.disconnectStore();
284                 } else {
285                   doneMap.put(currentStore, new Boolean JavaDoc(true));
286                 }
287               } catch (Exception JavaDoc e) {
288                 // ignore. just say done and exit.
289
} finally {
290                 currentStore.stopStoreThread();
291                 currentStore.cleanup();
292                 doneMap.put(currentStore, new Boolean JavaDoc(true));
293               }
294             }
295           }, storeThread), new java.awt.event.ActionEvent JavaDoc(pSource, 1, "store-close"), net.suberic.util.thread.ActionThread.PRIORITY_HIGH);
296       }
297     }
298     long sleepTime = 30000;
299     try {
300       sleepTime = Long.parseLong(Pooka.getProperty("Pooka.exitTimeout", "30000"));
301     } catch (Exception JavaDoc e) {
302     }
303     long currentTime = System.currentTimeMillis();
304     boolean done = false;
305
306     String JavaDoc closingMessage = Pooka.getProperty("info.exit.closing", "Closing Store {0}");
307     String JavaDoc waitingMessage = Pooka.getProperty("info.exit.waiting", "Closing Store {0}... Waiting {1,number} seconds.");
308     String JavaDoc waitingMultipleMessage = Pooka.getProperty("info.exit.waiting.multiple", "Waiting {0,number} seconds for {1,number} Stores to close.");
309
310     while (! done && System.currentTimeMillis() - currentTime < sleepTime) {
311       String JavaDoc waitingStoreName = null;
312       int waitingStoreCount = 0;
313       try {
314         Thread.currentThread().sleep(1000);
315       } catch (InterruptedException JavaDoc ie) {
316       }
317       done = true;
318       for (int i = 0; i < v.size(); i++) {
319         Object JavaDoc key = v.get(i);
320         Boolean JavaDoc value = (Boolean JavaDoc) doneMap.get(key);
321         if (value != null && ! value.booleanValue()) {
322           done = false;
323           waitingStoreCount++;
324           if (waitingStoreName == null)
325             waitingStoreName = ((StoreInfo) key).getStoreID();
326         }
327       }
328
329       if (! done) {
330         int secondsWaiting = (int) (sleepTime - (System.currentTimeMillis() - currentTime)) / 1000;
331         String JavaDoc message = closingMessage;
332         Object JavaDoc[] args;
333         if (secondsWaiting > 20) {
334           args = new Object JavaDoc[] { waitingStoreName };
335           message = closingMessage;
336         } else if (waitingStoreCount == 1) {
337           args = new Object JavaDoc[] { waitingStoreName, new Integer JavaDoc(secondsWaiting) };
338           message = waitingMessage;
339         } else {
340           args = new Object JavaDoc[] { new Integer JavaDoc(secondsWaiting), new Integer JavaDoc(waitingStoreCount) };
341           message = waitingMultipleMessage;
342         }
343         Pooka.getUIFactory().showStatusMessage(java.text.MessageFormat.format(message, args));
344       }
345     }
346
347   }
348
349   /**
350    * Moves Pooka over to a Minimal startup.
351    */

352   public void stopPookaToTray(Object JavaDoc pSource) {
353     final Object JavaDoc fSource = pSource;
354     Runnable JavaDoc runMe = new Runnable JavaDoc() {
355         public void run() {
356           try {
357             mShuttingDown = true;
358
359             stopMainPookaWindow(fSource);
360             mFrame = null;
361             if (mPookaManager.getMainPanel() != null) {
362               KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener(mPookaManager.getMainPanel().getFocusManager());
363               mPookaManager.getMainPanel().getInfoPanel().stopThread();
364             }
365             mPookaManager.setMainPanel(null);
366             mPookaManager.getUIFactory().setShowing(false);
367             /*
368               mPookaManager.setStoreManager(new StoreManager());
369               updateTime("created store manager.");
370
371               mPookaManager.getStoreManager().loadAllSentFolders();
372               mPookaManager.getOutgoingMailManager().loadOutboxFolders();
373             updateTime("loaded sent/outbox");
374             */

375             mPookaManager.setStoreManager(null);
376             mPookaManager.getUserProfileManager().shutdownManager();
377             mPookaManager.setUserProfileManager(null);
378             mPookaManager.getOutgoingMailManager().stopServers();
379
380             /*
381               java.util.Map allListeners = mPookaManager.getResources().getAllListeners();
382               java.util.Iterator keys = allListeners.keySet().iterator();
383               while (keys.hasNext()) {
384               Object o = keys.next();
385               Object value = allListeners.get(o);
386               if (value instanceof java.util.List) {
387               java.util.Iterator values = ((java.util.List) value).iterator();
388               while (values.hasNext()) {
389               System.err.println("key " + o + ", value " + values.next());
390               }
391               } else {
392               System.err.println("key " + o + ", value " + allListeners.get(o));
393               }
394               }
395             */

396           } finally {
397             mShuttingDown = false;
398           }
399           PookaUIFactory newFactory = new PookaMinimalUIFactory(Pooka.getUIFactory());
400
401           mFullStartup=false;
402
403           loadManagers(null);
404           mPookaManager.setUIFactory(newFactory);
405           if (mPookaManager.getResources().getProperty("Pooka.exitToIcon.notify", "true").equalsIgnoreCase("true")) {
406             MessageNotificationManager mnm = newFactory.getMessageNotificationManager();
407             if (mnm != null)
408               mnm.displayMessage(mPookaManager.getResources().getProperty("info.exitToIcon.title", "System Tray Notification"), mPookaManager.getResources().getProperty("info.exitToIcon", "Pooka has disconnected from you mail servers, but is still running in the System Tray. To exit Pooka completely, use File->Exit from the toolbar or right-click on the Tray Icon and choose Exit."), MessageNotificationManager.INFO_MESSAGE_TYPE);
409
410           }
411         }
412       };
413     if (Pooka.getMainPanel() != null)
414       Pooka.getMainPanel().setCursor(java.awt.Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
415
416     Thread JavaDoc stopWindowThread = new Thread JavaDoc(runMe);
417     stopWindowThread.start();
418   }
419
420   /**
421    * Does a minimal startup of Pooka.
422    */

423   public void startupMinimal() {
424     updateTime("startup invoked.");
425
426     loadManagers(null);
427
428     mPookaManager.setUIFactory(new PookaMinimalUIFactory());
429
430     if (mToAddress != null) {
431       if (!sendMessageTo(mToAddress, mFromProfile))
432         System.err.println("send failed.");
433     }
434   }
435
436   /**
437    * Checks to see if there's already a running instance of Pooka that
438    * we can use.
439    */

440   boolean checkRunningInstance() {
441     // first see if there's already a pooka instance running.
442
net.suberic.pooka.messaging.PookaMessageSender sender = new net.suberic.pooka.messaging.PookaMessageSender();
443     try {
444       sender.openConnection();
445       // check to make sure that we're connected to a correct version of Pooka.
446
if (sender.checkVersion()) {
447         // ok, there is one. try either sending a message or starting
448
// up Pooka, whichever we're trying to do.
449
if (mFullStartup) {
450           sender.sendStartPookaMessage();
451           sender.closeConnection();
452           System.out.println("contacted already running instance of Pooka.");
453           return true;
454         } else {
455           return sendMessageTo(mToAddress, mFromProfile);
456         }
457       }
458     } catch (Exception JavaDoc e) {
459
460     }
461
462     return false;
463   }
464
465   /**
466    * This loads all of the background managers that Pooka uses.
467    */

468   public void loadManagers(net.suberic.pooka.gui.PookaStartup startup) {
469     if (startup != null)
470       startup.setStatus("Pooka.startup.ssl");
471     updateTime("loading ssl");
472     StoreManager.setupSSL();
473     updateTime("ssl loaded.");
474
475     try {
476       UIManager.setLookAndFeel(Pooka.getProperty("Pooka.looknfeel", UIManager.getCrossPlatformLookAndFeelClassName()));
477     } catch (Exception JavaDoc e) { System.out.println("Cannot set look and feel...");
478     }
479     updateTime("set looknfeel");
480
481     if (startup != null)
482       startup.setStatus("Pooka.startup.addressBook");
483     mPookaManager.setAddressBookManager(new AddressBookManager());
484     updateTime("loaded address book");
485
486     mPookaManager.setConnectionManager(new NetworkConnectionManager());
487     updateTime("loaded connections");
488
489     mPookaManager.setOutgoingMailManager(new OutgoingMailServerManager());
490     updateTime("loaded mailservers");
491
492     mPookaManager.setDateFormatter(new DateFormatter());
493
494     if (startup != null)
495       startup.setStatus("Pooka.startup.profiles");
496     UserProfileManager profileManager = new UserProfileManager(mPookaManager.getResources());
497     mPookaManager.setUserProfileManager(profileManager);
498     updateTime("created profiles");
499
500     String JavaDoc mailcapSource = null;
501     if (System.getProperty("file.separator").equals("\\")) {
502       mailcapSource = System.getProperty("user.home") + "\\pooka_mailcap.txt";
503     } else {
504       mailcapSource = System.getProperty("user.home") + System.getProperty("file.separator") + ".pooka_mailcap";
505     }
506     try {
507       mPookaManager.setMailcap(Pooka.getResourceManager().createMailcap(mailcapSource));
508     } catch (java.io.IOException JavaDoc ioe) {
509       System.err.println("exception loading mailcap: " + ioe);
510     }
511
512     updateTime("created mailcaps");
513
514     javax.activation.CommandMap.setDefaultCommandMap(mPookaManager.getMailcap());
515     javax.activation.FileTypeMap.setDefaultFileTypeMap(mPookaManager.getMimeTypesMap());
516     updateTime("set command/file maps");
517
518     if (startup != null)
519       startup.setStatus("Pooka.startup.crypto");
520     mPookaManager.setCryptoManager(new PookaEncryptionManager(mPookaManager.getResources(), "EncryptionManager"));
521     updateTime("loaded encryption manager");
522
523     mPookaManager.setSearchManager(new SearchTermManager("Search"));
524     updateTime("created search manager");
525
526     // set up help
527
if (startup != null)
528       startup.setStatus("Pooka.startup.help");
529     try {
530       ClassLoader JavaDoc cl = new Pooka().getClass().getClassLoader();
531       java.net.URL JavaDoc hsURL = HelpSet.findHelpSet(cl, "net/suberic/pooka/doc/en/help/Master.hs");
532       HelpSet hs = new HelpSet(cl, hsURL);
533       mPookaManager.setHelpBroker(hs.createHelpBroker());
534     } catch (Exception JavaDoc ee) {
535       System.out.println("HelpSet net/suberic/pooka/doc/en/help/merge/Master.hs not found: " + ee);
536       ee.printStackTrace();
537     }
538     updateTime("loaded help");
539
540     if (mFullStartup) {
541       if (Pooka.getProperty("Pooka.guiType", "Desktop").equalsIgnoreCase("Preview"))
542         mPookaManager.setUIFactory(new PookaPreviewPaneUIFactory());
543       else
544         mPookaManager.setUIFactory(new PookaDesktopPaneUIFactory());
545
546       updateTime("created ui factory");
547     }
548
549     mPookaManager.getResources().addValueChangeListener(new net.suberic.util.ValueChangeListener() {
550
551         public void valueChanged(String JavaDoc changedValue) {
552           if (Pooka.getProperty("Pooka.guiType", "Desktop").equalsIgnoreCase("Preview")) {
553             MessagePanel mp = (MessagePanel) Pooka.getMainPanel().getContentPanel();
554             PookaPreviewPaneUIFactory newFactory = new PookaPreviewPaneUIFactory(Pooka.getUIFactory());
555             mPookaManager.setUIFactory(newFactory);
556
557             ContentPanel cp = newFactory.createContentPanel(mp);
558             Pooka.getMainPanel().setContentPanel(cp);
559             Pooka.getMainPanel().setMainToolbar(newFactory.createMainToolbar());
560             Pooka.getMainPanel().getFolderPanel().setFolderPanelToolbar(newFactory.createFolderPanelToolbar());
561           } else {
562             PreviewContentPanel pcp = (PreviewContentPanel) Pooka.getMainPanel().getContentPanel();
563             PookaDesktopPaneUIFactory newFactory = new PookaDesktopPaneUIFactory(Pooka.getUIFactory());
564             mPookaManager.setUIFactory(newFactory);
565             ContentPanel mp = newFactory.createContentPanel(pcp);
566             Pooka.getMainPanel().setContentPanel(mp);
567             Pooka.getMainPanel().setMainToolbar(newFactory.createMainToolbar());
568             Pooka.getMainPanel().getFolderPanel().setFolderPanelToolbar(newFactory.createFolderPanelToolbar());
569           }
570         }
571       }, "Pooka.guiType");
572
573     mPookaManager.getResources().addValueChangeListener(new net.suberic.util.ValueChangeListener() {
574         public void valueChanged(String JavaDoc changedValue) {
575           PookaUIFactory factory = Pooka.getUIFactory();
576           IconManager iconManager = IconManager.getIconManager(Pooka.getResources(), "IconManager._default");
577           factory.setIconManager(iconManager);
578           factory.setEditorFactory(new PropertyEditorFactory(Pooka.getResources(), iconManager, Pooka.getPookaManager().getHelpBroker()));
579         }
580       }, "IconManager._default");
581
582     mPookaManager.getResources().addValueChangeListener(new net.suberic.util.ValueChangeListener() {
583         public void valueChanged(String JavaDoc changedValue) {
584           try {
585             UIManager.setLookAndFeel(Pooka.getProperty("Pooka.looknfeel", UIManager.getCrossPlatformLookAndFeelClassName()));
586             javax.swing.SwingUtilities.updateComponentTreeUI(javax.swing.SwingUtilities.windowForComponent(Pooka.getMainPanel()));
587           } catch (Exception JavaDoc e) {
588             System.out.println("Cannot set look and feel..."); }
589         }
590       }, "Pooka.looknfeel");
591
592     updateTime("created resource listeners");
593
594     // create the MessageListener.
595
if (mPookaManager.getMessageListener() == null) {
596       PookaMessageListener pmlistener= new PookaMessageListener();
597       mPookaManager.setMessageListener(pmlistener);
598     }
599
600     /*
601       mFrame = new JFrame("Pooka");
602       updateTime("created frame");
603     */

604
605     mPookaManager.setDefaultAuthenticator(new SimpleAuthenticator());
606     java.util.Properties JavaDoc sysProps = System.getProperties();
607     sysProps.setProperty("mail.mbox.mailspool", mPookaManager.getResources().getProperty("Pooka.spoolDir", "/var/spool/mail"));
608     mPookaManager.setDefaultSession (javax.mail.Session.getDefaultInstance(sysProps, mPookaManager.getDefaultAuthenticator()));
609     if (Pooka.getProperty("Pooka.sessionDebug", "false").equalsIgnoreCase("true"))
610       mPookaManager.getDefaultSession().setDebug(true);
611
612     updateTime("created session.");
613     if (startup != null)
614       startup.setStatus("Pooka.startup.mailboxInfo");
615     mPookaManager.setStoreManager(new StoreManager());
616     updateTime("created store manager.");
617
618     mPookaManager.getStoreManager().loadAllSentFolders();
619     mPookaManager.getOutgoingMailManager().loadOutboxFolders();
620     updateTime("loaded sent/outbox");
621
622   }
623
624   /**
625    * This parses any command line arguments, and makes the appropriate
626    * changes.
627    */

628   public void parseArgs(String JavaDoc[] argv) {
629     if (argv == null || argv.length < 1)
630       return;
631
632     String JavaDoc mailAddress = null;
633     String JavaDoc selectedProfile = null;
634
635     for (int i = 0; i < argv.length; i++) {
636       if (argv[i] != null) {
637         if (argv[i].equals("-nf") || argv[i].equals("--noOpenSavedFolders")) {
638           mOpenFolders = false;
639         } else if (argv[i].equals("-rc") || argv[i].equals("--rcfile")) {
640           String JavaDoc filename = argv[++i];
641           if (filename == null) {
642             System.err.println("error: no startup file specified.");
643             printUsage();
644             System.exit(-1);
645           }
646
647           mPookaManager.setLocalrc(filename);
648         } else if (argv[i].equals("--http")) {
649           mUseHttp = true;
650           mUseLocalFiles = false;
651         } else if (argv[i].equals("-open")) {
652           if (argv.length < i + 2) {
653             System.err.println("error: no address specified.");
654             printUsage();
655             System.exit(-1);
656           }
657           mToAddress = argv[++i];
658           mFullStartup = false;
659         } else if (argv[i].equals("--minimal")) {
660           mFullStartup = false;
661         } else if (argv[i].equals("--from")) {
662           mFromProfile = argv[++i];
663           if (mFromProfile == null) {
664             System.err.println("error: no from profile specified.");
665             printUsage();
666             System.exit(-1);
667           }
668           mFullStartup = false;
669         } else if (argv[i].equals("--help")) {
670           printUsage();
671           System.exit(0);
672         } else {
673           // if invalid arguments are specified
674
printUsage();
675           System.exit(0);
676         }
677       }
678     }
679   }
680
681   /**
682    * Prints the usage information.
683    */

684   public void printUsage() {
685     System.out.println(Pooka.getProperty("info.startup.help", "\nUsage: net.suberic.pooka.Pooka [OPTIONS]\n\n -nf, --noOpenSavedFolders don't open saved folders on startup.\n -rc, --rcfile FILE use the given file as the pooka startup file.\n --http runs with a configuration file loaded via http\n -open ADDRESS sends a new message to ADDRESS.\n [--from USER] [from user USER].\n --minimal startup to system tray only.\n --help shows these options.\n"));
686   }
687
688   /**
689    * Checks to make sure that the Java version is valid.
690    */

691   public boolean checkJavaVersion() {
692     // Pooka 1.1 only runs on JDK 1.4 or higher.
693
String JavaDoc javaVersion = System.getProperty("java.version");
694     if (javaVersion.compareTo("1.6") >= 0) {
695       return true;
696     } else {
697       return false;
698     }
699   }
700
701   /**
702    * Called if an incorrect version of Java is being used.
703    */

704   private void versionError() {
705     Runnable JavaDoc runMe = new Runnable JavaDoc() {
706         public void run() {
707           String JavaDoc errorString = Pooka.getProperty("error.incorrectJavaVersion", "Error running Pooka. This version (2.0) \nof Pooka requires a 1.6 JDK. \n\nFor JDK 1.4, please use a release of Pooka 1.1.\n\nPooka can be downloaded from\nhttp://pooka.sourceforge.net/\n\nYour JDK version: ");
708           javax.swing.JOptionPane.showMessageDialog(null, errorString + System.getProperty("java.version"));
709         }
710       };
711
712     if (SwingUtilities.isEventDispatchThread())
713       runMe.run();
714     else {
715       try {
716         SwingUtilities.invokeAndWait(runMe);
717       } catch (Exception JavaDoc ie) {
718       }
719     }
720   }
721
722   /**
723    * Sends a message to the given mail address on startup.
724    */

725   public boolean sendMessageTo(String JavaDoc pAddress, String JavaDoc pProfile) {
726     // first see if there's already a pooka instance running.
727
net.suberic.pooka.messaging.PookaMessageSender sender = new net.suberic.pooka.messaging.PookaMessageSender();
728     try {
729       sender.openConnection();
730       // check to make sure that we're connected to a correct version of Pooka.
731
if (sender.checkVersion()) {
732         sender.openNewEmail(pAddress, pProfile);
733       } else
734         return false;
735     } catch (Exception JavaDoc e) {
736       return false;
737     } finally {
738       if (sender.isConnected())
739         sender.closeConnection();
740     }
741
742     mToAddress = null;
743     mFromProfile = null;
744
745     return true;
746   }
747
748   private long mStartTime = 0;
749   private long mLastUpdate = 0;
750   /**
751    * debug.
752    */

753   public void updateTime(String JavaDoc message) {
754     if (mPookaManager.getResources() != null && Pooka.isDebug()) {
755       long current = System.currentTimeMillis();
756       System.err.println(message + ", time " + (current - mLastUpdate) + ", total " + (current - mStartTime));
757       mLastUpdate = current;
758     }
759   }
760
761   /**
762    * Returns true if we're in the process of shutting down.
763    */

764   public boolean isShuttingDown() {
765     return mShuttingDown;
766   }
767
768   /**
769    * Gets the logger for this class.
770    */

771   public Logger getLogger() {
772     return Logger.getLogger("Pooka.debug.startupManager");
773   }
774
775 }
776
Popular Tags