KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > demo > sharedqueue > Main


1 /*
2 @COPYRIGHT@
3 */

4 package demo.sharedqueue;
5
6 import java.io.File JavaDoc;
7 import java.net.InetAddress JavaDoc;
8 import java.net.UnknownHostException JavaDoc;
9 import javax.management.MBeanServer JavaDoc;
10 import javax.management.MBeanServerFactory JavaDoc;
11 import javax.management.MBeanServerNotification JavaDoc;
12 import javax.management.Notification JavaDoc;
13 import javax.management.NotificationFilter JavaDoc;
14 import javax.management.NotificationListener JavaDoc;
15 import javax.management.ObjectName JavaDoc;
16 import org.mortbay.http.handler.ResourceHandler;
17 import org.mortbay.http.HttpContext;
18 import org.mortbay.http.HttpHandler;
19 import org.mortbay.http.HttpServer;
20 import org.mortbay.http.SocketListener;
21
22 public class Main {
23    private final File JavaDoc cwd = new File JavaDoc(System.getProperty("user.dir"));
24    private int lastPortUsed;
25    private Queue queue;
26    private Worker worker;
27
28    /**
29     * Start a web server at the specified port.
30     *
31     *@param port Description of Parameter
32     *@exception Exception Description of Exception
33     */

34    public void start(int port)
35           throws Exception JavaDoc {
36       String JavaDoc nodeId = registerForNotifications();
37       port = setPort(port);
38
39       System.out.println("DSO SharedQueue (node " + nodeId + ")");
40       System.out.println("Open your browser and go to - http://" + getHostName() + ":" + port + "/webapp\n");
41       HttpServer server = new HttpServer();
42       SocketListener listener = new SocketListener();
43       listener.setPort(port);
44       server.addListener(listener);
45
46       HttpContext context = server.addContext("/");
47       String JavaDoc resourceBase = cwd.getPath();
48       context.setResourceBase(resourceBase);
49       context.addHandler(new ResourceHandler());
50
51       queue = new Queue(port);
52       worker = queue.createWorker(nodeId);
53
54       HttpContext ajaxContext = server.addContext(SimpleHttpHandler.ACTION);
55       HttpHandler ajaxHandler = new SimpleHttpHandler(queue, resourceBase);
56       ajaxContext.addHandler(ajaxHandler);
57
58       startReaper();
59       server.start();
60    }
61
62    private int setPort(int port) {
63       if (port == -1) {
64          if (lastPortUsed == 0) {
65             port = lastPortUsed = 1990;
66          }
67          else {
68             port = ++lastPortUsed;
69          }
70       }
71       else {
72          lastPortUsed = port;
73       }
74
75       return port;
76    }
77
78    /**
79     * Starts a thread to identify dead workers (From nodes that have been
80     * brought down) and removes them from the (shared) list of workers.
81     */

82    private void startReaper() {
83       Thread JavaDoc reaper = new Thread JavaDoc(
84                new Runnable JavaDoc() {
85                   public void run() {
86                      while (true) {
87                         Main.this.queue.reap();
88                         try {
89                            Thread.sleep(1000);
90                         }
91                         catch (InterruptedException JavaDoc ie) {
92                            System.err.println(ie.getMessage());
93                         }
94                      }
95                   }
96                });
97       reaper.start();
98    }
99
100    /**
101     * Starts the demo
102     *
103     *@param args The command line arguments
104     *@exception Exception Description of Exception
105     */

106    public static final void main(String JavaDoc[] args)
107           throws Exception JavaDoc {
108       int port = -1;
109       try { port = Integer.parseInt(args[0]); }
110       catch (Exception JavaDoc e) { }
111
112       (new Main()).start(port);
113    }
114
115    /**
116     *@return The HostName value
117     */

118    static String JavaDoc getHostName() {
119       try {
120          InetAddress JavaDoc addr = InetAddress.getLocalHost();
121          byte[] ipAddr = addr.getAddress();
122          return addr.getHostName();
123       }
124       catch (UnknownHostException JavaDoc e) {
125          return "Unknown";
126       }
127    }
128    
129    /**
130     * Registers this client for JMX notifications.
131     * @returns This clients Node ID
132     */

133    private String JavaDoc registerForNotifications() throws Exception JavaDoc {
134       java.util.List JavaDoc servers = MBeanServerFactory.findMBeanServer(null);
135         if (servers.size() == 0) {
136            System.err.println("WARNING: No JMX servers found, unable to register for notifications.");
137            return "0";
138         }
139         
140       MBeanServer JavaDoc server = (MBeanServer JavaDoc)servers.get(0);
141       final ObjectName JavaDoc clusterBean = new ObjectName JavaDoc("org.terracotta:type=Terracotta Cluster,name=Terracotta Cluster Bean");
142       ObjectName JavaDoc delegateName = ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate");
143       final java.util.List JavaDoc clusterBeanBag = new java.util.ArrayList JavaDoc();
144       
145       // listener for newly registered MBeans
146
NotificationListener JavaDoc listener0 = new NotificationListener JavaDoc() {
147          public void handleNotification(Notification JavaDoc notification, Object JavaDoc handback) {
148             synchronized (clusterBeanBag) {
149                clusterBeanBag.add(handback);
150                clusterBeanBag.notifyAll();
151             }
152          }
153       };
154
155       // filter to let only clusterBean passed through
156
NotificationFilter JavaDoc filter0 = new NotificationFilter JavaDoc() {
157          public boolean isNotificationEnabled(Notification JavaDoc notification) {
158             if (notification.getType().equals("JMX.mbean.registered")
159                   && ((MBeanServerNotification JavaDoc) notification)
160                         .getMBeanName().equals(clusterBean))
161                return true;
162             return false;
163          }
164       };
165       
166       // add our listener for clusterBean's registration
167
server.addNotificationListener(delegateName, listener0, filter0,
168             clusterBean);
169
170       // because of race condition, clusterBean might already have registered
171
// before we registered the listener
172
java.util.Set JavaDoc allObjectNames = server.queryNames(null, null);
173
174       if (!allObjectNames.contains(clusterBean)) {
175          synchronized (clusterBeanBag) {
176             while (clusterBeanBag.isEmpty()) {
177                clusterBeanBag.wait();
178             }
179          }
180       }
181
182       // clusterBean is now registered, no need to listen for it
183
server.removeNotificationListener(delegateName, listener0);
184       
185       // listener for clustered bean events
186
NotificationListener JavaDoc listener1 = new NotificationListener JavaDoc() {
187          public void handleNotification(Notification JavaDoc notification, Object JavaDoc handback) {
188             String JavaDoc nodeId = notification.getMessage();
189             Worker worker = Main.this.queue.getWorker(nodeId);
190             if (worker != null) {
191                worker.markForExpiration();
192             } else {
193                System.err.println("Worker for nodeId: " + nodeId + " not found.");
194             }
195          }
196       };
197
198       // filter for nodeDisconnected notifications only
199
NotificationFilter JavaDoc filter1 = new NotificationFilter JavaDoc() {
200          public boolean isNotificationEnabled(Notification JavaDoc notification) {
201             return notification.getType().equals("com.tc.cluster.event.nodeDisconnected");
202          }
203       };
204
205       // now that we have the clusterBean, add listener for membership events
206
server.addNotificationListener(clusterBean, listener1, filter1, clusterBean);
207       return (server.getAttribute(clusterBean, "NodeId")).toString();
208    }
209 }
210
Popular Tags