01: /*
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: package org.getahead.dwrdemo.clock;
17:
18: import java.util.Collection;
19: import java.util.Date;
20: import java.util.concurrent.ScheduledThreadPoolExecutor;
21: import java.util.concurrent.TimeUnit;
22:
23: import org.directwebremoting.ScriptSession;
24: import org.directwebremoting.ServerContext;
25: import org.directwebremoting.ServerContextFactory;
26: import org.directwebremoting.proxy.dwr.Util;
27: import org.directwebremoting.util.SharedObjects;
28:
29: /**
30: * A server-side clock that broadcasts the server time to any browsers that will
31: * listen.
32: * This is an example of how to control clients using server side threads
33: * @author Joe Walker [joe at getahead dot ltd dot uk]
34: */
35: public class Clock implements Runnable {
36: /**
37: * Create a schedule to update the clock every second.
38: */
39: public Clock() {
40: ScheduledThreadPoolExecutor executor = SharedObjects
41: .getScheduledThreadPoolExecutor();
42: executor.scheduleAtFixedRate(this , 1, 1, TimeUnit.SECONDS);
43: }
44:
45: /* (non-Javadoc)
46: * @see java.lang.Runnable#run()
47: */
48: public void run() {
49: if (active) {
50: setClockDisplay(new Date().toString());
51: }
52: }
53:
54: /**
55: * Called from the client to turn the clock on/off
56: */
57: public synchronized void toggle() {
58: active = !active;
59:
60: if (active) {
61: setClockDisplay("Started");
62: } else {
63: setClockDisplay("Stopped");
64: }
65: }
66:
67: /**
68: * Actually alter the clients.
69: * In DWR 2.x you had to know the ServletContext in order to be able to get
70: * a ServerContext. With DWR 3.0 this restriction has been removed.
71: * This method is public so you can call this from the dwr auto-generated
72: * pages to demo altering one page from another
73: * @param output The string to display.
74: */
75: public void setClockDisplay(String output) {
76: ServerContext sctx = ServerContextFactory.get();
77: Collection<ScriptSession> sessions = sctx
78: .getScriptSessionsByPage(sctx.getContextPath()
79: + "/clock/index.html");
80: Util pages = new Util(sessions);
81: pages.setValue("clockDisplay", output);
82: }
83:
84: /**
85: * Are we updating the clocks on all the pages?
86: */
87: protected transient boolean active = false;
88: }
|