01: /*
02: * Created on 09.10.2004
03: *
04: * To change the template for this generated file go to
05: * Window - Preferences - Java - Code Generation - Code and Comments
06: */
07: package de.schlund.pfixcore.example.webservices.chat;
08:
09: import java.util.Calendar;
10: import java.util.Iterator;
11: import java.util.WeakHashMap;
12:
13: /**
14: * @author ml
15: *
16: * To change the template for this generated type comment go to
17: * Window - Preferences - Java - Code Generation - Code and Comments
18: */
19: public class ChatServer {
20:
21: private static ChatServer instance = new ChatServer();
22:
23: private WeakHashMap<String, ContextChat> ctxMap;
24:
25: public ChatServer() {
26: ctxMap = new WeakHashMap<String, ContextChat>();
27: }
28:
29: public static ChatServer getInstance() {
30: return instance;
31: }
32:
33: public synchronized void register(String nickName, ContextChat ctx)
34: throws Exception {
35: if (ctxMap.containsKey(nickName))
36: throw new Exception("Nickname already in use");
37: ctxMap.put(nickName, ctx);
38: publish("Admin", nickName + " joined the chat.", null);
39: }
40:
41: public synchronized void deregister(String nickName)
42: throws Exception {
43: if (!ctxMap.containsKey(nickName))
44: throw new Exception("Nickname is not registered");
45: ctxMap.remove(nickName);
46: publish("Admin", nickName + " has left the chat.", null);
47: }
48:
49: private void publish(Message msg, String[] to) {
50: if (to == null || to.length == 0) {
51: Iterator<ContextChat> it = ctxMap.values().iterator();
52: while (it.hasNext()) {
53: ContextChat cc = it.next();
54: cc.addMessage(msg);
55: }
56: } else {
57: for (int i = 0; i < to.length; i++) {
58: ContextChat cc = (ContextChat) ctxMap.get(to[i]);
59: if (cc != null)
60: cc.addMessage(msg);
61: }
62: }
63: }
64:
65: public synchronized void publish(String from, String txt,
66: String[] to) {
67: Calendar cal = Calendar.getInstance();
68: Message msg = new Message(from, txt, cal);
69: publish(msg, to);
70: }
71:
72: public synchronized String[] getRegisteredNames() {
73: String[] names = new String[ctxMap.size()];
74: ctxMap.keySet().toArray(names);
75: return names;
76: }
77:
78: }
|