KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > demo > chatter > Main


1 /*
2  @COPYRIGHT@
3  */

4  package demo.chatter;
5
6  import java.awt.BorderLayout JavaDoc;
7  import java.awt.Color JavaDoc;
8  import java.awt.Container JavaDoc;
9  import java.awt.Dimension JavaDoc;
10  import java.awt.Font JavaDoc;
11  import java.awt.event.ActionEvent JavaDoc;
12  import java.awt.event.ActionListener JavaDoc;
13  import java.awt.event.WindowEvent JavaDoc;
14  import java.awt.event.WindowListener JavaDoc;
15  import java.util.Random JavaDoc;
16
17  import javax.management.MBeanServer JavaDoc;
18  import javax.management.MBeanServerFactory JavaDoc;
19  import javax.management.MBeanServerNotification JavaDoc;
20  import javax.management.Notification JavaDoc;
21  import javax.management.NotificationFilter JavaDoc;
22  import javax.management.NotificationListener JavaDoc;
23  import javax.management.ObjectName JavaDoc;
24  import javax.swing.DefaultListModel JavaDoc;
25  import javax.swing.ImageIcon JavaDoc;
26  import javax.swing.JFrame JavaDoc;
27  import javax.swing.JLabel JavaDoc;
28  import javax.swing.JList JavaDoc;
29  import javax.swing.JPanel JavaDoc;
30  import javax.swing.JScrollPane JavaDoc;
31  import javax.swing.JTextField JavaDoc;
32  import javax.swing.JTextPane JavaDoc;
33  import javax.swing.text.Document JavaDoc;
34  import javax.swing.text.Style JavaDoc;
35  import javax.swing.text.StyleConstants JavaDoc;
36
37  /**
38   * Description of the Class
39   *
40   *@author Terracotta, Inc.
41   */

42  public class Main extends JFrame JavaDoc implements ActionListener JavaDoc, ChatterDisplay,
43        WindowListener JavaDoc {
44
45     private final ChatManager chatManager = new ChatManager();
46
47     private final JTextPane JavaDoc display = new JTextPane JavaDoc();
48
49     private User user;
50
51     private final JList JavaDoc buddyList = new JList JavaDoc();
52
53     private boolean isServerDown = false;
54     private static final String JavaDoc CHATTER_SYSTEM = "SYSTEM";
55
56     public Main() {
57        try {
58           final String JavaDoc nodeId = registerForNotifications();
59           user = new User(nodeId, this);
60           populateCurrentUsers();
61           login();
62        }
63        catch (final Exception JavaDoc e) {
64           throw new RuntimeException JavaDoc(e);
65        }
66
67        addWindowListener(this);
68        setDefaultLookAndFeelDecorated(true);
69        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
70        final Container JavaDoc content = getContentPane();
71
72        display.setFont(new Font JavaDoc("Andale Mono", Font.PLAIN, 9));
73        display.setEditable(false);
74        display.setRequestFocusEnabled(false);
75
76        final JTextField JavaDoc input = new JTextField JavaDoc();
77        input.setFont(new Font JavaDoc("Andale Mono", Font.PLAIN, 9));
78        input.addActionListener(this);
79        final JScrollPane JavaDoc scroll = new JScrollPane JavaDoc(display);
80        final Random JavaDoc r = new Random JavaDoc();
81        final JLabel JavaDoc avatar = new JLabel JavaDoc(user.getName() + " (node id: "
82              + user.getNodeId() + ")", new ImageIcon JavaDoc(getClass().getResource(
83              "/images/buddy" + r.nextInt(10) + ".gif")), JLabel.LEFT);
84        avatar.setForeground(Color.WHITE);
85        avatar.setFont(new Font JavaDoc("Georgia", Font.PLAIN, 16));
86        avatar.setVerticalTextPosition(JLabel.CENTER);
87        final JPanel JavaDoc buddypanel = new JPanel JavaDoc();
88        buddypanel.setBackground(Color.DARK_GRAY);
89        buddypanel.setLayout(new BorderLayout JavaDoc());
90        buddypanel.add(avatar, BorderLayout.CENTER);
91
92        final JPanel JavaDoc buddyListPanel = new JPanel JavaDoc();
93        buddyListPanel.setBackground(Color.WHITE);
94        buddyListPanel.add(buddyList);
95        buddyList.setFont(new Font JavaDoc("Andale Mono", Font.BOLD, 9));
96
97        content.setLayout(new BorderLayout JavaDoc());
98        content.add(buddypanel, BorderLayout.NORTH);
99        content.add(scroll, BorderLayout.CENTER);
100        content.add(input, BorderLayout.SOUTH);
101        content.add(new JScrollPane JavaDoc(buddyListPanel), BorderLayout.EAST);
102        pack();
103
104        setTitle("Chatter: " + user.getName());
105        setSize(new Dimension JavaDoc(600, 400));
106        setVisible(true);
107        input.requestFocus();
108     }
109
110     public void actionPerformed(final ActionEvent JavaDoc e) {
111        final JTextField JavaDoc input = (JTextField JavaDoc) e.getSource();
112        final String JavaDoc message = input.getText();
113        input.setText("");
114        (
115           new Thread JavaDoc() {
116              public void run() {
117                 chatManager.send(user, message);
118              }
119           }).start();
120
121        if (isServerDown) {
122           updateMessage(user.getName(), message, true);
123        }
124     }
125
126     public void handleConnectedServer() {
127        isServerDown = false;
128        javax.swing.SwingUtilities.invokeLater(
129                 new Runnable JavaDoc() {
130                    public void run() {
131                       Main.this.buddyList.setVisible(true);
132                       Main.this.buddyList.setEnabled(true);
133                    }
134                 });
135     }
136
137     public void handleDisconnectedServer() {
138        isServerDown = true;
139        updateMessage("The server is down; all of your messages will be queued until the server goes back up again.");
140        javax.swing.SwingUtilities.invokeLater(
141                 new Runnable JavaDoc() {
142                    public void run() {
143                       Main.this.buddyList.setVisible(false);
144                       Main.this.buddyList.setEnabled(false);
145                    }
146                 });
147     }
148
149     public synchronized void handleDisconnectedUser(final String JavaDoc nodeId) {
150        chatManager.removeUser(nodeId);
151        populateCurrentUsers();
152     }
153
154     public synchronized void handleNewUser(final String JavaDoc username) {
155        populateCurrentUsers();
156     }
157
158     public void updateMessage(final String JavaDoc username, final String JavaDoc message,
159           final boolean isOwnMessage) {
160        javax.swing.SwingUtilities.invokeLater(
161                 new Runnable JavaDoc() {
162                    public void run() {
163                       try {
164                          final Document JavaDoc doc = display.getDocument();
165                          final Style JavaDoc style = display.addStyle("Style", null);
166
167                          if (isOwnMessage) {
168                             StyleConstants.setItalic(style, true);
169                             StyleConstants.setForeground(style, Color.LIGHT_GRAY);
170                             StyleConstants.setFontSize(style, 9);
171                          }
172
173                          if (username.equals(CHATTER_SYSTEM)) {
174                             StyleConstants.setItalic(style, true);
175                             StyleConstants.setForeground(style, Color.RED);
176                          }
177                          else {
178                             StyleConstants.setBold(style, true);
179                             doc.insertString(doc.getLength(), username + ": ",
180                                   style);
181                          }
182
183                          StyleConstants.setBold(style, false);
184                          doc.insertString(doc.getLength(), message, style);
185                          doc.insertString(doc.getLength(), "\n", style);
186
187                          display.setCaretPosition(doc.getLength());
188                       }
189                       catch (final javax.swing.text.BadLocationException JavaDoc ble) {
190                          System.err.println(ble.getMessage());
191                       }
192                    }
193                 });
194     }
195
196     public void windowClosing(WindowEvent JavaDoc e) {
197        handleDisconnectedUser(user.getNodeId());
198     }
199
200     public void windowActivated(WindowEvent JavaDoc e) {
201        // TODO Auto-generated method stub
202
}
203
204     public void windowClosed(WindowEvent JavaDoc e) {
205        // TODO Auto-generated method stub
206
}
207
208     public void windowDeactivated(WindowEvent JavaDoc e) {
209        // TODO Auto-generated method stub
210
}
211
212     public void windowDeiconified(WindowEvent JavaDoc e) {
213        // TODO Auto-generated method stub
214
}
215
216     public void windowIconified(WindowEvent JavaDoc e) {
217        // TODO Auto-generated method stub
218
}
219
220     public void windowOpened(WindowEvent JavaDoc e) {
221        // TODO Auto-generated method stub
222
}
223
224     void login() {
225        // ****************************************************
226
// Uncomment this section if you want incoming clients
227
// to see the history of messages.
228
// ****************************************************
229
// --- CODE BEGINS HERE ---
230
// final Message[] messages = chatManager.getMessages();
231
// for (int i = 0; i < messages.length; i++) {
232
// user.newMessage(messages[i]);
233
// }
234
// --- CODE ENDS HERE ---
235
synchronized (chatManager) {
236           chatManager.registerUser(user);
237        }
238     }
239
240     private synchronized void populateCurrentUsers() {
241         DefaultListModel JavaDoc list = new DefaultListModel JavaDoc();
242         final Object JavaDoc[] currentUsers = chatManager.getCurrentUsers();
243         for (int i = 0; i < currentUsers.length; i++) {
244            list.addElement(new String JavaDoc(((User) currentUsers[i])
245                  .getName()));
246         }
247         buddyList.setModel(list);
248     }
249
250     private void updateMessage(final String JavaDoc message) {
251        updateMessage(CHATTER_SYSTEM, message, true);
252     }
253
254     /**
255      * Registers this client for JMX notifications.
256      *
257      *@return Description of the Returned Value
258      *@exception Exception Description of Exception
259      *@returns This clients Node ID
260      */

261     private String JavaDoc registerForNotifications() throws Exception JavaDoc {
262        final java.util.List JavaDoc servers = MBeanServerFactory.findMBeanServer(null);
263        if (servers.size() == 0) {
264
265           System.err.println("WARNING: No JMX servers found, unable to register for notifications.");
266           return "0";
267        }
268
269        final MBeanServer JavaDoc server = (MBeanServer JavaDoc) servers.get(0);
270        final ObjectName JavaDoc clusterBean = new ObjectName JavaDoc(
271              "org.terracotta:type=Terracotta Cluster,name=Terracotta Cluster Bean");
272        final ObjectName JavaDoc delegateName =
273              ObjectName.getInstance("JMImplementation:type=MBeanServerDelegate");
274        final java.util.List JavaDoc clusterBeanBag = new java.util.ArrayList JavaDoc();
275
276        // listener for newly registered MBeans
277
final NotificationListener JavaDoc listener0 =
278           new NotificationListener JavaDoc() {
279              public void handleNotification(Notification JavaDoc notification,
280                    Object JavaDoc handback) {
281                 synchronized (clusterBeanBag) {
282                    clusterBeanBag.add(handback);
283                    clusterBeanBag.notifyAll();
284                 }
285              }
286           };
287
288        // filter to let only clusterBean passed through
289
final NotificationFilter JavaDoc filter0 =
290           new NotificationFilter JavaDoc() {
291              public boolean isNotificationEnabled(Notification JavaDoc notification) {
292                 if (notification.getType().equals("JMX.mbean.registered")
293                       && ((MBeanServerNotification JavaDoc) notification)
294                       .getMBeanName().equals(clusterBean)) {
295                    return true;
296                 }
297                 return false;
298              }
299           };
300
301        // add our listener for clusterBean's registration
302
server.addNotificationListener(delegateName, listener0, filter0,
303              clusterBean);
304
305        // because of race condition, clusterBean might already have registered
306
// before we registered the listener
307
final java.util.Set JavaDoc allObjectNames = server.queryNames(null, null);
308
309        if (!allObjectNames.contains(clusterBean)) {
310           synchronized (clusterBeanBag) {
311              while (clusterBeanBag.isEmpty()) {
312                 clusterBeanBag.wait();
313              }
314           }
315        }
316
317        // clusterBean is now registered, no need to listen for it
318
server.removeNotificationListener(delegateName, listener0);
319
320        // listener for clustered bean events
321
final NotificationListener JavaDoc listener1 =
322           new NotificationListener JavaDoc() {
323              public void handleNotification(Notification JavaDoc notification,
324                    Object JavaDoc handback) {
325                 String JavaDoc nodeId = notification.getMessage();
326                 if (notification.getType().endsWith("thisNodeConnected")) {
327                    handleConnectedServer();
328                 }
329                 if (notification.getType().endsWith("thisNodeDisconnected")) {
330                    handleDisconnectedServer();
331                 }
332                 else if (notification.getType().endsWith("nodeDisconnected")) {
333                    handleDisconnectedUser(nodeId);
334                 }
335              }
336           };
337
338        // now that we have the clusterBean, add listener for membership events
339
server.addNotificationListener(clusterBean, listener1, null,
340              clusterBean);
341        return (server.getAttribute(clusterBean, "NodeId")).toString();
342     }
343
344     public static void main(final String JavaDoc[] args) {
345        javax.swing.SwingUtilities.invokeLater(
346                 new Runnable JavaDoc() {
347                    public void run() {
348                       new Main();
349                    }
350                 });
351     }
352  }
353
Popular Tags