01: /*
02: *
03: * Copyright 2005 Joe Walker
04: *
05: * Licensed under the Apache License, Version 2.0 (the "License");
06: * you may not use this file except in compliance with the License.
07: * You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: *
17: */
18:
19: package uk.ltd.getahead.dwrdemo.chat;
20:
21: import java.util.Collection;
22: import java.util.Iterator;
23: import java.util.LinkedList;
24:
25: import org.directwebremoting.ScriptBuffer;
26: import org.directwebremoting.ScriptSession;
27: import org.directwebremoting.WebContext;
28: import org.directwebremoting.WebContextFactory;
29: import org.directwebremoting.util.Logger;
30:
31: /**
32: * @author Joe Walker [joe at getahead dot ltd dot uk]
33: */
34: public class JavascriptChat {
35: /**
36: * @param text The new message text to add
37: */
38: public void addMessage(String text) {
39: if (text != null && text.trim().length() > 0) {
40: messages.addFirst(new Message(text));
41: while (messages.size() > 10) {
42: messages.removeLast();
43: }
44: }
45:
46: WebContext wctx = WebContextFactory.get();
47: String currentPage = wctx.getCurrentPage();
48:
49: ScriptBuffer script = new ScriptBuffer();
50: script.appendScript("receiveMessages(").appendData(messages)
51: .appendScript(");");
52:
53: // Loop over all the users on the current page
54: Collection pages = wctx.getScriptSessionsByPage(currentPage);
55: for (Iterator it = pages.iterator(); it.hasNext();) {
56: ScriptSession otherSession = (ScriptSession) it.next();
57: otherSession.addScript(script);
58: }
59: }
60:
61: /**
62: * The current set of messages
63: */
64: private LinkedList messages = new LinkedList();
65:
66: /**
67: *
68: */
69: public void pingMe() {
70: WebContext wctx = WebContextFactory.get();
71: final ScriptSession scriptSession = wctx.getScriptSession();
72: Thread worker = new Thread(new Runnable() {
73: public void run() {
74: int count = 0;
75: while (count < 100) {
76: count++;
77: try {
78: Thread.sleep(1000);
79: log.debug("ping: " + count);
80: scriptSession.addScript(new ScriptBuffer(
81: "dwr.util.setValue('ping', 'count="
82: + count + "');"));
83: } catch (Exception ex) {
84: log.warn("Waking:", ex);
85: }
86: }
87: }
88: });
89: worker.start();
90: }
91:
92: /**
93: * The log stream
94: */
95: protected static final Logger log = Logger
96: .getLogger(JavascriptChat.class);
97: }
|