Author: remy.maucherat(a)jboss.com
Date: 2008-10-28 11:51:50 -0400 (Tue, 28 Oct 2008)
New Revision: 823
Added:
trunk/test/java/org/apache/cometd/
trunk/test/java/org/apache/cometd/bayeux/
trunk/test/java/org/apache/cometd/bayeux/sample/
trunk/test/java/org/apache/cometd/bayeux/sample/BayeuxStockTicker.java
trunk/test/java/org/apache/cometd/bayeux/sample/EchoChatClient.java
trunk/test/webapps/cometd/
trunk/test/webapps/cometd/WEB-INF/
trunk/test/webapps/cometd/WEB-INF/web.xml
trunk/test/webapps/cometd/examples/
trunk/test/webapps/cometd/examples/simplechat/
trunk/test/webapps/cometd/examples/simplechat/cometdchat.htm
trunk/test/webapps/cometd/examples/simplechat/ticker.html
trunk/test/webapps/cometd/index.html
Log:
- Add the bayeux test webapp to have it around.
Added: trunk/test/java/org/apache/cometd/bayeux/sample/BayeuxStockTicker.java
===================================================================
--- trunk/test/java/org/apache/cometd/bayeux/sample/BayeuxStockTicker.java
(rev 0)
+++ trunk/test/java/org/apache/cometd/bayeux/sample/BayeuxStockTicker.java 2008-10-28
15:51:50 UTC (rev 823)
@@ -0,0 +1,215 @@
+package org.apache.cometd.bayeux.samples;
+
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+import javax.servlet.ServletContextAttributeListener;
+import javax.servlet.ServletContextAttributeEvent;
+import org.apache.cometd.bayeux.Bayeux;
+
+import java.text.DecimalFormat;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.cometd.bayeux.Client;
+import org.apache.cometd.bayeux.Listener;
+import org.apache.cometd.bayeux.Message;
+import org.apache.cometd.bayeux.Channel;
+
+public class BayeuxStockTicker implements ServletContextListener,
+ ServletContextAttributeListener, Listener {
+
+ static AtomicInteger counter = new AtomicInteger(0);
+ protected int id;
+ protected Bayeux b;
+ protected Client c;
+ protected boolean alive = true;
+ protected boolean initialized = false;
+ protected TickerThread tt = new TickerThread();
+
+ public BayeuxStockTicker() {
+ id = counter.incrementAndGet();
+ System.out.println("new listener created with id:" + id);
+ }
+
+ public void contextDestroyed(ServletContextEvent servletContextEvent) {
+ alive = false;
+ tt.run = false;
+ tt.interrupt();
+ }
+
+ public void contextInitialized(ServletContextEvent servletContextEvent) {
+ }
+
+ public void attributeAdded(ServletContextAttributeEvent scae) {
+ if (scae.getName().equals(Bayeux.DOJOX_COMETD_BAYEUX)) {
+ if (initialized) return;
+ initialized = true;
+ System.out.println("Starting stock ticker server client!");
+ b = (Bayeux) scae.getValue();
+ c = b.newClient("stock-ticker-", this);
+ tt.start();
+ }
+ }
+
+ public void attributeRemoved(ServletContextAttributeEvent scae) {
+ if (scae.getName().equals(Bayeux.DOJOX_COMETD_BAYEUX)) {
+ initialized = false;
+ b = (Bayeux) scae.getValue();
+ List<Channel> chs = b.getChannels();
+ for (Channel ch : chs) {
+ ch.unsubscribe(c);
+ }
+ }
+ }
+
+ public void attributeReplaced(
+ ServletContextAttributeEvent servletContextAttributeEvent) {
+ }
+
+ public void removed(boolean timeout) {
+ System.out.println("Client removed.");
+ }
+
+ public void deliver(Message[] msgs) {
+ for (int i = 0; msgs != null && i < msgs.length; i++) {
+ Message msg = msgs[i];
+ System.out.println("[stock ticker server client ]received message:"
+ msg);
+ }
+ }
+
+ public class TickerThread extends Thread {
+ public boolean run = true;
+
+ public TickerThread() {
+ setName("Ticker Thread");
+ }
+
+ public void run() {
+ try {
+
+ Stock[] stocks = new Stock[] {
+ new Stock("GOOG", 435.43),
+ new Stock("YHOO", 27.88),
+ new Stock("SPRG", 1015.55), };
+ for (Stock s : stocks) {
+ Channel ch = b.getChannel("/stock/"+s.getSymbol(), true);
+ ch.subscribe(c);
+
+ }
+ Random r = new Random(System.currentTimeMillis());
+ while (run) {
+ for (int j = 0; j < 1; j++) {
+ int i = r.nextInt() % 3;
+ if (i < 0)
+ i = i * (-1);
+ Stock stock = stocks[i];
+ double change = r.nextDouble();
+ boolean plus = r.nextBoolean();
+ if (plus) {
+ stock.setValue(stock.getValue() + change);
+ } else {
+ stock.setValue(stock.getValue() - change);
+ }
+ Channel ch = b.getChannel("/stock/"+stock.getSymbol(),
true);
+ Message m = b.newMessage(c);
+ m.put("stock", stock.toString());
+ m.put("symbol", stock.getSymbol());
+ m.put("price", stock.getValueAsString());
+ m.put("change", stock.getLastChangeAsString());
+ ch.publish(m);
+ System.out.println("Stock: "+stock.getSymbol()+"
Price: "+stock.getValueAsString()+" Change:
"+stock.getLastChangeAsString());
+ }
+ Thread.sleep(850);
+ }
+ } catch (InterruptedException ix) {
+
+ } catch (Exception x) {
+ x.printStackTrace();
+ }
+ }
+ }
+
+ public static class Stock {
+ protected static DecimalFormat df = new DecimalFormat("0.00");
+ protected String symbol = "";
+ protected double value = 0.0d;
+ protected double lastchange = 0.0d;
+ protected int cnt = 0;
+
+ public Stock(String symbol, double initvalue) {
+ this.symbol = symbol;
+ this.value = initvalue;
+ }
+
+ public void setCnt(int c) {
+ this.cnt = c;
+ }
+
+ public int getCnt() {
+ return cnt;
+ }
+
+ public String getSymbol() {
+ return symbol;
+ }
+
+ public double getValue() {
+ return value;
+ }
+
+ public void setValue(double value) {
+ double old = this.value;
+ this.value = value;
+ this.lastchange = value - old;
+ }
+
+ public String getValueAsString() {
+ return df.format(value);
+ }
+
+ public double getLastChange() {
+ return this.lastchange;
+ }
+
+ public void setLastChange(double lastchange) {
+ this.lastchange = lastchange;
+ }
+
+ public String getLastChangeAsString() {
+ return df.format(lastchange);
+ }
+
+ public int hashCode() {
+ return symbol.hashCode();
+ }
+
+ public boolean equals(Object other) {
+ if (other instanceof Stock) {
+ return this.symbol.equals(((Stock) other).symbol);
+ } else {
+ return false;
+ }
+ }
+
+ public String toString(){
+ StringBuffer buf = new StringBuffer("STOCK#");
+ buf.append(getSymbol());
+ buf.append("#");
+ buf.append(getValueAsString());
+ buf.append("#");
+ buf.append(getLastChangeAsString());
+ buf.append("#");
+ buf.append(String.valueOf(getCnt()));
+ return buf.toString();
+
+ }
+
+ public Object clone() {
+ Stock s = new Stock(this.getSymbol(), this.getValue());
+ s.setLastChange(this.getLastChange());
+ s.setCnt(this.cnt);
+ return s;
+ }
+ }
+
+}
\ No newline at end of file
Added: trunk/test/java/org/apache/cometd/bayeux/sample/EchoChatClient.java
===================================================================
--- trunk/test/java/org/apache/cometd/bayeux/sample/EchoChatClient.java
(rev 0)
+++ trunk/test/java/org/apache/cometd/bayeux/sample/EchoChatClient.java 2008-10-28
15:51:50 UTC (rev 823)
@@ -0,0 +1,101 @@
+package org.apache.cometd.bayeux.samples;
+
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+import javax.servlet.ServletContextAttributeListener;
+import javax.servlet.ServletContextAttributeEvent;
+import org.apache.cometd.bayeux.Bayeux;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.cometd.bayeux.Client;
+import org.apache.cometd.bayeux.Listener;
+import org.apache.cometd.bayeux.Message;
+import org.apache.cometd.bayeux.Channel;
+
+public class EchoChatClient implements ServletContextListener,
ServletContextAttributeListener, Listener {
+
+ static AtomicInteger counter = new AtomicInteger(0);
+ protected int id;
+ protected Bayeux b;
+ protected Client c;
+ protected boolean alive = true;
+ protected TimestampThread tt = new TimestampThread();
+
+ public EchoChatClient() {
+ id = counter.incrementAndGet();
+ System.out.println("new listener created with id:"+id);
+ }
+
+ public void contextDestroyed(ServletContextEvent servletContextEvent) {
+ alive = false;
+ tt.interrupt();
+ }
+
+ public void contextInitialized(ServletContextEvent servletContextEvent) {
+ }
+
+ public void attributeAdded(ServletContextAttributeEvent scae) {
+ if (scae.getName().equals(Bayeux.DOJOX_COMETD_BAYEUX)) {
+ System.out.println("Starting echo chat client!");
+ b = (Bayeux)scae.getValue();
+ c = b.newClient("echochat-",this);
+ Channel ch = b.getChannel("/chat/demo",true);
+ ch.subscribe(c);
+ tt.start();
+ }
+ }
+
+ public void attributeRemoved(ServletContextAttributeEvent
servletContextAttributeEvent) {
+ }
+
+ public void attributeReplaced(ServletContextAttributeEvent
servletContextAttributeEvent) {
+ }
+
+ public void removed(boolean timeout) {
+ System.out.println("Client removed.");
+ }
+
+ public void deliver(Message[] msgs) {
+ for (int i=0; msgs!=null && i<msgs.length; i++) {
+ Message msg = msgs[i];
+ System.out.println("[echochatclient ]received message:" + msg);
+ Message m = b.newMessage(c);
+ m.putAll(msg);
+ //echo the same message
+ m.put("user", "echochatserver");
+ if (m.containsKey("msg")) {
+ //simple chat demo
+ String chat = (String) m.get("msg");
+ m.put("msg", "echochatserver|I received your
message-" + chat.substring(chat.indexOf("|") + 1));
+ }
+ System.out.println("[echochatclient ]sending message:" + m);
+ msg.getChannel().publish(m);
+ }
+ }
+
+ public class TimestampThread extends Thread {
+ public TimestampThread() {
+ setDaemon(true);
+ }
+
+ public void run() {
+ while (alive) {
+ try {
+ sleep(5000);
+ Channel ch = b.getChannel("/chat/demo",false);
+ if (ch.getSubscribers().size()<=1) {
+ continue;
+ }
+ Message m = b.newMessage(c);
+ m.put("user","echochatserver");
+ m.put("chat","Time is:"+new
java.sql.Date(System.currentTimeMillis()).toLocaleString());
+ m.put("join",false);
+ ch.publish(m);
+ }catch (InterruptedException ignore) {
+ Thread.currentThread().interrupted();
+ }catch (Exception x) {
+ x.printStackTrace();
+ }
+ }
+ }
+ }
+}
Added: trunk/test/webapps/cometd/WEB-INF/web.xml
===================================================================
--- trunk/test/webapps/cometd/WEB-INF/web.xml (rev 0)
+++ trunk/test/webapps/cometd/WEB-INF/web.xml 2008-10-28 15:51:50 UTC (rev 823)
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<web-app
+
xmlns="http://java.sun.com/xml/ns/javaee"
+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
+ version="2.5">
+ <display-name>Cometd Test WebApp</display-name>
+
+ <servlet>
+ <servlet-name>cometd</servlet-name>
+ <servlet-class>org.apache.tomcat.bayeux.BayeuxServlet</servlet-class>
+ <init-param>
+ <param-name>timeout</param-name>
+ <param-value>120000000</param-value>
+ </init-param>
+ <init-param>
+ <param-name>reconnectInterval</param-name>
+ <param-value>250</param-value>
+ </init-param>
+ <load-on-startup>1</load-on-startup>
+ </servlet>
+
+ <servlet-mapping>
+ <servlet-name>cometd</servlet-name>
+ <url-pattern>/cometd/*</url-pattern>
+ </servlet-mapping>
+
+ <listener>
+
<listener-class>org.apache.cometd.bayeux.samples.EchoChatClient</listener-class>
+ </listener>
+ <listener>
+
<listener-class>org.apache.cometd.bayeux.samples.BayeuxStockTicker</listener-class>
+ </listener>
+
+</web-app>
+
+
Added: trunk/test/webapps/cometd/examples/simplechat/cometdchat.htm
===================================================================
--- trunk/test/webapps/cometd/examples/simplechat/cometdchat.htm
(rev 0)
+++ trunk/test/webapps/cometd/examples/simplechat/cometdchat.htm 2008-10-28 15:51:50 UTC
(rev 823)
@@ -0,0 +1,114 @@
+<html>
+<header><title>Comet Simple Chat Application</title>
+
+<script type="text/javascript"
src="../../dojo/dojo.js.uncompressed.js"></script>
+<script type="text/javascript"
src="../../dojox/cometd.js"></script>
+<script type="text/javascript"
src="../../dojox/cometd/_base.js"></script>
+
+<script type="text/javascript">
+
+dojo.require("dojox.cometd");
+
+dojo.addOnLoad(function() {
+ dojo.byId("message").style.visibility='hidden';
+ dojox.cometd.init("/cometd/cometd");
+});
+
+
+function trim(str) {
+ return str.replace(/(^\s+|\s+$)/g,'');
+}
+
+
+function clear() {
+ dojo.byId("msgtext").value = "";
+ dojo.byId("msgtext").focus();
+}
+
+
+function enterKeyHandler(e) {
+if (!e) e = window.event;
+ if (e.keyCode == 13) {
+ send(trim(dojo.byId("msgtext").value));
+ clear();
+ }
+
+}
+
+
+function connect() {
+ dojox.cometd.subscribe("/chat/demo", onMsgEvent);
+ dojo.byId("login").style.visibility='hidden';
+ dojo.byId("message").style.visibility='visible';
+ send("Has joined the chat room");
+ clear();
+ dojo.byId("msgtext").onkeydown = enterKeyHandler;
+ dojo.byId("myname").appendChild(document.createTextNode("-> " +
dojo.byId("scrname").value + " <-"));
+}
+
+
+function onMsgEvent(event) {
+
+ // Break apart the text string into screen name and message parts.
+ var str = trim(event.data.msg);
+ var scrname = "";
+ if (str.match(/^.*[|].*$/)) {
+ var spl = str.split("|");
+ scrname = spl[0];
+ str = " - " + spl[1];
+ }
+
+ // Insert the screen name in red and the message black into the DOM
+ var newP = document.createElement("p");
+ var fnt1 = document.createElement("font");
+ var attr1 = document.createAttribute("color");
+ attr1.nodeValue = "red";
+ fnt1.setAttributeNode(attr1);
+
+ var newT = document.createTextNode(scrname);
+ fnt1.appendChild(newT);
+
+ newP.appendChild(fnt1);
+
+ var fnt2 = document.createElement("font");
+ var attr2 = document.createAttribute("color");
+ attr2.nodeValue = "black";
+ fnt2.setAttributeNode(attr2);
+
+ var newT2 = document.createTextNode(str);
+ fnt2.appendChild(newT2);
+
+ newP.appendChild(fnt2);
+
+ dojo.byId("dialog").appendChild(newP)
+}
+
+
+function send(msg) {
+ var scrname = dojo.byId("scrname").value;
+ var evt = {'data': { 'msg': trim(scrname) + '|' + msg }};
+ onMsgEvent(evt); // Echo local
+ dojox.cometd.publish("/chat/demo", evt.data);
+}
+
+
+</script>
+
+</head>
+</header>
+<body>
+<form>
+<div id="login">
+Screen name: <input type="text" id="scrname">
+<input type=Button Id=logbtn value=Connect onClick=connect()><br/>Type a
screen name and click the 'Connect' button
+</div>
+
+<div id="dialog"></div>
+<hr/>
+<div id="message">
+<div id="myname"></div> Is my screen name<br/>
+<textarea rows="3" cols="50"
id="msgtext"></textarea>[ENTER] sends message</div>
+</form>
+</body>
+</html>
+
Added: trunk/test/webapps/cometd/examples/simplechat/ticker.html
===================================================================
--- trunk/test/webapps/cometd/examples/simplechat/ticker.html (rev
0)
+++ trunk/test/webapps/cometd/examples/simplechat/ticker.html 2008-10-28 15:51:50 UTC (rev
823)
@@ -0,0 +1,128 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
+<html>
+<head>
+<meta http-equiv="Content-Type"
content="text/html;charset=ISO-8859-1" >
+<title>Bayeux Stock Ticker</title>
+<script type="text/javascript"
src="../../dojo/dojo.js.uncompressed.js"></script>
+<script type="text/javascript"
src="../../dojox/cometd.js"></script>
+<script type="text/javascript"
src="../../dojox/cometd/_base.js"></script>
+<script type="text/javascript">
+
+dojo.require("dojox.cometd");
+
+dojo.addOnUnload(function() {
+ dojox.cometd.init("/cometd/cometd");
+ dojox.cometd.startBatch();
+ dojox.cometd.unsubscribe("/stock/GOOG", this,"");
+ dojox.cometd.unsubscribe("/stock/YHOO", this,"");
+ dojox.cometd.unsubscribe("/stock/SPRG", this,"");
+ dojox.cometd.endBatch();
+ });
+
+
+dojo.addOnLoad(function() {
+ dojox.cometd.init("/cometd/cometd");
+ dojox.cometd.startBatch();
+ dojox.cometd.subscribe("/stock/GOOG", onMsgEvent);
+ dojox.cometd.subscribe("/stock/YHOO", onMsgEvent);
+ dojox.cometd.subscribe("/stock/SPRG", onMsgEvent);
+ dojox.cometd.endBatch();
+});
+
+
+function subscribe(box, symbol) {
+ if (box.checked) {
+ dojox.cometd.subscribe("/stock/"+symbol, onMsgEvent);
+ var rowCurrent = dojo.byId("row."+symbol);
+ rowCurrent.bgColor="white";
+ } else {
+ dojox.cometd.unsubscribe("/stock/"+symbol, onMsgEvent);
+ var rowCurrent = dojo.byId("row."+symbol);
+ rowCurrent.bgColor="gray";
+ }
+}
+
+function removeChildrenFromNode(node)
+{
+ if(node == undefined || node == null)
+ {
+ return;
+ }
+
+ var len = node.childNodes.length;
+
+ while (node.hasChildNodes())
+ {
+ node.removeChild(node.firstChild);
+ }
+}
+
+function onMsgEvent(event) {
+ // Break apart the text string into screen name and message parts.
+ var symbol = event.data.symbol;
+ var price = event.data.price;
+ var pricechange = event.data.change;
+ //alert("symbol: "+symbol+" price: "+price+" change:
"+pricechange);
+
+ var pricenode = dojo.byId("price."+symbol);
+ var changenode = dojo.byId("change."+symbol);
+ removeChildrenFromNode(pricenode);
+ removeChildrenFromNode(changenode);
+ var pricelabel = document.createTextNode(price);
+ pricelabel.value = price;
+ var changelabel = document.createTextNode(pricechange);
+ changelabel.value = pricechange;
+ pricenode.appendChild(pricelabel);
+ changenode.appendChild(changelabel);
+
+ var table = dojo.byId("stocktable");
+ var rows = table.getElementsByTagName("tr");
+ for(i = 0; i < rows.length; i++){
+ if (rows[i].bgColor != "gray") {
+ rows[i].bgColor = "white";
+ }
+ }
+ //manipulate rows
+ var rowCurrent = dojo.byId("row."+symbol);
+ if (pricechange<=0) {
+ rowCurrent.bgColor = "red";
+ } else {
+ rowCurrent.bgColor = "cyan";
+ }
+}
+
+
+</script>
+</head>
+<body bgcolor="#ffffff">
+<h1 align="center">Bayeux Stock Ticker</h1>
+<h2 align="left"> </h2>
+<p>
+<table id="stocktable" cellspacing="0" cellpadding="3"
width="100%" align="center" border="0">
+ <tr id="row.HEADER">
+ <td>SYMBOL</td>
+ <td>PRICE</td>
+ <td>LAST CHANGE</td>
+ <td>SUBSCRIBE</td></tr>
+ <tr id="row.SPRG">
+ <td>SPRG</td>
+ <td id="price.SPRG"></td>
+ <td id="change.SPRG"></td>
+ <td id="check.SPRG"><input type="checkbox"
id="check.SPRG" checked
onClick="subscribe(this,'SPRG')"></td>
+ </tr>
+ <tr id="row.GOOG">
+ <td>GOOG</td>
+ <td id="price.GOOG"></td>
+ <td id="change.GOOG"></td>
+ <td id="check.GOOG"><input type="checkbox"
id="check.GOOG" checked
onClick="subscribe(this,'GOOG')"></td>
+ </tr>
+ <tr id="row.YHOO">
+ <td>YHOO</td>
+ <td id="price.YHOO"></td>
+ <td id="change.YHOO"></td>
+ <td id="check.YHOO"><input type="checkbox"
id="check.GOOG" checked
onClick="subscribe(this,'YHOO')"></td>
+ </tr>
+</table>
+</p>
+</body>
+</html>
\ No newline at end of file
Added: trunk/test/webapps/cometd/index.html
===================================================================
--- trunk/test/webapps/cometd/index.html (rev 0)
+++ trunk/test/webapps/cometd/index.html 2008-10-28 15:51:50 UTC (rev 823)
@@ -0,0 +1,7 @@
+
+<h1>Cometd demo</h1>
+
+<p>
+Try the <a href="examples/simplechat/cometdchat.htm">Simple Chat
Demo</a>.</br>
+Try the <a href="examples/simplechat/ticker.html">Stock Ticker
Demo</a>.</br>
+</p>