/Users/lyon/j4p/src/net/rmi/utils/RmiRegistryUtils.java

1    package net.rmi.utils; 
2     
3    import gui.In; 
4     
5    import java.net.MalformedURLException; 
6    import java.rmi.RemoteException; 
7    import java.rmi.registry.Registry; 
8     
9    /** 
10    * DocJava, Inc. 
11    * http://www.docjava.com 
12    * Programmer: dlyon 
13    * Date: Oct 13, 2004 
14    * Time: 1:27:44 PM 
15    * net.rmi.utils.RmiRegistryUtils 
16    * Is a singleton pattern that lets you get the local registry. 
17    */ 
18   public final class RmiRegistryUtils { 
19       // use singleton pattern and 
20       // prevent instantiation of RmiRegistryUtils. 
21    
22       private RmiRegistryUtils(){} 
23       // the only instance of the Registry held by the RmiRegistryUtils 
24       private static Registry registry; 
25    
26       /** 
27        * Checks whether a Registry has been started on this host. 
28        * If not, it tries to start one. 
29        * when it fails to start a Registry, it exits the program 
30        * with exit code 1. 
31        */ 
32       public static void restart() { 
33           if (isRegistryRunning()) 
34               return; 
35           startRegistry(); 
36       } 
37    
38       private static boolean isRegistryRunning() { 
39           try { 
40               java.rmi.Naming.list("/"); 
41               return true; 
42           } catch (RemoteException e) { 
43               return false; 
44           } catch (MalformedURLException e) { 
45               return false; 
46           } 
47       } 
48       /** 
49        * Restart the registry, if needed. 
50        * Return the only instance of the registry for consistent global 
51        * using by making use of the Singleton Design Pattern 
52        * @return the internally held registry instance. 
53        */ 
54       public static Registry getRegistry() { 
55           restart(); 
56           return registry; 
57       } 
58       private static void startRegistry() { 
59           try { 
60               registry = new sun.rmi.registry.RegistryImpl 
61                       (Registry.REGISTRY_PORT); 
62           } catch (Exception e) { 
63               In.message("could not start registry..."+e.getMessage()); 
64               System.exit(1); 
65           } 
66       } 
67    
68       public static void main(String args[]) { 
69           restart(); 
70           In.message("Registry Started"); 
71       } 
72   } 
73