01: /*
02: @COPYRIGHT@
03: */
04: package demo.chatter;
05:
06: import java.util.HashMap;
07: import java.util.List;
08: import java.util.Map;
09: import java.util.Vector;
10: import javax.swing.DefaultListModel;
11:
12: /**
13: * Description of the Class
14: *
15: *@author Terracotta, Inc.
16: */
17: class ChatManager {
18: private transient ChatListener listener;
19:
20: private List messages;
21:
22: private DefaultListModel listModel;
23:
24: private Map map;
25:
26: public ChatManager() {
27: listModel = new DefaultListModel();
28: messages = new Vector();
29: map = new HashMap();
30: }
31:
32: public Message[] getMessages() {
33: return (Message[]) messages.toArray(new Message[0]);
34: }
35:
36: public Object[] getCurrentUsers() {
37: synchronized (listModel) {
38: return listModel.toArray();
39: }
40: }
41:
42: public void send(User user, String message) {
43: Message msg = new Message(user, message);
44: synchronized (messages) {
45: messages.add(msg);
46: }
47: sendNewMessageEvent(msg);
48: }
49:
50: public void registerUser(User user) {
51:
52: synchronized (Lock.lock) {
53: System.err.println("setting listener from " + listener
54: + " to " + user);
55: this .listener = user;
56: }
57:
58: synchronized (listModel) {
59: listModel.addElement(user);
60: map.put(user.getNodeId(), user);
61: }
62: sendNewUserEvent(user.getName());
63: }
64:
65: public String removeUser(String nodeId) {
66: synchronized (listModel) {
67: if (map.containsKey(nodeId)) {
68: User removedUser = (User) map.get(nodeId);
69: listModel.removeElement(removedUser);
70: return removedUser.getName();
71: } else {
72: return "";
73: }
74: }
75: }
76:
77: private synchronized void sendNewUserEvent(String username) {
78: synchronized (Lock.lock) {
79: if (this .listener == null) {
80: System.err.println("listener is NULL!!!!");
81: return;
82: }
83: this .listener.newUser(username);
84: }
85: }
86:
87: private synchronized void sendNewMessageEvent(Message message) {
88: this .listener.newMessage(message);
89: }
90:
91: static class Lock {
92: final static Object lock = new Object();
93: }
94:
95: }
|