01: package uk.ltd.getahead.dwrdemo.clock;/*
02: * Copyright 2005 Joe Walker
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: import java.util.Collection;
18: import java.util.Date;
19:
20: import javax.servlet.ServletContext;
21:
22: import org.directwebremoting.ServerContext;
23: import org.directwebremoting.ServerContextFactory;
24: import org.directwebremoting.WebContextFactory;
25: import org.directwebremoting.proxy.dwr.Util;
26: import org.directwebremoting.util.Logger;
27:
28: /**
29: * @author Joe Walker [joe at getahead dot ltd dot uk]
30: */
31: public class Clock implements Runnable {
32: /**
33: *
34: */
35: public Clock() {
36: ServletContext servletContext = WebContextFactory.get()
37: .getServletContext();
38: sctx = ServerContextFactory.get(servletContext);
39: }
40:
41: /**
42: *
43: */
44: public synchronized void toggle() {
45: active = !active;
46:
47: if (active) {
48: new Thread(this ).start();
49: }
50: }
51:
52: /* (non-Javadoc)
53: * @see java.lang.Runnable#run()
54: */
55: public void run() {
56: try {
57: log.debug("CLOCK: Starting server-side thread");
58:
59: while (active) {
60: Collection sessions = sctx
61: .getScriptSessionsByPage("/jpublishdwr/clock");
62: Util pages = new Util(sessions);
63: pages.setValue("clockDisplay", new Date().toString());
64:
65: log.debug("Sent message");
66: Thread.sleep(1000);
67: }
68:
69: Collection sessions = sctx
70: .getScriptSessionsByPage("/jpublishdwr/clock");
71: Util pages = new Util(sessions);
72: pages.setValue("clockDisplay", "");
73:
74: log.debug("CLOCK: Stopping server-side thread");
75: } catch (InterruptedException ex) {
76: ex.printStackTrace();
77: }
78: }
79:
80: /**
81: * Our key to get hold of ServerContexts
82: */
83: private ServerContext sctx;
84:
85: /**
86: * Are we updating the clocks on all the pages?
87: */
88: private transient boolean active = false;
89:
90: /**
91: * The log stream
92: */
93: private static final Logger log = Logger.getLogger(Clock.class);
94: }
|