KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > entray > EnTray


1 /* EnTray.java */
2
3 package org.enhydra.entray;
4
5 import java.util.ResourceBundle JavaDoc;
6 import java.util.StringTokenizer JavaDoc;
7 import java.util.Hashtable JavaDoc;
8 import java.util.List JavaDoc;
9 import java.util.Enumeration JavaDoc;
10 import java.util.Vector JavaDoc;
11 import java.util.Locale JavaDoc;
12 import java.util.Properties JavaDoc;
13 import javax.swing.JFrame JavaDoc;
14 import javax.swing.JMenu JavaDoc;
15 import javax.swing.UIManager JavaDoc;
16 import java.awt.BorderLayout JavaDoc;
17 import java.awt.event.ActionEvent JavaDoc;
18 import java.awt.event.ActionListener JavaDoc;
19 import javax.swing.BoxLayout JavaDoc;
20 import javax.swing.JLabel JavaDoc;
21 import javax.swing.JPanel JavaDoc;
22 import javax.swing.JOptionPane JavaDoc;
23 import javax.swing.JFileChooser JavaDoc;
24 import javax.swing.ImageIcon JavaDoc;
25 import javax.swing.JTextArea JavaDoc;
26
27 import javax.management.*;
28 import javax.management.remote.*;
29
30
31 import snoozesoft.systray4j.*;
32
33 import java.io.*;
34
35 import java.rmi.*;
36 import java.rmi.server.*;
37 import java.rmi.registry.*;
38
39 /**
40  * Implementation of EnTray, based on Snoozesoft's systray4j.
41  *
42  * @author Vladimir Puskas
43  * @version 0.41
44  */

45 public class EnTray implements SysTrayMenuListener {
46     public static final String JavaDoc msgText[] = {
47     " EnTray",
48     " version 6.4",
49     " ",
50     " Enhydra Enterprise Server service manager",
51     " ",
52     " ",
53     " Uses MX4J and SysTray."
54     };
55     public static final String JavaDoc APP_NAME = "enhydra.systray";
56     public static final String JavaDoc PROPERTY_FILE = "entray";
57     public static final String JavaDoc SERVICE_NAMES_KEY = "servicenames";
58
59     public static final String JavaDoc NAMING_PROVIDER_HOST = "naming.provider.host";
60     public static final String JavaDoc NAMING_PROVIDER_PORT = "naming.provider.port";
61
62     public static final String JavaDoc ICON_WHITE = "otterWhite";
63     public static final String JavaDoc ICON_YELLOW = "otterYellow";
64     public static final String JavaDoc ICON_RUNNING = "icon.running";
65     public static final String JavaDoc DEFAULT_ICON_RUNNING = "otterGreen";
66     public static final String JavaDoc MESSAGE_RUNNING = "message.running";
67     public static final String JavaDoc DEFAULT_MESSAGE_RUNNING = "running";
68     public static final String JavaDoc ICON_STOPPED = "icon.stopped";
69     public static final String JavaDoc DEFAULT_ICON_STOPPED = "otterRed";
70     public static final String JavaDoc MESSAGE_STOPPED = "message.stopped";
71     public static final String JavaDoc DEFAULT_MESSAGE_STOPPED = "stopped";
72     public static final String JavaDoc ICON_STARTING = "icon.starting";
73     public static final String JavaDoc DEFAULT_ICON_STARTING = "otterGreenNose";
74     public static final String JavaDoc MESSAGE_STARTING = "message.starting";
75     public static final String JavaDoc DEFAULT_MESSAGE_STARTING = "starting";
76     public static final String JavaDoc ICON_STOPPING = "icon.stopping";
77     public static final String JavaDoc DEFAULT_ICON_STOPPING = "otterRedNose";
78     public static final String JavaDoc MESSAGE_STOPPING = "message.stopping";
79     public static final String JavaDoc DEFAULT_MESSAGE_STOPPING = "stopping";
80     public static final String JavaDoc START_COMMAND = ".cmd.start";
81     public static final String JavaDoc STOP_COMMAND = ".cmd.stop";
82     
83     public static final String JavaDoc USERNAME = ".username";
84     public static final String JavaDoc PASSWORD = ".password";
85     public static final String JavaDoc DEFAULT_USERNAME = "admin";
86     public static final String JavaDoc DEFAULT_PASSWORD = "enhydra";
87     public static final String JavaDoc PORT = ".port";
88     public static final String JavaDoc DEFAULT_PORT = "9000";
89     
90     public static final String JavaDoc HOST = ".host";
91     public static final String JavaDoc DEFAULT_HOST = "localhost";
92
93     /**
94      * Method getPropertyString extracts values from property file
95      * loaded through getResourceBundle.
96      *
97      * @param key if null, value for APP_NAME will be extracted,
98      * otherwise key is appended to APP_NAME
99      * and value for resulting key is returned
100      * @return value of the property <i>key</i> or <b>null</b>
101      * @see #getResourceBundle
102      */

103     public static String JavaDoc getPropertyString(String JavaDoc key) {
104     if (null == key)
105         key = APP_NAME;
106     else
107         key = APP_NAME +"."+ key;
108     try {
109         return getResourceBundle().getString(key);
110     } catch(Throwable JavaDoc t) {
111         return null;
112     }
113     }
114
115     /**
116      * Uses <tt>getPropertyString</tt> to extract value from property file,
117      * then tokenizes it, to return array of Strings.
118      *
119      * @param key
120      * @return String array tokenized with "<b>,</b>" character
121      * @see #getPropertyString
122      */

123     public static String JavaDoc[] getPropertyStrings(String JavaDoc key) {
124     StringTokenizer JavaDoc tokenizer =
125         new StringTokenizer JavaDoc(getPropertyString(key),",");
126     if (tokenizer.countTokens()>0) {
127           String JavaDoc[] res=new String JavaDoc[tokenizer.countTokens()];
128           int i=0;
129           try{
130             while(tokenizer.hasMoreTokens()){
131               res[i++]=tokenizer.nextToken();
132             }
133           }
134           catch(Throwable JavaDoc t){
135             if(res.length!=i){
136               fatalError("Internal error - tokening.");
137             }
138           }
139           return res;
140         } else {
141           return null;
142         }
143     }
144
145     /**
146      * Internally checks if appropriate bundle object is created
147      * to return it, or creates and stores one.
148      *
149      * @return ResourceBundle created from <tt>PROPERTY_FILE</tt>
150      */

151     private static ResourceBundle JavaDoc getResourceBundle() {
152     if (null == rb) {
153       try{
154             rb = ResourceBundle.getBundle(PROPERTY_FILE,new Locale JavaDoc("en","US"), ClassLoader.getSystemClassLoader());
155     } catch (Exception JavaDoc e){
156         //e.printStackTrace();
157
}
158     }
159     return rb;
160     }
161     private static ResourceBundle JavaDoc rb = null;
162     private String JavaDoc rootPath = null;
163
164     /**
165      * Hmm. I don't know...
166      *
167      * @param argv
168      */

169     public static void main(String JavaDoc[]argv) {
170       System.setProperty("java.naming.factory.initial","com.sun.jndi.rmi.registry.RegistryContextFactory");
171       //System.setProperty("jmx.serial.form", "1.1");
172

173       try {
174             UIManager.setLookAndFeel
175             (UIManager.getSystemLookAndFeelClassName());
176         } catch( Exception JavaDoc e ) {}
177
178         try {
179             new EnTray().show();
180         } catch(Throwable JavaDoc t) {
181             System.exit(-1);
182         }
183
184     }
185
186     private SysTrayMenuIcon mainIcon = null;
187     private SysTrayMenu mainMenu = null;
188     private Vector JavaDoc vecServices = new Vector JavaDoc();
189
190     /**
191      *
192      */

193     public void show() {
194     //initialize property rootPath used for checking Enhydras presence (if uninstalled)
195
rootPath = getPropertyString("root");
196
197     String JavaDoc[]serviceNames = getPropertyStrings(SERVICE_NAMES_KEY);
198
199     if (null != serviceNames && serviceNames.length > 0) {
200         if (null != mainIcon) {
201             mainIcon.removeSysTrayMenuListener(this);
202             mainIcon = null;
203             mainMenu = null;
204         }
205         if (serviceNames.length > 1) {
206             try{
207                 // multiple service mode
208
mainIcon =new SysTrayMenuIcon
209                     (getClass().getResource
210                      (ICON_WHITE + SysTrayMenuIcon.getExtension()));
211                 mainMenu = new SysTrayMenu(mainIcon);
212                 for(int i=0; i < serviceNames.length; i++) {
213
214                     SystemService ss = new SystemService(serviceNames[i],this);
215                     vecServices.add(ss);
216                     mainMenu.addItem(ss.getSubMenu());
217                     ss.isRunning();
218                 }
219                 mainMenu.addSeparator(0);
220                 mainMenu.addItem(new SysTrayMenuItem("START ALL") {
221                     protected void fireMenuItemSelected() {
222                         changeAll(false);
223                     }
224                     }, 0);
225                 mainMenu.addItem(new SysTrayMenuItem("STOP ALL") {
226                     protected void fireMenuItemSelected() {
227                         changeAll(true);
228                     }
229                     }, 0);
230                 mainMenu.addItem(new SysTrayMenuItem("Exit") {
231                     protected void fireMenuItemSelected() {
232                         System.exit(0);
233                     }
234                     }, 0);
235                 mainMenu.addSeparator(0);
236                 mainMenu.addItem(new SysTrayMenuItem("Add Enhydra Service") {
237                     protected void fireMenuItemSelected() {
238                         showAddServiceDialog();
239                     }
240                 },0);
241                 mainMenu.addSeparator(0);
242                 mainMenu.addItem(new SysTrayMenuItem("Enhydra Quick Start") {
243                     protected void fireMenuItemSelected() {
244                         showQuickStart();
245                     }
246                 },0);
247                                 mainMenu.addItem(new SysTrayMenuItem("About") {
248                     protected void fireMenuItemSelected() {
249                         showAboutDialog();
250                     }
251                 },0);
252                 String JavaDoc test = "Entray (" + this.rootPath + ") - multiservice mode";
253                 if (test.length()<65){
254                      mainMenu.setToolTip(test);
255                   } else {
256                      mainMenu.setToolTip("Entray - multiservice mode");
257                   }
258             }catch(Exception JavaDoc e){
259             }
260         }
261         else if (serviceNames.length == 1) {
262             // single service mode
263
mainIcon =new SysTrayMenuIcon
264                 (getClass().getResource
265                  (ICON_YELLOW +SysTrayMenuIcon.getExtension()));
266             SystemService ss = new SystemService(serviceNames[0], this);
267             vecServices.add(ss);
268             mainMenu = ss.getMenu(mainIcon);
269             String JavaDoc test = "EnTray (" + this.rootPath + ") - service " + ss.name;
270             if (test.length()<65){
271                mainMenu.setToolTip(test);
272             } else {
273                mainMenu.setToolTip("EnTray - service " + ss.name);
274             }
275         }
276         mainIcon.addSysTrayMenuListener(this);
277         
278         new Thread JavaDoc() {
279             int [] st = new int [vecServices.size()];
280             
281             public void run() {
282             for (int i=0; i<st.length; i++){
283             st[i]=0;
284             }
285                 while(true) {
286                 // wait
287
try {sleep(1977);} catch(Throwable JavaDoc t) {}
288                     // check status of services
289
st = checkStatus(st);
290                 }
291             }
292         }.start();
293     }
294   }
295   boolean once = true;
296
297   //checks Enhydra presence (if uninstalled)
298
private boolean checkEnhydraPresence(){
299     try {
300         String JavaDoc fileName = this.rootPath+File.separator+"conf"+File.separator+"entray.show";
301         File testFile = new File (fileName);
302         boolean test1 = testFile.exists();
303         fileName = this.rootPath+File.separator+"conf"+File.separator+"entray.installed";
304         testFile = new File (fileName);
305         boolean test2 = testFile.exists();
306         return (test1 && test2);
307     } catch (Exception JavaDoc ex) {
308         return false;
309     }
310   }
311
312   int [] checkStatus(int [] old) {
313     //if Enhydra is uninstalled then exit
314
if (!checkEnhydraPresence()){
315         System.exit(-1);
316     }
317     int [] stat = new int [vecServices.size()];
318     for (int i=0; i<stat.length; i++){
319         stat[i]=3;
320     }
321     int k = 0;
322     for (Enumeration JavaDoc e = vecServices.elements(); e.hasMoreElements();) {
323         SystemService ss = (SystemService)e.nextElement();
324         stat[k] &= ss.isRunning();
325         k++;
326     }
327
328     k = 0;
329     int j = 0;
330     for (int i=0; i<stat.length; i++){
331         if (stat[i]!=old[i]){
332             k++;
333         }
334         if (stat[i]==3){
335             j++;
336         }
337     }
338     if ((k != 0)||once) {
339         String JavaDoc entrayIcon = ICON_YELLOW;
340         try {
341             if (j == 0){
342                 entrayIcon = DEFAULT_ICON_STOPPED;
343                 mainMenu.getItem("STOP ALL").setEnabled(false);
344                 mainMenu.getItem("START ALL").setEnabled(true);
345             } else if (j == stat.length) {
346                 entrayIcon = DEFAULT_ICON_RUNNING;
347                 mainMenu.getItem("START ALL").setEnabled(false);
348                 mainMenu.getItem("STOP ALL").setEnabled(true);
349             } else {
350                 mainMenu.getItem("START ALL").setEnabled(true);
351                 mainMenu.getItem("STOP ALL").setEnabled(true);
352             }
353         } catch (Exception JavaDoc e){}
354         mainIcon = new SysTrayMenuIcon
355         (getClass().getResource
356          (entrayIcon + SysTrayMenuIcon.getExtension()));
357         mainMenu.setIcon(mainIcon);
358         mainIcon.addSysTrayMenuListener(this);
359         once = false;
360     }
361     //once =((0 == stat)||(3 == stat));
362
return stat;
363   }
364
365     /**
366      * Does nothing
367      * @param e ignored
368      */

369     public void menuItemSelected(SysTrayMenuEvent e) {}
370
371     /**
372      * Displays about message box.
373      */

374     public void showAboutDialog() {
375         JPanel JavaDoc message = new JPanel JavaDoc(new BorderLayout JavaDoc());
376         message.add(new JLabel JavaDoc(new ImageIcon JavaDoc
377                        (getClass().getResource
378                     ("Together.gif"))), BorderLayout.WEST);
379         JPanel JavaDoc text = new JPanel JavaDoc();
380         text.setLayout(new BoxLayout JavaDoc(text, BoxLayout.Y_AXIS));
381         for(int i = 0; i < msgText.length; ++i) {
382             text.add(new JLabel JavaDoc(msgText[i]));
383         }
384         message.add(text, BorderLayout.EAST);
385         JOptionPane.showMessageDialog(null,message,"About EnTray",JOptionPane.PLAIN_MESSAGE);
386     }
387
388     /**
389      * Starts Enhydra_quick_start.html page.
390      */

391     public void showQuickStart() {
392         String JavaDoc cmdPrefix = "cmd /c start ";
393         if ('/' == java.io.File.separatorChar) {
394             cmdPrefix = "kfmclient exec ";
395         }
396         String JavaDoc fileName = this.rootPath+java.io.File.separatorChar+".."+java.io.File.separatorChar
397                       +"multiserver"+java.io.File.separatorChar+"enhydra"+java.io.File.separatorChar
398                       +"doc"+java.io.File.separatorChar+"Enhydra_quick_start.html";
399          File testFile = new File (fileName);
400          boolean test = testFile.exists();
401          
402          try {
403            fileName = testFile.getCanonicalPath();
404          }catch (IOException ex){}
405          
406         if (test){
407         try {
408             Runtime.getRuntime().exec(cmdPrefix + fileName);
409         } catch(Throwable JavaDoc t) {}
410      }else {
411           JOptionPane.showMessageDialog(null, "Unable to find "+fileName+" document", "EnTray - Error",
412                                         JOptionPane.ERROR_MESSAGE);
413         }
414
415     }
416
417     /**
418      * Displays Add service dialog box.
419      */

420     public void showAddServiceDialog() {
421         JFileChooser JavaDoc chooser = new JFileChooser JavaDoc();
422         chooser.setDialogTitle("Choose Enhydra Server Root!!!");
423         int temp = chooser.DIRECTORIES_ONLY;
424         chooser.setFileSelectionMode(temp);
425         int returnVal = chooser.showOpenDialog(null);
426         if(returnVal == JFileChooser.APPROVE_OPTION) {
427             try{
428                 String JavaDoc fileName = chooser.getSelectedFile().getAbsolutePath()+File.separator+"conf"+File.separator+"entray.properties";
429                 File propertyFile = new File (fileName);
430                 boolean test = propertyFile.exists();
431                 if (!test){
432                     JOptionPane.showMessageDialog(null, "Invalid Enhydra (Multi)Server Directory", "EnTray - Error",
433                                         JOptionPane.ERROR_MESSAGE);
434                 } else {
435                     addService(propertyFile);
436                 }
437             }catch (Exception JavaDoc e) {
438                 JOptionPane.showMessageDialog(null, "Invalid Enhydra (Multi)Server Directory", "EnTray - Error",
439                                         JOptionPane.ERROR_MESSAGE);
440             }
441         }
442     }
443
444     private void addService(File propertyFile) {
445
446       try{
447         Properties JavaDoc enTrayProperies=new Properties JavaDoc();
448         FileInputStream inTempStream=new FileInputStream(propertyFile);
449         enTrayProperies.load(inTempStream);
450         inTempStream.close();
451
452         String JavaDoc newServiceNames = enTrayProperies.getProperty("enhydra.systray.servicenames");
453         StringTokenizer JavaDoc newTokenizer = new StringTokenizer JavaDoc(newServiceNames,",");
454         String JavaDoc[] newNames = new String JavaDoc[newTokenizer.countTokens()];
455         int i = 0;
456         try {
457             while(newTokenizer.hasMoreTokens()) {
458                 newNames[i++] = newTokenizer.nextToken();
459             }
460         } catch(Throwable JavaDoc t) {
461             if (newNames.length != i) {
462                 fatalError("Internal error - tokening.");
463             }
464         }
465
466         String JavaDoc fileName = rootPath + File.separator + "conf" + File.separator + "entray.properties";
467         propertyFile = new File (fileName);
468         FileInputStream inStream=new FileInputStream(propertyFile);
469         enTrayProperies.load(inStream);
470         inStream.close();
471
472         //part that inits enhydra.systray.servicenames property value in the
473
//way that does not allows existance of two services with the same name
474
String JavaDoc oldServiceNames = enTrayProperies.getProperty("enhydra.systray.servicenames");
475         StringTokenizer JavaDoc oldTokenizer = new StringTokenizer JavaDoc(oldServiceNames,",");
476         String JavaDoc[] oldNames = new String JavaDoc[oldTokenizer.countTokens()];
477         i = 0;
478         try {
479             while(oldTokenizer.hasMoreTokens()) {
480                 oldNames[i++] = oldTokenizer.nextToken();
481             }
482         } catch(Throwable JavaDoc t) {
483             if (oldNames.length != i) {
484                 fatalError("Internal error - tokening.");
485             }
486         }
487         String JavaDoc finallServiceNames = "";
488         boolean found = false;
489         for (i=0;i<newNames.length;i++) {
490           for (int j=0;j<oldNames.length;j++){
491             if (oldNames[j].equals(newNames[i])) {
492               found = true;
493             }
494           }
495           if (!found){
496             finallServiceNames = finallServiceNames + "," + newNames[i];
497           } else {
498             found = false;
499           }
500         }
501         for (i=0;i<oldNames.length;i++){
502           finallServiceNames = finallServiceNames + "," + oldNames[i];
503         }
504         enTrayProperies.setProperty("enhydra.systray.servicenames",finallServiceNames.substring(1));
505         //end of the enhydra.systray.servicenames parameter initialization
506

507         FileOutputStream outStream=new FileOutputStream(propertyFile);
508         enTrayProperies.store(outStream, "File edited by EnTray!!!");
509         outStream.close();
510         restartEnTray();
511       }catch(Exception JavaDoc ex){
512         JOptionPane.showMessageDialog(null, "Invalid EnTray Root - check conf/entray.property file", "EnTray - Error",
513                                         JOptionPane.ERROR_MESSAGE);
514       }
515     }
516
517     private void removeService(String JavaDoc name){
518       try{
519               String JavaDoc fileName = rootPath + File.separator + "conf" + File.separator + "entray.properties";
520               File propertyFile = new File (fileName);
521               FileInputStream inStream=new FileInputStream(propertyFile);
522               Properties JavaDoc enTrayProperies = new Properties JavaDoc();
523               enTrayProperies.load(inStream);
524               inStream.close();
525
526               //start of the enhydra.systray.servicenames parameter initialization
527
String JavaDoc oldServiceNames = enTrayProperies.getProperty("enhydra.systray.servicenames");
528               StringTokenizer JavaDoc oldTokenizer = new StringTokenizer JavaDoc(oldServiceNames,",");
529               String JavaDoc[] oldNames = new String JavaDoc[oldTokenizer.countTokens()];
530               int i = 0;
531               try {
532                   while(oldTokenizer.hasMoreTokens()) {
533                       oldNames[i++] = oldTokenizer.nextToken();
534                   }
535               } catch(Throwable JavaDoc t) {
536                   if (oldNames.length != i) {
537                       fatalError("Internal error - tokening.");
538                   }
539               }
540               String JavaDoc finallServiceNames = "";
541               for (i=0;i<oldNames.length;i++) {
542                 if (!name.equals(oldNames[i])){
543                   finallServiceNames = finallServiceNames + "," + oldNames[i];
544                 }
545               }
546               if (!finallServiceNames.equals("")){
547                 enTrayProperies.setProperty("enhydra.systray.servicenames",finallServiceNames.substring(1));
548               } else {
549                 enTrayProperies.setProperty("enhydra.systray.servicenames",finallServiceNames);
550               }
551               //end of the enhydra.systray.servicenames parameter initialization
552

553               //removing other service options
554
for (Enumeration JavaDoc props = enTrayProperies.propertyNames(); props.hasMoreElements();) {
555                 String JavaDoc prop = (String JavaDoc) props.nextElement();
556                 if (prop.equals("enhydra.systray." + name + ".cmd.start")){
557                   enTrayProperies.remove(prop);
558                 } else if (prop.equals("enhydra.systray." + name + ".cmd.stop")){
559                   enTrayProperies.remove(prop);
560                 } else if (prop.equals("enhydra.systray." + name + ".namingport")){
561                   enTrayProperies.remove(prop);
562                 } else if (prop.equals("enhydra.systray." + name + ".port")){
563                   enTrayProperies.remove(prop);
564                 }
565               }
566
567
568               FileOutputStream outStream=new FileOutputStream(propertyFile);
569               enTrayProperies.store(outStream, "File edited by EnTray!!!");
570               outStream.close();
571               restartEnTray();
572             }catch(Exception JavaDoc ex){
573               JOptionPane.showMessageDialog(null, "Invalid EnTray Root - check conf/entray.property file", "EnTray - Error",
574                                               JOptionPane.ERROR_MESSAGE);
575             }
576
577     }
578
579     private void restartEnTray(){
580       try {
581             String JavaDoc cmdEnTray = rootPath + File.separator + "bin" + File.separator + "entray.bat start";
582             if ('/' == java.io.File.separatorChar) {
583               cmdEnTray = rootPath + File.separator + "bin" + File.separator + "entray.sh start";
584             }
585             Runtime.getRuntime().exec(cmdEnTray);
586             System.exit(0);
587         } catch(Throwable JavaDoc t) {
588             JOptionPane.showMessageDialog(null, "Error Ocurred - Please restart EnTray manualy!", "EnTray - Error",
589                                               JOptionPane.ERROR_MESSAGE);
590             System.exit(-1);
591         }
592     }
593
594     /**
595      * Refresh of service application list(s)
596      * @param e ignored
597      */

598     public void iconLeftClicked(SysTrayMenuEvent e) {
599         for (Enumeration JavaDoc enumeration = vecServices.elements(); enumeration.hasMoreElements();) {
600             SystemService ss = (SystemService)enumeration.nextElement();
601             ss.addEntries();
602         }
603     }
604     
605     
606     /**
607      * Displays Enhydra Quick Start Document.
608      * @param stme ignored
609      */

610     public void iconLeftDoubleClicked(SysTrayMenuEvent stme) {
611         showQuickStart();
612     }
613
614     /**
615      * Sets adequate menu icon depending on EnTray state (start/stop)
616      *
617      * @param stop
618      */

619     public void setIcon(boolean stop) {
620         if (null != mainIcon) {
621             mainIcon.removeSysTrayMenuListener(this);
622         }
623         mainIcon = new SysTrayMenuIcon
624             (getClass().getResource
625              ((stop?DEFAULT_ICON_STOPPING:DEFAULT_ICON_STARTING)
626               + SysTrayMenuIcon.getExtension()));
627         if (null != mainMenu)
628             mainMenu.setIcon(mainIcon);
629         mainIcon.addSysTrayMenuListener(this);
630     }
631
632     /**
633      * Changes states for all services (toggles them all) depending
634      * on input parameter value (stoping or starting all services)
635      *
636      * @param stop
637      */

638     void changeAll(boolean stop) {
639         setIcon(stop);
640         for (Enumeration JavaDoc e = vecServices.elements(); e.hasMoreElements();) {
641             SystemService ss = (SystemService)e.nextElement();
642             boolean runn = (ss.isRunning()==3);
643             if (stop && runn) {
644                 ss.stop();
645             } else if (!stop && !runn) {
646                 ss.start();
647             }
648         }
649     }
650
651     /**
652      * Used for Multiservice work mode and implements DoubleClick action.
653      * Changes states for all services (toggles them all)
654      */

655     void changeAll() {
656         if (null != mainIcon) {
657             mainIcon.removeSysTrayMenuListener(this);
658         }
659         mainIcon = new SysTrayMenuIcon
660             (getClass().getResource
661              (ICON_WHITE + SysTrayMenuIcon.getExtension()));
662         if (null != mainMenu)
663             mainMenu.setIcon(mainIcon);
664         mainIcon.addSysTrayMenuListener(this);
665         for (Enumeration JavaDoc e = vecServices.elements(); e.hasMoreElements();) {
666             SystemService ss = (SystemService)e.nextElement();
667             boolean runn = (ss.isRunning()==3);
668             if (runn) {
669                 ss.removeEntries();
670                 ss.exec(ss.stopCommand);
671             } else {
672                 ss.removeEntries();
673                 ss.exec(ss.startCommand);
674             }
675         }
676     }
677
678     private static void fatalError(String JavaDoc message) {
679         throw new RuntimeException JavaDoc("Oops! "+ message);
680     }
681
682     /**
683      * Static class used for registering EnTray as RMI service.
684      * Purpose is to disable multiple instances at runtime!
685      */

686     static class EnTrayReg extends UnicastRemoteObject implements Remote {
687        private String JavaDoc message;
688        public EnTrayReg() throws RemoteException {
689         super();
690        }
691
692        public void setMessage(String JavaDoc string) {
693         message = string;
694        }
695
696        public String JavaDoc getMessage() {
697         return message;
698        }
699     }
700
701     /**
702      *
703      */

704     class SystemService {
705     /**
706      * Constructs an instance of service based on name.
707      * All parameters are either read from property file or set
708      * to default values.
709      */

710     SystemService(String JavaDoc sName, EnTray entray) {
711         name = sName;
712         tray = entray;
713
714         startCommand = getPropertyString(name + START_COMMAND);
715         stopCommand = getPropertyString(name + STOP_COMMAND);
716         
717         namingProviderPort = getPropertyString(name + ".namingport");
718         if (null == namingProviderPort) {
719             namingProviderPort = "1099";
720         }
721
722         if (null == startCommand || null == stopCommand) {
723         fatalError("Both "+ APP_NAME +"."+ name + START_COMMAND
724                +" and "+ APP_NAME +"."+ name + STOP_COMMAND
725                +" must be defined.");
726         }
727         table = new Hashtable JavaDoc();
728         stm = null;
729         sm = null;
730         readProperties();
731     }
732     private String JavaDoc name;
733     private String JavaDoc serverName;
734     private Hashtable JavaDoc table;
735     SysTrayMenu stm;
736     SubMenu sm;
737     EnTray tray;
738
739     public SysTrayMenu getMenu(SysTrayMenuIcon stmi) {
740         if (null != stm) {
741         stm.removeAll();
742         }
743         stm = new SysTrayMenu(stmi);
744         addEntries();
745         return stm;
746     }
747
748     public SubMenu getSubMenu() {
749         if (null != sm) {
750         sm.removeAll();
751         }
752         sm = new SubMenu(name);
753         addEntries();
754         return sm;
755     }
756
757     private void removeEntries() {
758       if ((null == stm)&&(null == sm))
759           fatalError("Internal error.");
760     else if (null != stm){
761           stm.removeAll();
762     } else {
763             sm.removeAll();
764       }
765   }
766
767     private void addEntries() {
768         removeEntries();
769         boolean intoMenu = (null != stm);
770         String JavaDoc sORs = "Stop "+ name;
771         JMXConnector connector = null;
772         try {
773         // The JMXConnectorServer protocol
774
String JavaDoc serverProtocol = "rmi";
775       
776             // The RMI server's host
777
String JavaDoc serverHost = "localhost";
778       
779             // The path where the rmiregistry runs.
780
String JavaDoc jndiPath = "jrmpconnector_" + name;
781             
782             System.setProperty("java.naming.provider.url","rmi://" + serverHost + ":"+ namingProviderPort);
783             
784             // The address of the connector server
785
//JMXServiceURL url = new JMXServiceURL("service:jmx:" + serverProtocol + "://" + serverHost + ":" + namingProviderPort + "/jndi/" + jndiPath);
786
JMXServiceURL url = new JMXServiceURL("service:jmx:" + serverProtocol + "://" + serverHost + "/jndi/" + jndiPath);
787       
788             // Connect a JSR 160 JMXConnector to the server side
789
connector = JMXConnectorFactory.connect(url);
790       
791             // Retrieve an MBeanServerConnection that represent the MBeanServer the remote
792
// connector server is bound to
793
MBeanServerConnection connection = connector.getMBeanServerConnection();
794
795         
796       if("Jetty".equals(serverName))
797      {
798       
799             ObjectName oName = new ObjectName(name + ":type=service,name=webContainers");
800             List JavaDoc dWars = null;
801             dWars = (List JavaDoc)connection.getAttribute(oName,"DeployedWars");
802             for (int i = dWars.size(); i > 0;) {
803                 String JavaDoc warPath = ((String JavaDoc) dWars.get(--i)).replace(':','|');
804                   ObjectName war = new ObjectName(name + ":type=war,fname="+ warPath);
805                 String JavaDoc context = (String JavaDoc) connection.getAttribute(war,"ContextRoot");
806                 context = context.startsWith("/")?context:"/"+context;
807                 
808                 String JavaDoc path = getWarName(warPath);
809                 String JavaDoc appUrl = "";
810                 if ("".equals(context)){
811                     context = "ROOT";
812                     appUrl = "http"+"://localhost:"+port+"/";
813                 } else {
814                     appUrl = "http"+"://localhost:"+port+"/"+path+"/";
815                 }
816        
817                 
818                 table.put(path, appUrl);
819                 SysTrayMenuItem stmi = new SysTrayMenuItem(path) {
820                                      protected void fireMenuItemSelected() {
821                                       startBrowser(getLabel());
822                                      }
823                                     };
824         
825                                  if (intoMenu)
826                                    stm.addItem(stmi);
827                                 else
828                                    sm.addItem(stmi);
829          
830                 }
831               
832             running = 3;
833       }
834      else if("Apache Tomcat".equals(serverName))
835      {
836         try{
837             ObjectName oName = new ObjectName("*:type=Engine");
838             java.util.Set JavaDoc mEngines = (java.util.Set JavaDoc)connection.queryNames(oName, null);
839             java.util.Iterator JavaDoc engineIterator = mEngines.iterator();
840             for (int i=0; i<mEngines.size();i++){
841                 ObjectName tempEngine = (ObjectName)engineIterator.next();
842                 oName = new ObjectName(tempEngine.getDomain()+":type=Connector,*");
843                 java.util.Set JavaDoc mConnectors = (java.util.Set JavaDoc)connection.queryNames(oName, null);
844                 java.util.Iterator JavaDoc connectorIterator = mConnectors.iterator();
845                 for (int j=0; j<mConnectors.size();j++){
846                     ObjectName tempConnector = (ObjectName)connectorIterator.next();
847                     while (!connection.isRegistered(tempConnector)){
848                         Thread.currentThread().sleep(100);
849                     }
850                     String JavaDoc connectorProtocol = null;
851                     connectorProtocol = (String JavaDoc)connection.getAttribute(tempConnector,"protocol");
852                     if ("HTTP/1.1".equals(connectorProtocol)){
853                         Integer JavaDoc connectorPort = (Integer JavaDoc)connection.getAttribute(tempConnector,"port");
854                         String JavaDoc connPort = connectorPort.toString();
855                         String JavaDoc scheme = (String JavaDoc) connection.getAttribute(tempConnector,"scheme");
856                         
857                         ObjectName tempMapper = new ObjectName(tempEngine.getDomain()+":type=Mapper,port="+connectorPort);
858                         while (!connection.isRegistered(tempMapper)){
859                             Thread.currentThread().sleep(100);
860                         }
861                         String JavaDoc [] dWars = null;
862                         dWars = (String JavaDoc [])connection.getAttribute(tempMapper,"contextNames");
863                         for (int k=dWars.length; k > 0; k--) {
864                                 int finSlash = ((String JavaDoc)dWars[k-1]).lastIndexOf("/");
865                                 String JavaDoc context = ((String JavaDoc) dWars[k-1]).substring(finSlash);
866                                 context = context.startsWith("/")?context.substring(1):context;
867                                 String JavaDoc appUrl = "";
868                                 if ("".equals(context)){
869                                     context = "ROOT";
870                                     appUrl = scheme+"://localhost:"+connPort+"/";
871                                 } else {
872                                     appUrl = scheme+"://localhost:"+connPort+"/"+context+"/";
873                                 }
874                                 context+=" ("+connPort+")";
875                                 table.put(context, appUrl);
876                                 SysTrayMenuItem stmi = new SysTrayMenuItem(context) {
877                                  protected void fireMenuItemSelected() {
878                                   startBrowser(getLabel());
879                                  }
880                                 };
881                                 if (intoMenu)
882                                   stm.addItem(stmi);
883                                 else
884                                  sm.addItem(stmi);
885                         }
886                         
887                     }
888                 }
889             }
890         
891             running = 3;
892           } catch (InstanceNotFoundException except){
893             running = 0;
894           }
895         }
896         
897         } catch(Throwable JavaDoc t) {
898             sORs = "Start "+ name;
899             running = 0;
900         } finally {
901             if (connector!=null){
902                 try {
903                     connector.close();
904                 } catch (Exception JavaDoc exept){}
905             }
906         }
907         if (sORs.startsWith("Stop")) {
908             if (intoMenu){
909                 stm.addSeparator(0);
910                 stm.addItem(new SysTrayMenuItem("Refresh Application List") {
911                     protected void fireMenuItemSelected() {
912                         addEntries();
913                     }
914                 },0);
915                 stm.addSeparator(0);
916             }else {
917                 sm.addSeparator(0);
918                 sm.addItem(new SysTrayMenuItem("Refresh Application List") {
919                     protected void fireMenuItemSelected() {
920                         addEntries();
921                     }
922                 },0);
923                 sm.addSeparator(0);
924             }
925         }
926         SysTrayMenuItem stmi = new SysTrayMenuItem(sORs) {
927             protected void fireMenuItemSelected() {
928                 toggleService();
929             }
930           };
931         SysTrayMenuItem stmir = new SysTrayMenuItem("Remove this EnTray service") {
932             protected void fireMenuItemSelected() {
933                 removeService(name);
934             }
935         };
936         if (intoMenu) {
937             stm.addItem(stmi, 0);
938             stm.addItem(new SysTrayMenuItem("Exit") {
939                     protected void fireMenuItemSelected() {
940                        System.exit(0);
941                     }
942                 },0);
943             stm.addSeparator(0);
944             stm.addItem(new SysTrayMenuItem("Add Enhydra Service") {
945                     protected void fireMenuItemSelected() {
946                         showAddServiceDialog();
947                     }
948                 },0);
949             stm.addSeparator(0);
950             stm.addItem(new SysTrayMenuItem("Enhydra Quick Start") {
951                     protected void fireMenuItemSelected() {
952                         showQuickStart();
953                     }
954                 },0);
955             stm.addItem(new SysTrayMenuItem("About") {
956                 protected void fireMenuItemSelected() {
957                     showAboutDialog();
958                 }
959             },0);
960         } else {
961             sm.addItem(stmi, 0);
962             sm.addSeparator(0);
963             sm.addItem(stmir, 0);
964         }
965     }
966
967     void toggleService() {
968         System.err.println("toggleService:"+running);
969         if (3 == running)
970             this.stop();
971         else if (0 == running)
972             this.start();
973     }
974
975     private int running = 0; /* 0 - stopped; 3 - running */
976
977     public int isRunning() {
978         int old = running;
979         //MBeanServerConnection connection = null;
980
JMXConnector connector = null;
981         try {
982
983             // The JMXConnectorServer protocol
984
String JavaDoc serverProtocol = "rmi";
985       
986             // The RMI server's host
987
String JavaDoc serverHost = "localhost";
988       
989             // The path where the rmiregistry runs.
990
String JavaDoc jndiPath = "jrmpconnector_" + name;
991             
992             System.setProperty("java.naming.provider.url","rmi://" + serverHost + ":"+ namingProviderPort);
993             
994             // The address of the connector server
995
//JMXServiceURL url = new JMXServiceURL("service:jmx:" + serverProtocol + "://" + serverHost + ":" + namingProviderPort + "/jndi/" + jndiPath);
996
JMXServiceURL url = new JMXServiceURL("service:jmx:" + serverProtocol + "://" + serverHost + "/jndi/" + jndiPath);
997       
998             // Connect a JSR 160 JMXConnector to the server side
999
connector = JMXConnectorFactory.connect(url);
1000            
1001            // Retrieve an MBeanServerConnection that represent the MBeanServer the remote
1002
// connector server is bound to
1003

1004            MBeanServerConnection connection = connector.getMBeanServerConnection();
1005            
1006            ObjectName oName = new ObjectName(name + ":type=service,name=webContainers");
1007  
1008            serverName = (String JavaDoc)connection.getAttribute(oName,"ServerName");
1009            List JavaDoc dWars = null;
1010            dWars = (List JavaDoc)connection.getAttribute(oName,"DeployedWars");
1011                
1012                running = 3;
1013        } catch(Throwable JavaDoc t) {
1014            running = 0;
1015        } finally {
1016            if (connector!=null){
1017                try {
1018                    connector.close();
1019                } catch (Exception JavaDoc exept){}
1020            }
1021        }
1022        //Slobodan Vujasinovic - needs revision
1023
if ((old != running)&&((0 == running)||(3 == running))) {
1024            addEntries();
1025        }
1026        return running;
1027    }
1028
1029    private void exec(String JavaDoc cmd) {
1030        String JavaDoc command = "cmd /c ";
1031        if ('/' == java.io.File.separatorChar) {
1032            command = "/bin/sh ";
1033        }
1034        try {
1035            Runtime.getRuntime().exec(command + cmd);
1036        } catch(Throwable JavaDoc t) {
1037            //t.printStackTrace();
1038
}
1039    }
1040
1041    void start() {
1042        setIcon(false);
1043        removeEntries();
1044        exec(startCommand);
1045    }
1046
1047    void stop() {
1048        setIcon(true);
1049        removeEntries();
1050        exec(stopCommand);
1051    }
1052
1053    void startBrowser(String JavaDoc s) {
1054        String JavaDoc cmdPrefix = "cmd /c start ";
1055        if ('/' == java.io.File.separatorChar) {
1056        cmdPrefix = "kfmclient exec ";
1057        }
1058        String JavaDoc url = (String JavaDoc)table.get(s);
1059        try {
1060            Runtime.getRuntime().exec(cmdPrefix+url);
1061        } catch(Throwable JavaDoc t) {}
1062    }
1063
1064    private String JavaDoc getWarName(String JavaDoc wp) {
1065      if (wp.endsWith(".war")){
1066        return wp.substring(wp.lastIndexOf('/')+ 1, wp.length() - 4);
1067      } else {
1068        File tempFile = new File(wp);
1069        return tempFile.getName();
1070      }
1071    }
1072
1073    private void readProperties() {
1074        String JavaDoc property;
1075        property = getPropertyString(MESSAGE_RUNNING);
1076        messageRunning = (null == property)?DEFAULT_MESSAGE_RUNNING:property;
1077        property = getPropertyString(MESSAGE_STOPPED);
1078        messageStopped = (null == property)?DEFAULT_MESSAGE_STOPPED:property;
1079        property = getPropertyString(MESSAGE_STARTING);
1080        messageStarting = (null == property)?DEFAULT_MESSAGE_STARTING:property;
1081        property = getPropertyString(MESSAGE_STOPPING);
1082        messageStopping = (null == property)?DEFAULT_MESSAGE_STOPPING:property;
1083                
1084        property = getPropertyString(name + USERNAME);
1085        username = (null == property)?DEFAULT_USERNAME:property;
1086        property = getPropertyString(name + PASSWORD);
1087        password = (null == property)?DEFAULT_PASSWORD:property;
1088        property = getPropertyString(name + PORT);
1089        port = (null == property)?DEFAULT_PORT:property;
1090        
1091        property = getPropertyString(name + HOST);
1092        host = (null == property)?DEFAULT_HOST:property;
1093
1094        property = getPropertyString(ICON_RUNNING);
1095        if (null == property)
1096        property = DEFAULT_ICON_RUNNING;
1097        iconRunning = new SysTrayMenuIcon
1098        (getClass().getResource
1099         (property + SysTrayMenuIcon.getExtension()));
1100        property = getPropertyString(ICON_STOPPED);
1101        if (null == property)
1102        property = DEFAULT_ICON_STOPPED;
1103        iconStopped = new SysTrayMenuIcon
1104        (getClass().getResource
1105         (property + SysTrayMenuIcon.getExtension()));
1106        property = getPropertyString(ICON_STARTING);
1107        if (null == property)
1108        property = DEFAULT_ICON_STARTING;
1109        iconStarting = new SysTrayMenuIcon
1110        (getClass().getResource
1111         (property + SysTrayMenuIcon.getExtension()));
1112        property = getPropertyString(ICON_STOPPING);
1113        if (null == property)
1114        property = DEFAULT_ICON_STOPPING;
1115        iconStopping = new SysTrayMenuIcon
1116        (getClass().getResource
1117         (property + SysTrayMenuIcon.getExtension()));
1118    }
1119    
1120    SysTrayMenuIcon iconRunning;
1121    SysTrayMenuIcon iconStopped;
1122    SysTrayMenuIcon iconStarting;
1123    SysTrayMenuIcon iconStopping;
1124
1125    String JavaDoc startCommand;
1126    String JavaDoc stopCommand;
1127    String JavaDoc messageRunning;
1128    String JavaDoc messageStopped;
1129    String JavaDoc messageStarting;
1130    String JavaDoc messageStopping;
1131    String JavaDoc username;
1132    String JavaDoc password;
1133    String JavaDoc host;
1134    String JavaDoc port;
1135    String JavaDoc namingProviderPort;
1136    }
1137}
1138/* End of EnTray.java */
1139
Popular Tags