1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.cometd.demo;
16
17
18 import javax.servlet.ServletContextAttributeEvent;
19 import javax.servlet.ServletContextAttributeListener;
20
21 import org.cometd.Bayeux;
22 import org.cometd.Client;
23 import org.cometd.Message;
24 import org.mortbay.cometd.BayeuxService;
25 import org.mortbay.cometd.ext.TimesyncExtension;
26 import org.mortbay.log.Log;
27
28 public class BayeuxServicesListener implements ServletContextAttributeListener
29 {
30 public void initialize(Bayeux bayeux)
31 {
32 synchronized (bayeux)
33 {
34 if (!bayeux.hasChannel("/service/echo"))
35 {
36 new EchoRPC(bayeux);
37 new Monitor(bayeux);
38 new ChatService(bayeux);
39 bayeux.addExtension(new TimesyncExtension());
40 }
41 }
42 }
43
44 public void attributeAdded(ServletContextAttributeEvent event)
45 {
46 if (event.getName().equals(Bayeux.DOJOX_COMETD_BAYEUX))
47 {
48 Bayeux bayeux = (Bayeux)event.getValue();
49 initialize(bayeux);
50 }
51 }
52
53 public void attributeRemoved(ServletContextAttributeEvent scab)
54 {
55 }
56
57 public void attributeReplaced(ServletContextAttributeEvent scab)
58 {
59 }
60
61 public static class EchoRPC extends BayeuxService
62 {
63 public EchoRPC(Bayeux bayeux)
64 {
65 super(bayeux, "echo");
66 subscribe("/service/echo", "doEcho");
67 }
68
69 public Object doEcho(Client client, Object data)
70 {
71 Log.info("ECHO from " + client + " " + data);
72 return data;
73 }
74 }
75
76 public static class Monitor extends BayeuxService
77 {
78 public Monitor(Bayeux bayeux)
79 {
80 super(bayeux, "monitor");
81 subscribe("/meta/subscribe", "monitorSubscribe");
82 subscribe("/meta/unsubscribe", "monitorUnsubscribe");
83 subscribe("/meta/*", "monitorMeta");
84
85 }
86
87 public void monitorSubscribe(Client client, Message message)
88 {
89 Log.info("Subscribe from " + client + " for " + message.get(Bayeux.SUBSCRIPTION_FIELD));
90 }
91
92 public void monitorUnsubscribe(Client client, Message message)
93 {
94 Log.info("Unsubscribe from " + client + " for " + message.get(Bayeux.SUBSCRIPTION_FIELD));
95 }
96
97 public void monitorMeta(Client client, Message message)
98 {
99 if (Log.isDebugEnabled())
100 Log.debug(message.toString());
101 }
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117 }
118 }