This commit is contained in:
unknown
2012-05-21 23:31:43 +08:00
commit 99386c3dff
1111 changed files with 36351 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>comet4j</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
</projectDescription>
+1
View File
@@ -0,0 +1 @@
12
+1
View File
@@ -0,0 +1 @@
12
@@ -0,0 +1,105 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.event.demo.mic;
import org.comet4j.event.Event;
import org.comet4j.event.Listener;
import org.comet4j.event.Observable;
public class Test {
// 用法展示:微观事件模式
public class SpeakEvent extends Event<Person> {
public String words = "";
public SpeakEvent(Person target, String aWords) {
super(target);
words = aWords;
}
}
public abstract class SpeakListener extends Listener<SpeakEvent> {
}
public class GoEvent extends Event<Person> {
public String where = "";
public GoEvent(Person target, String where) {
super(target);
this.where = where;
}
}
public abstract class GoListener extends Listener<GoEvent> {
}
@SuppressWarnings({
"unchecked", "rawtypes"
})
public class Person extends Observable {
public Person() {
this.addEvent(SpeakEvent.class);
this.addEvent(GoEvent.class);
}
public void say(String aWords) {
SpeakEvent e = new SpeakEvent(this, aWords);
if (!this.fireEvent(e)) {
return;
}
System.out.println("say:" + aWords);
}
public void go(String anPlace) {
GoEvent e = new GoEvent(this, anPlace);
if (!this.fireEvent(e)) {
return;
}
System.out.println("go:" + anPlace);
}
}
/**
* @param args
*/
public static void main(String[] args) {
new Test().run();
}
@SuppressWarnings("unchecked")
public void run() {
Person person = new Person();
person.addListener(SpeakEvent.class, new SpeakListener() {
@Override
public boolean handleEvent(SpeakEvent anEvent) {
// anEvent.stopEvent();
System.out.println("One person want to say:" + anEvent.words);
return true;
}
});
person.addListener(GoEvent.class, new GoListener() {
@Override
public boolean handleEvent(GoEvent anEvent) {
// anEvent.stopEvent();
System.out.println("One person want to go:" + anEvent.where);
return true;
}
});
person.say("Hello world!");
person.go("Home!");
}
}
@@ -0,0 +1,113 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.core.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* 过滤器
*/
public class CharacterEncodingFilter implements Filter {
/**
* 对 HttpServletRequestWrapper 进行扩充, 不影响原来的功能并能提供所有的 HttpServletRequest
* 接口中的功能. 它可以统一的对 Tomcat 默认设置下的中文问题进行解决而只需要用新的 Request 对象替换页面中的 request
* 对象即可.
*/
protected String encoding = null;
protected FilterConfig filterConfig = null;
// protected boolean ignore = true;
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
class Request extends HttpServletRequestWrapper {
public Request(HttpServletRequest request) {
super(request);
}
/**
* 转换由表单读取的数据的内码. 从 ISO 字符转到 utf-8(或gbk).
*/
public String toChi(String input) {
try {
byte[] bytes = input.getBytes("ISO-8859-1");
return new String(bytes, encoding);
} catch (Exception ex) {
}
return null;
}
/**
* Return the HttpServletRequest holded by this object.
*/
private HttpServletRequest getHttpServletRequest() {
return (HttpServletRequest) super.getRequest();
}
/**
* 读取参数 -- 修正了中文问题.
*/
@Override
public String getParameter(String name) {
return toChi(getHttpServletRequest().getParameter(name));
}
/**
* 读取参数列表 - 修正了中文问题.
*/
@Override
public String[] getParameterValues(String name) {
String values[] = getHttpServletRequest().getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = toChi(values[i]);
}
}
return values;
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
HttpServletRequest httpreq = (HttpServletRequest) request;
if (httpreq.getMethod().equals("POST")) {
request.setCharacterEncoding(encoding);
} else {
request = new Request(httpreq);
}
chain.doFilter(request, response);
}
/**
* Place this filter into service.
* @param filterConfig The filter configuration object
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 875 B

@@ -0,0 +1 @@
服务端事件监视器,监视服务器组件的事件是否正确触发。
Binary file not shown.

After

Width:  |  Height:  |  Size: 810 B

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<project path="" name="Comet4J JavaScript Client" author="jinghai.xiao@gamil.com" version="0.1.7" copyright="$projectName V$version&#xD;&#xA;Copyright(c) 2011, $author.&#xD;&#xA;http://code.google.com/p/comet4j/&#xD;&#xA;This code is licensed under BSD license. Use it as you wish, &#xD;&#xA;but keep this copyright intact." output="$project\build" source="True" source-dir="$output\source" minify="False" min-dir="$output\build" doc="False" doc-dir="$output\docs" master="true" master-file="$output\yui-ext.js" zip="true" zip-file="$output\yuo-ext.$version.zip">
<target name="comet4j-0.1.7.js" file="$output\comet4j-0.1.7.js" debug="True" shorthand="False" shorthand-list="YAHOO.util.Dom.setStyle&#xD;&#xA;YAHOO.util.Dom.getStyle&#xD;&#xA;YAHOO.util.Dom.getRegion&#xD;&#xA;YAHOO.util.Dom.getViewportHeight&#xD;&#xA;YAHOO.util.Dom.getViewportWidth&#xD;&#xA;YAHOO.util.Dom.get&#xD;&#xA;YAHOO.util.Dom.getXY&#xD;&#xA;YAHOO.util.Dom.setXY&#xD;&#xA;YAHOO.util.CustomEvent&#xD;&#xA;YAHOO.util.Event.addListener&#xD;&#xA;YAHOO.util.Event.getEvent&#xD;&#xA;YAHOO.util.Event.getTarget&#xD;&#xA;YAHOO.util.Event.preventDefault&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Event.stopPropagation&#xD;&#xA;YAHOO.util.Event.stopEvent&#xD;&#xA;YAHOO.util.Anim&#xD;&#xA;YAHOO.util.Motion&#xD;&#xA;YAHOO.util.Connect.asyncRequest&#xD;&#xA;YAHOO.util.Connect.setForm&#xD;&#xA;YAHOO.util.Dom&#xD;&#xA;YAHOO.util.Event">
<include name="src\JS.js" />
<include name="src\Observable.js" />
<include name="src\XMLHttpRequest.js" />
<include name="src\AJAX.js" />
<include name="src\Connector.js" />
<include name="src\Engine.js" />
</target>
<directory name="src" />
<file name="src\AJAX.js" path="" />
<file name="src\Connector.js" path="" />
<file name="src\Engine.js" path="" />
<file name="src\JS.js" path="" />
<file name="src\Observable.js" path="" />
<file name="src\XMLHttpRequest.js" path="" />
</project>
Binary file not shown.

After

Width:  |  Height:  |  Size: 854 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 962 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 815 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 925 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 911 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,104 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.event;
import java.util.ArrayList;
import java.util.List;
/**
* 事件源 一个事件源代一个事件种类,并管理这种事件的侦听。 职责:对于侦听的管理和执行
* @author xiaojinghai@kedacom.com
*/
@SuppressWarnings("rawtypes")
public class EventSource<E extends Event, L extends ListenerInterface<E>> {
protected List<L> listeners = new ArrayList<L>();
public EventSource() {
}
/**
* 触发所有侦听函数
* @param anEvent
* @return
*/
public boolean fire(E anEvent) {
synchronized (listeners) {
for (int i = listeners.size() - 1; i >= 0; i--) {
L listener = listeners.get(i);
if (anEvent.hasStoped()) {
return false;
}
if (anEvent.hasPreventDefault()) {
break;
}
if (!listener.handleEvent(anEvent)) { // 等同于hasStoped
return false;
}
}
}
return anEvent.hasStoped() ? false : true;
}
/**
* 添加侦听函数
* @param aListener
*/
public void addListener(L aListener) {
synchronized (listeners) {
listeners.add(aListener);
}
}
/**
* 删除指定的侦听函数
* @param aListener
*/
public void removeListener(L aListener) {
synchronized (listeners) {
listeners.remove(aListener);
}
}
/**
* 删除所有侦听
*/
public void removeAllListeners() {
synchronized (listeners) {
listeners.clear();
}
}
/**
* 得到某个侦听函数
* @param aListener
* @return
*/
public L getListener(L aListener) {
for (L l : listeners) {
if (l == aListener) {
return l;
}
}
return null;
}
/**
* 获取所有侦听函数
* @return
*/
public List<L> getListeners() {
return listeners;
}
public void destroy() {
removeAllListeners();
listeners = null;
}
}
@@ -0,0 +1,39 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Language" content="zh-cn" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ChatDemo</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript" src="js/comet4j-0.1.7.js"></script>
<script type="text/javascript" src="js/chat.js?v=0.1"></script>
</head>
<body onload="init()">
<div id="statebar">
连接状态:<span id="workStyle"></span>
连接数量:<span id="connectorCount"></span>
已用内存:<span id="usedMemory"></span>
可用内存:<span id="freeMemory"></span>
内存容量:<span id="totalMemory"></span>
最大容量:<span id="maxMemory"></span>
系统已运行:<span id="startup"></span>
</div>
<div id="logbox">
</div>
<div id="toolbar" >
请输入:<input maxlength="200" id="inputbox" class="inputbox" onkeypress="return onSendBoxEnter(event);" type="text" ></input>
<input type="button" class="button" onclick="send(inputbox.value);" value="回车发送"></input>
<input type="button" class="button" onclick="rename();" value="改名"></input>
</div>
<div id="login">
请输入昵称:<input type="text" class="inputbox" maxlength="50" id="loginName" onkeypress="return loginEnter(event);"></input>
<input type="button" class="button" onclick="login();" value="确定"></input>
</div>
</body>
</html>
@@ -0,0 +1,73 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.core;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.CometEvent;
import org.apache.catalina.CometProcessor;
/**
* 连接前端Servlet,负责处理连接请求,并转交给引擎处理。
*/
public class CometServletTomcat6 extends HttpServlet implements CometProcessor {
private static final long serialVersionUID = 1L;
public CometServletTomcat6() {
super();
}
/*
* @see
* org.apache.catalina.CometProcessor#event(org.apache.catalina.CometEvent)
*/
public void event(CometEvent event) throws IOException, ServletException {
HttpServletRequest request = event.getHttpServletRequest();
HttpServletResponse response = event.getHttpServletResponse();
// request.setAttribute("org.apache.tomcat.comet.timeout",
// CometContext.getInstance().getTimeout());
if (event.getEventType() == CometEvent.EventType.BEGIN) {
event.setTimeout(CometContext.getInstance().getTimeout());
String action = request.getParameter(CometProtocol.FLAG_ACTION);
if (CometProtocol.CMD_CONNECT.equals(action)) {
CometContext.getInstance().getEngine().connect(request, response);
event.close();
} else if (CometProtocol.CMD_REVIVAL.equals(action)) {
CometContext.getInstance().getEngine().revival(request, response);
} else if (CometProtocol.CMD_DROP.equals(action)) {
CometContext.getInstance().getEngine().drop(request, response);
event.close();
}
} else if (event.getEventType() == CometEvent.EventType.ERROR) {
if (event.getEventSubType() == CometEvent.EventSubType.TIMEOUT) {
CometContext.getInstance().getEngine().dying(request, response);
event.close();
} else {
CometContext.getInstance().getEngine().drop(request, response);
event.close();
}
} else if (event.getEventType() == CometEvent.EventType.END) {
CometContext.getInstance().getEngine().dying(request, response);
event.close();
} else if (event.getEventType() == CometEvent.EventType.READ) {
event.close();
}
}
@Override
public void destroy() {
super.destroy();
}
}
@@ -0,0 +1,83 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.core;
/**
* 用于封装向客户端发送信息的数据格式
*/
public class CometMessage {
/** 应用模块标识 */
private String channel;
private long time;// 发送时间
private Object data;// 包含数据
public CometMessage(Object anData, String aChannel) {
data = anData;
channel = aChannel;
time = System.currentTimeMillis();
}
/**
* 获取发送时间
* @return
*/
public long getTime() {
return time;
}
/**
* 设置发送时间
* @param time
*/
public void setTime(long time) {
this.time = time;
}
/**
* 获取被发送数据
* @return
*/
public Object getData() {
return data;
}
/**
* 设置被发送数据
* @param data
*/
public void setData(Object data) {
this.data = data;
}
/**
* 获取通道标识
* @return
*/
public String getChannel() {
return channel;
}
/**
* 设置通道标识
* @param channel
*/
public void setChannel(String channel) {
this.channel = channel;
}
public void destroy() {
data = null;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 919 B

@@ -0,0 +1,24 @@
package org.comet4j.demo.eventmonitor;
import org.comet4j.core.event.BeforeConnectEvent;
import org.comet4j.core.listener.BeforeConnectListener;
/**
* (用一句话描述类的主要功能)
* @author xiaojinghai
* @date 2011-3-9
*/
public class BeforeConnectEventListener extends BeforeConnectListener {
/*
* (non-Jsdoc)
* @see org.comet4j.event.Listener#handleEvent(org.comet4j.event.Event)
*/
@Override
public boolean handleEvent(BeforeConnectEvent anEvent) {
System.out.println("[BeforeConnectEvent]:");
return true;
}
}
@@ -0,0 +1,38 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.core.event;
import org.comet4j.core.CometConnection;
import org.comet4j.core.CometEngine;
import org.comet4j.event.Event;
/**
* 连接复活事件对象
*/
public class RevivalEvent extends Event<CometEngine> {
private CometConnection conn;
public RevivalEvent(CometEngine target, CometConnection anConn) {
super(target);
conn = anConn;
}
public CometConnection getConn() {
return conn;
}
public void setConn(CometConnection conn) {
this.conn = conn;
}
@Override
public void destroy() {
super.destroy();
conn = null;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1001 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 925 B

@@ -0,0 +1,355 @@
JS.ns("JS.HTTPStatus","JS.XMLHttpRequest");
/**
* FC 2616 HTTP1.1规范的HTTP Status状态常量,详见
* http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10
* @author jinghai.xiao@gmail.com
*/
JS.HTTPStatus = {
//Informational 1xx
'100' : 'Continue',
'101' : 'Switching Protocols',
//Successful 2xx
'200' : 'OK',
'201' : 'Created',
'202' : 'Accepted',
'203' : 'Non-Authoritative Information',
'204' : 'No Content',
'205' : 'Reset Content',
'206' : 'Partial Content',
//Redirection 3xx
'300' : 'Multiple Choices',
'301' : 'Moved Permanently',
'302' : 'Found',
'303' : 'See Other',
'304' : 'Not Modified',
'305' : 'Use Proxy',
'306' : 'Unused',
'307' : 'Temporary Redirect',
//Client Error 4xx
'400' : 'Bad Request',
'401' : 'Unauthorized',
'402' : 'Payment Required',
'403' : 'Forbidden',
'404' : 'Not Found',
'405' : 'Method Not Allowed',
'406' : 'Not Acceptable',
'407' : 'Proxy Authentication Required',
'408' : 'Request Timeout',
'409' : 'Conflict',
'410' : 'Gone',
'411' : 'Length Required',
'412' : 'Precondition Failed',
'413' : 'Request Entity Too Large',
'414' : 'Request-URI Too Long',
'415' : 'Unsupported Media Type',
'416' : 'Requested Range Not Satisfiable',
'417' : 'Expectation Failed',
//Server Error 5xx
'500' : 'Internal Server Error',
'501' : 'Not Implemented',
'502' : 'Bad Gateway',
'503' : 'Service Unavailable',
'504' : 'Gateway Timeout',
'505' : 'HTTP Version Not Supported'
};
JS.HTTPStatus.OK = 200;
JS.HTTPStatus.BADREQUEST = 400;
JS.HTTPStatus.FORBIDDEN = 403;
JS.HTTPStatus.NOTFOUND = 404;
JS.HTTPStatus.TIMEOUT = 408;
JS.HTTPStatus.SERVERERROR = 500;
/**
* @class JS.XMLHttpRequest
* @extends JS.Observable
* 跨浏览器、事件驱动的XMLHTTPRequest对象,此对象完全兼容传统XMLHTTPRequest对象,在遵循
* http://www.w3.org/TR/XMLHttpRequest/标准的前提下有所扩展。
* @author jinghai.xiao@gmail.com
*/
JS.XMLHttpRequest = JS.extend(JS.Observable,{
/**
* @cfg {Boolean} enableCache
* 是否启用缓存,默认为false
*/
enableCache : false,
/**
* @cfg {Number} timeout
* 请求超时毫秒数,默认为30000(30秒),设置为0则永不超时
*/
timeout : 30000,//default never time out
/**
* 是否调用了abort方法
* @property
* @type Boolean
*/
isAbort : false,
/**
* @cfg {String} specialXHR
* 指定一个特定的ActiveX对象名称用于取代XMLHTTPRequest对象,默认为空。
*/
specialXHR : '',//指定使用特殊的xhr对象
//propoty
_xhr : null,
//--------request propoty--------
/**
* @property
* @type Number
*/
readyState : 0,
//--------response propoty--------
/**
* @property
* @type Number
*/
status : 0,
/**
* @property
* @type String
*/
statusText : '',
/**
* @property
* @type String
*/
responseText : '',
/**
* @property
* @type DOM
*/
responseXML : null,
//private method
constructor : function(){
var self = this;
this.addEvents([
/**
* @event readyStateChange 当readyState发生变化
* @param {Number} readyState
* @param {Number} status
* @param {JS.XMLHttpRequest} xhr
* @param {XMLHTTPRequest} realXhr 实际使用的XMLHTTPRequest对象
*/
'readyStateChange',
/**
* @event timeout 请求超时
* @param {JS.XMLHttpRequest} xhr
* @param {XMLHTTPRequest} realXhr 实际使用的XMLHTTPRequest对象
*/
'timeout',
/**
* @event abort 主动取消
* @param {JS.XMLHttpRequest} xhr
* @param {XMLHTTPRequest} realXhr 实际使用的XMLHTTPRequest对象
*/
'abort',
/**
* @event error 请求出错
* @param {JS.XMLHttpRequest} xhr
* @param {XMLHTTPRequest} realXhr 实际使用的XMLHTTPRequest对象
*/
'error',
/**
* @event load 接收完毕
* @param {JS.XMLHttpRequest} xhr
* @param {XMLHTTPRequest} realXhr 实际使用的XMLHTTPRequest对象
*/
'load',
/**
* @event progress 正在接收
* @param {JS.XMLHttpRequest} xhr
* @param {XMLHTTPRequest} realXhr 实际使用的XMLHTTPRequest对象
*/
'progress'
]);
JS.XMLHttpRequest.superclass.constructor.apply(this,arguments);
this._xhr = this.createXmlHttpRequestObject();
this._xhr.onreadystatechange = function(){
self.doReadyStateChange();
};
},
//private
//超时任务
timeoutTask : null,
//延迟执行超时任务(timeoutTask)
delayTimeout : function(){
if(this.timeout){
if(!this.timeoutTask){
this.timeoutTask = new JS.DelayedTask(function(){
//readyState=4已经停止,由doReadyStateChange来判断为何停止
if(this._xhr.readyState != 4){
this.fireEvent('timeout', this, this._xhr);
}else{
this.cancelTimeout();
}
},this);
}
this.timeoutTask.delay(this.timeout);
}
},
//取消超时任务
cancelTimeout : function(){
if(this.timeoutTask){
this.timeoutTask.cancel();
}
},
createXmlHttpRequestObject : function(){
var activeX = [
'Msxml2.XMLHTTP.6.0',
'Msxml2.XMLHTTP.5.0',
'Msxml2.XMLHTTP.4.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP'],
xhr,
specialXHR = this.specialXHR;
if(specialXHR){//如果指定了xhr对象
if(JS.isString(specialXHR)){
return new ActiveXObject(specialXHR);
}else{
return specialXHR;
}
}
try {
xhr = new XMLHttpRequest();
} catch(e) {
for (var i = 0; i < activeX.length; ++i) {
try {
xhr = new ActiveXObject(activeX[i]);
break;
} catch(e) {}
}
} finally {
return xhr;
}
},
//private
doReadyStateChange : function(){
this.delayTimeout();
var xhr = this._xhr;
try{
this.readyState = xhr.readyState;
}catch(e){
this.readyState = 0;
}
try{
this.status = xhr.status;
}catch(e){
this.status = 0;
}
try{
this.statusText = xhr.statusText;
}catch(e){
this.statusText = "";
}
try {
this.responseText = xhr.responseText;
}catch(e){
this.responseText = "";
}
try {
this.responseXML = xhr.responseXML;
}catch(e){
this.responseXML = null;
}
this.fireEvent('readyStateChange',this.readyState, this.status, this, xhr );
if(this.readyState == 3 && (this.status >= 200 && this.status < 300)){
this.fireEvent('progress', this, xhr);
}
if(this.readyState == 4){
this.cancelTimeout();
var status = this.status ;
if(status == 0 || status == ""){
this.fireEvent('error', this, xhr);
}else if(status >= 200 && status < 300){
this.fireEvent('load', this, xhr);
}else if(status >= 400 && status != 408){
this.fireEvent('error', this, xhr);
}else if(status == 408){
this.fireEvent('timeout', this, xhr);
}
}
this.onreadystatechange();
},
/**
* 兼容标准的onreadystatechange
* @method
*/
onreadystatechange : function(){
},
//--------request--------
/**
* 兼容标准的open方法
* @method
*/
open : function(method, url, async, username, password){
if(!url){
return;
}
if(!this.enableCache){
if(url.indexOf('?') != -1){
url += '&ram='+Math.random();
}else{
url += '?ram='+Math.random();
}
}
this._xhr.open(method, url, async, username, password);
},
/**
* 兼容标准的send方法
* @method
*/
send : function(content){
this.delayTimeout();
this.isAbort = false;
this._xhr.send(content);
},
/**
* 兼容标准的abort方法
* @method
*/
abort : function(){
this.isAbort = true;
this.cancelTimeout();
this._xhr.abort();
if(JS.isIE){//IE在abort后会清空侦听
var self = this;
self._xhr.onreadystatechange = function(){
self.doReadyStateChange();
};
}
this.fireEvent('abort',this,this._xhr);
},
/**
* 兼容标准的setRequestHeader方法
* @method
*/
setRequestHeader : function(header, value){
this._xhr.setRequestHeader(header,value);
},
//--------request--------
/**
* 兼容标准的getResponseHeader方法
* @method
*/
getResponseHeader : function(header){
return this._xhr.getResponseHeader(header);
},
/**
* 兼容标准的getAllResponseHeaders方法
* @method
*/
getAllResponseHeaders : function(){
return this._xhr.getAllResponseHeaders();
},
/**
* 设置客户端超时时间
* @method
*/
setTimeout : function(t){
this.timeout = t;
}
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 923 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 956 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 819 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 823 B

@@ -0,0 +1,73 @@
package org.comet4j.demo.requestmonitor;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.comet4j.core.CometContext;
import org.comet4j.core.CometProtocol;
/**
* 应用初始化
* @author jinghai.xiao@gmail.com
* @date 2011-2-25
*/
public class AppInit implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener,
ServletRequestListener {
// ServletContextListener
public void contextInitialized(ServletContextEvent event) {
CometContext cc = CometContext.getInstance();
cc.registChannel(Constant.AppChannel);
}
public void contextDestroyed(ServletContextEvent event) {
}
// HttpSessionListener
public void sessionCreated(HttpSessionEvent event) {
HttpSession session = event.getSession();
// System.out.println("Session:" + session.getId() + "创建了");
}
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session = event.getSession();
// System.out.println("Session:" + session.getId() + "销毁了");
}
// HttpSessionAttributeListener
public void attributeAdded(HttpSessionBindingEvent event) {
// System.out.println("Session中增加了:" + event.getName() + "属性");
}
public void attributeRemoved(HttpSessionBindingEvent event) {
// System.out.println("Session中删除了:" + event.getName() + "属性");
}
public void attributeReplaced(HttpSessionBindingEvent event) {
// System.out.println("Session中修改了:" + event.getName() + "属性");
}
// ServletRequestListener
public void requestInitialized(ServletRequestEvent event) {
HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
System.out.println("请求:" + request.getRequestURI() + ","+CometProtocol.FLAG_ACTION+":" + request.getParameter(CometProtocol.FLAG_ACTION) + ",cId:"
+ request.getParameter("cid"));
}
public void requestDestroyed(ServletRequestEvent event) {
HttpServletRequest request = (HttpServletRequest) event.getServletRequest();
// System.out.println("请求完毕:" + request.getRequestURI());
}
}
@@ -0,0 +1,39 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.core.event;
import javax.servlet.http.HttpServletRequest;
import org.comet4j.core.CometEngine;
import org.comet4j.event.Event;
/**
* 即将断开前的事件对象
*/
public class BeforeDropEvent extends Event<CometEngine> {
private HttpServletRequest request;
public BeforeDropEvent(CometEngine target, HttpServletRequest aRequest) {
super(target);
request = aRequest;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
@Override
public void destroy() {
super.destroy();
request = null;
}
}
@@ -0,0 +1,52 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.core.temp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ReadJARResource {
public static void main(String[] args) throws IOException {
String jarName = "C://VODOSSClient.jar";
String fileName = "client.properties";
JarFile jarFile = new JarFile(jarName);// 读入jar文件
JarEntry entry = jarFile.getJarEntry(fileName);
InputStream input = jarFile.getInputStream(entry);// 读入需要的文件
readFile(input);
jarFile.close();
}
private static void readFile(InputStream input)
throws IOException {
InputStreamReader isr =
new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 981 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 916 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 839 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

@@ -0,0 +1,25 @@
function _pr_isIE6(){var F=navigator&&navigator.userAgent&&/\bMSIE 6\./.test(navigator.userAgent);_pr_isIE6=function(){return F};return F}var aa="break continue do else for if return while ",ba="auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile ",ca="catch class delete false import new operator private protected public this throw true try ",da="alignof align_union asm axiom bool concept concept_map const_cast constexpr decltype dynamic_cast explicit export friend inline late_check mutable namespace nullptr reinterpret_cast static_assert static_cast template typeid typename typeof using virtual wchar_t where ",
ea="boolean byte extends final finally implements import instanceof null native package strictfp super synchronized throws transient ",fa="as base by checked decimal delegate descending event fixed foreach from group implicit in interface internal into is lock object out override orderby params readonly ref sbyte sealed stackalloc string select uint ulong unchecked unsafe ushort var ",ga="debugger eval export function get null set undefined var with Infinity NaN ",ha="caller delete die do dump elsif eval exit foreach for goto if import last local my next no our print package redo require sub undef unless until use wantarray while BEGIN END ",
ia="and as assert class def del elif except exec finally from global import in is lambda nonlocal not or pass print raise try with yield False True None ",ja="alias and begin case class def defined elsif end ensure false in module next nil not or redo rescue retry self super then true undef unless until when yield BEGIN END ",ka="case done elif esac eval fi function in local set then until ",la="a",ma="z",na="A",oa="Z",pa="!",qa="!=",ra="!==",s="#",sa="%",Ha="%=",v="&",Ia="&&",Ja="&&=",Ka="&=",La=
"(",Ma="*",Na="*=",Oa="+=",Pa=",",Qa="-=",Ra="->",w="/",Sa="/=",Ta=":",Ua="::",y=";",z="<",Va="<<",Wa="<<=",Xa="<=",Ya="=",Za="==",$a="===",A=">",ab=">=",bb=">>",cb=">>=",db=">>>",eb=">>>=",fb="?",C="@",gb="[",hb="^",ib="^=",jb="^^",kb="^^=",lb="{",mb="|",nb="|=",ob="||",pb="||=",qb="~",rb="break",sb="case",tb="continue",ub="delete",vb="do",wb="else",xb="finally",yb="instanceof",zb="return",Ab="throw",Bb="try",Cb="typeof",Db="(?:(?:(?:^|[^0-9.])\\.{1,3})|(?:(?:^|[^\\+])\\+)|(?:(?:^|[^\\-])-)",Eb=
"|\\b",Fb="\\$1",Gb="|^)\\s*$",Hb="&amp;",Ib="&lt;",Jb="&gt;",Kb="&quot;",Lb="&#",Mb="x",Nb="'",G='"',Ob=" ",Pb="XMP",Qb="</",Rb='="',H="PRE",Sb='<!DOCTYPE foo PUBLIC "foo bar">\n<foo />',I="",Tb="\t",Ub="\n",Vb="nocode",Wb=' $1="$2$3$4"',J="pln",O="com",Xb="dec",P="src",Q="tag",R="atv",S="pun",Yb="<>/=",X="atn",Zb=" \t\r\n",Y="str",$b="'\"",ac="'\"`",bc="\"'",cc=" \r\n",Z="lit",dc="123456789",ec=".",fc="kwd",gc="typ",$="</span>",hc='<span class="',ic='">',jc="$1&nbsp;",kc="<br />",lc="console",mc=
"cannot override language handler %s",nc="default-code",oc="default-markup",pc="html",qc="htm",rc="xhtml",sc="xml",tc="xsl",uc="c",vc="cc",wc="cpp",xc="cs",yc="cxx",zc="cyc",Ac="java",Bc="bsh",Cc="csh",Dc="sh",Ec="cv",Fc="py",Gc="perl",Hc="pl",Ic="pm",Jc="rb",Kc="js",Lc="pre",Mc="code",Nc="xmp",Oc="prettyprint",Pc="class",Qc="br",Rc="\r\n";(function(){function F(b){b=b.split(/ /g);var a={};for(var c=b.length;--c>=0;){var d=b[c];if(d)a[d]=null}return a}var K=aa,Sc=K+ba,T=Sc+ca,ta=T+da,ua=T+ea,Tc=ua+
fa,va=T+ga,wa=ha,xa=K+ia,ya=K+ja,za=K+ka,Uc=ta+Tc+va+wa+xa+ya+za;function Vc(b){return b>=la&&b<=ma||b>=na&&b<=oa}function D(b,a,c,d){b.unshift(c,d||0);try{a.splice.apply(a,b)}finally{b.splice(0,2)}}var Wc=(function(){var b=[pa,qa,ra,s,sa,Ha,v,Ia,Ja,Ka,La,Ma,Na,Oa,Pa,Qa,Ra,w,Sa,Ta,Ua,y,z,Va,Wa,Xa,Ya,Za,$a,A,ab,bb,cb,db,eb,fb,C,gb,hb,ib,jb,kb,lb,mb,nb,ob,pb,qb,rb,sb,tb,ub,vb,wb,xb,yb,zb,Ab,Bb,Cb],a=Db;for(var c=0;c<b.length;++c){var d=b[c];a+=Vc(d.charAt(0))?Eb+d:mb+d.replace(/([^=<>:&])/g,Fb)}a+=
Gb;return new RegExp(a)})(),Aa=/&/g,Ba=/</g,Ca=/>/g,Xc=/\"/g;function Yc(b){return b.replace(Aa,Hb).replace(Ba,Ib).replace(Ca,Jb).replace(Xc,Kb)}function U(b){return b.replace(Aa,Hb).replace(Ba,Ib).replace(Ca,Jb)}var Zc=/&lt;/g,$c=/&gt;/g,ad=/&apos;/g,bd=/&quot;/g,cd=/&amp;/g,dd=/&nbsp;/g;function ed(b){var a=b.indexOf(v);if(a<0)return b;for(--a;(a=b.indexOf(Lb,a+1))>=0;){var c=b.indexOf(y,a);if(c>=0){var d=b.substring(a+3,c),g=10;if(d&&d.charAt(0)===Mb){d=d.substring(1);g=16}var e=parseInt(d,g);
if(!isNaN(e))b=b.substring(0,a)+String.fromCharCode(e)+b.substring(c+1)}}return b.replace(Zc,z).replace($c,A).replace(ad,Nb).replace(bd,G).replace(cd,v).replace(dd,Ob)}function Da(b){return Pb===b.tagName}function L(b,a){switch(b.nodeType){case 1:var c=b.tagName.toLowerCase();a.push(z,c);for(var d=0;d<b.attributes.length;++d){var g=b.attributes[d];if(!g.specified)continue;a.push(Ob);L(g,a)}a.push(A);for(var e=b.firstChild;e;e=e.nextSibling)L(e,a);if(b.firstChild||!/^(?:br|link|img)$/.test(c))a.push(Qb,
c,A);break;case 2:a.push(b.name.toLowerCase(),Rb,Yc(b.value),G);break;case 3:case 4:a.push(U(b.nodeValue));break}}var V=null;function fd(b){if(null===V){var a=document.createElement(H);a.appendChild(document.createTextNode(Sb));V=!/</.test(a.innerHTML)}if(V){var c=b.innerHTML;if(Da(b))c=U(c);return c}var d=[];for(var g=b.firstChild;g;g=g.nextSibling)L(g,d);return d.join(I)}function gd(b){var a=0;return function(c){var d=null,g=0;for(var e=0,h=c.length;e<h;++e){var f=c.charAt(e);switch(f){case Tb:if(!d)d=
[];d.push(c.substring(g,e));var i=b-a%b;a+=i;for(;i>=0;i-=" ".length)d.push(" ".substring(0,i));g=e+1;break;case Ub:a=0;break;default:++a}}if(!d)return c;d.push(c.substring(g));return d.join(I)}}var hd=/(?:[^<]+|<!--[\s\S]*?--\>|<!\[CDATA\[([\s\S]*?)\]\]>|<\/?[a-zA-Z][^>]*>|<)/g,id=/^<!--/,jd=/^<\[CDATA\[/,kd=/^<br\b/i,Ea=/^<(\/?)([a-zA-Z]+)/;function ld(b){var a=b.match(hd),c=[],d=0,g=[];if(a)for(var e=0,h=a.length;e<h;++e){var f=a[e];if(f.length>1&&f.charAt(0)===z){if(id.test(f))continue;
if(jd.test(f)){c.push(f.substring(9,f.length-3));d+=f.length-12}else if(kd.test(f)){c.push(Ub);++d}else if(f.indexOf(Vb)>=0&&!!f.replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g,Wb).match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/)){var i=f.match(Ea)[2],j=1;end_tag_loop:for(var m=e+1;m<h;++m){var o=a[m].match(Ea);if(o&&o[2]===i)if(o[1]===w){if(--j===0)break end_tag_loop}else++j}if(m<h){g.push(d,a.slice(e,m+1).join(I));e=m}else g.push(d,f)}else g.push(d,f)}else{var k=ed(f);c.push(k);d+=k.length}}return{source:c.join(I),
tags:g}}function E(b,a){var c={};(function(){var e=b.concat(a);for(var h=e.length;--h>=0;){var f=e[h],i=f[3];if(i)for(var j=i.length;--j>=0;)c[i.charAt(j)]=f}})();var d=a.length,g=/\S/;return function(e,h){h=h||0;var f=[h,J],i=I,j=0,m=e;while(m.length){var o,k=null,p,l=c[m.charAt(0)];if(l){p=m.match(l[1]);k=p[0];o=l[0]}else{for(var n=0;n<d;++n){l=a[n];var q=l[2];if(q&&!q.test(i))continue;p=m.match(l[1]);if(p){k=p[0];o=l[0];break}}if(!k){o=J;k=m.substring(0,1)}}f.push(h+j,o);j+=k.length;m=m.substring(k.length);
if(o!==O&&g.test(k))i=k}return f}}var md=E([],[[J,/^[^<]+/,null],[Xb,/^<!\w[^>]*(?:>|$)/,null],[O,/^<!--[\s\S]*?(?:--\>|$)/,null],[P,/^<\?[\s\S]*?(?:\?>|$)/,null],[P,/^<%[\s\S]*?(?:%>|$)/,null],[P,/^<(script|style|xmp)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/i,null],[Q,/^<\/?\w[^<>]*>/,null]]);function nd(b){var a=md(b);for(var c=0;c<a.length;c+=2)if(a[c+1]===P){var d,g;d=a[c];g=c+2<a.length?a[c+2]:b.length;var e=b.substring(d,g),h=e.match(/^(<[^>]*>)([\s\S]*)(<\/[^>]*>)$/);if(h)a.splice(c,2,d,Q,d+h[1].length,
P,d+h[1].length+(h[2]||I).length,Q)}return a}var od=E([[R,/^\'[^\']*(?:\'|$)/,null,Nb],[R,/^\"[^\"]*(?:\"|$)/,null,G],[S,/^[<>\/=]+/,null,Yb]],[[Q,/^[\w:\-]+/,/^</],[R,/^[\w\-]+/,/^=/],[X,/^[\w:\-]+/,null],[J,/^\s+/,null,Zb]]);function pd(b,a){for(var c=0;c<a.length;c+=2){var d=a[c+1];if(d===Q){var g,e;g=a[c];e=c+2<a.length?a[c+2]:b.length;var h=b.substring(g,e),f=od(h,g);D(f,a,c,2);c+=f.length-2}}return a}function u(b){var a=[],c=[];if(b.tripleQuotedStrings)a.push([Y,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
null,$b]);else if(b.multiLineStrings)a.push([Y,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,ac]);else a.push([Y,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,bc]);c.push([J,/^(?:[^\'\"\`\/\#]+)/,null,cc]);if(b.hashComments)a.push([O,/^#[^\r\n]*/,null,s]);if(b.cStyleComments){c.push([O,/^\/\/[^\r\n]*/,null]);c.push([O,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(b.regexLiterals)c.push([Y,/^\/(?=[^\/*])(?:[^\/\x5B\x5C]|\x5C[\s\S]|\x5B(?:[^\x5C\x5D]|\x5C[\s\S])*(?:\x5D|$))+(?:\/|$)/,
Wc]);var d=F(b.keywords);b=null;var g=E(a,c),e=E([],[[J,/^\s+/,null,cc],[J,/^[a-z_$@][a-z_$@0-9]*/i,null],[Z,/^0x[a-f0-9]+[a-z]/i,null],[Z,/^(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d+)(?:e[+\-]?\d+)?[a-z]*/i,null,dc],[S,/^[^\s\w\.$@]+/,null]]);function h(f,i){for(var j=0;j<i.length;j+=2){var m=i[j+1];if(m===J){var o,k,p,l;o=i[j];k=j+2<i.length?i[j+2]:f.length;p=f.substring(o,k);l=e(p,o);for(var n=0,q=l.length;n<q;n+=2){var r=l[n+1];if(r===J){var B=l[n],M=n+2<q?l[n+2]:p.length,x=f.substring(B,M);if(x===ec)l[n+
1]=S;else if(x in d)l[n+1]=fc;else if(/^@?[A-Z][A-Z$]*[a-z][A-Za-z$]*$/.test(x))l[n+1]=x.charAt(0)===C?Z:gc}}D(l,i,j,2);j+=l.length-2}}return i}return function(f){var i=g(f);i=h(f,i);return i}}var W=u({keywords:Uc,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function qd(b,a){for(var c=0;c<a.length;c+=2){var d=a[c+1];if(d===P){var g,e;g=a[c];e=c+2<a.length?a[c+2]:b.length;var h=W(b.substring(g,e));for(var f=0,i=h.length;f<i;f+=2)h[f]+=g;D(h,a,c,2);c+=h.length-2}}return a}
function rd(b,a){var c=false;for(var d=0;d<a.length;d+=2){var g=a[d+1],e,h;if(g===X){e=a[d];h=d+2<a.length?a[d+2]:b.length;c=/^on|^style$/i.test(b.substring(e,h))}else if(g===R){if(c){e=a[d];h=d+2<a.length?a[d+2]:b.length;var f=b.substring(e,h),i=f.length,j=i>=2&&/^[\"\']/.test(f)&&f.charAt(0)===f.charAt(i-1),m,o,k;if(j){o=e+1;k=h-1;m=f}else{o=e+1;k=h-1;m=f.substring(1,f.length-1)}var p=W(m);for(var l=0,n=p.length;l<n;l+=2)p[l]+=o;if(j){p.push(k,R);D(p,a,d+2,0)}else D(p,a,d,2)}c=false}}return a}function sd(b){var a=
nd(b);a=pd(b,a);a=qd(b,a);a=rd(b,a);return a}function td(b,a,c){var d=[],g=0,e=null,h=null,f=0,i=0,j=gd(8),m=/([\r\n ]) /g,o=/(^| ) /gm,k=/\r\n?|\n/g,p=/[ \r\n]$/,l=true;function n(r){if(r>g){if(e&&e!==h){d.push($);e=null}if(!e&&h){e=h;d.push(hc,e,ic)}var B=U(j(b.substring(g,r))).replace(l?o:m,jc);l=p.test(B);d.push(B.replace(k,kc));g=r}}while(true){var q;q=f<a.length?(i<c.length?a[f]<=c[i]:true):false;if(q){n(a[f]);if(e){d.push($);e=null}d.push(a[f+1]);f+=2}else if(i<c.length){n(c[i]);h=c[i+1];i+=
2}else break}n(b.length);if(e)d.push($);return d.join(I)}var N={};function t(b,a){for(var c=a.length;--c>=0;){var d=a[c];if(!N.hasOwnProperty(d))N[d]=b;else if(lc in window)console.log(mc,d)}}t(W,[nc]);t(sd,[oc,pc,qc,rc,sc,tc]);t(u({keywords:ta,hashComments:true,cStyleComments:true}),[uc,vc,wc,xc,yc,zc]);t(u({keywords:ua,cStyleComments:true}),[Ac]);t(u({keywords:za,hashComments:true,multiLineStrings:true}),[Bc,Cc,Dc]);t(u({keywords:xa,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),
[Ec,Fc]);t(u({keywords:wa,hashComments:true,multiLineStrings:true,regexLiterals:true}),[Gc,Hc,Ic]);t(u({keywords:ya,hashComments:true,multiLineStrings:true,regexLiterals:true}),[Jc]);t(u({keywords:va,cStyleComments:true,regexLiterals:true}),[Kc]);function Fa(b,a){try{var c=ld(b),d=c.source,g=c.tags;if(!N.hasOwnProperty(a))a=/^\s*</.test(d)?oc:nc;var e=N[a].call({},d);return td(d,g,e)}catch(h){if(lc in window){console.log(h);console.trace()}return b}}function ud(b){var a=_pr_isIE6(),c=[document.getElementsByTagName(Lc),
document.getElementsByTagName(Mc),document.getElementsByTagName(Nc)],d=[];for(var g=0;g<c.length;++g)for(var e=0;e<c[g].length;++e)d.push(c[g][e]);c=null;var h=0;function f(){var i=(new Date).getTime()+250;for(;h<d.length&&(new Date).getTime()<i;h++){var j=d[h];if(j.className&&j.className.indexOf(Oc)>=0){var m=j.className.match(/\blang-(\w+)\b/);if(m)m=m[1];var o=false;for(var k=j.parentNode;k;k=k.parentNode)if((k.tagName===Lc||k.tagName===Mc||k.tagName===Nc)&&k.className&&k.className.indexOf(Oc)>=
0){o=true;break}if(!o){var p=fd(j);p=p.replace(/(?:\r\n?|\n)$/,I);var l=Fa(p,m);if(!Da(j))j.innerHTML=l;else{var n=document.createElement(H);for(var q=0;q<j.attributes.length;++q){var r=j.attributes[q];if(r.specified){var B=r.name.toLowerCase();if(B===Pc)n.className=r.value;else n.setAttribute(r.name,r.value)}}n.innerHTML=l;j.parentNode.replaceChild(n,j);j=n}if(a&&j.tagName===H){var M=j.getElementsByTagName(Qc);for(var x=M.length;--x>=0;){var Ga=M[x];Ga.parentNode.replaceChild(document.createTextNode(Rc),
Ga)}}}}}if(h<d.length)setTimeout(f,250);else if(b)b()}f()}window.PR_normalizedHtml=L;window.prettyPrintOne=Fa;window.prettyPrint=ud;window.PR={createSimpleLexer:E,registerLangHandler:t,sourceDecorator:u,PR_ATTRIB_NAME:X,PR_ATTRIB_VALUE:R,PR_COMMENT:O,PR_DECLARATION:Xb,PR_KEYWORD:fc,PR_LITERAL:Z,PR_NOCODE:Vb,PR_PLAIN:J,PR_PUNCTUATION:S,PR_SOURCE:P,PR_STRING:Y,PR_TAG:Q,PR_TYPE:gc}})();
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>comet4j-test</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.maven.ide.eclipse.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.maven.ide.eclipse.maven2Nature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>
Binary file not shown.

After

Width:  |  Height:  |  Size: 118 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 288 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 952 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 904 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 955 B

@@ -0,0 +1,127 @@
/**
* @class JS.AJAX
* AJAX常用方法封装
* @singleton
* @author jinghai.xiao@gmail.com
*/
JS.ns("JS.AJAX");
JS.AJAX = (function(){
var xhr = new JS.XMLHttpRequest();
return {
dataFormatError : '服务器返回的数据格式有误',
urlError : '未指定url',
/**
* 以POST方式向服务器发送请求,并得到服务返回的xhr对象。<br>
* <pre>如:JS.Ajax.post('/someurl.do','keyword=xxx',function(xhr){
alert(xhr.responseText);
});</pre>
* @method
* @param {String} url 网址
* @param {String|DOM} param 参数
* @param {Function} callback 回调函数 function(xhr){alert(xhr.responseText)}
* @param {Object} scope 作用域
* @param {Boolean} asyn 是否异步调用,默认true
*/
post : function(url,param,callback,scope,asyn){
if(typeof url!=='string'){
throw new Error(this.urlError);
}
//默认为异步请求
var asynchronous = true;
if(asyn===false){
asynchronous = false;
}
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && asynchronous){
JS.callBack(callback,scope,[xhr]);
}
};
xhr.open('POST', url, asynchronous);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF8");
xhr.send(param || null);
if(!asynchronous){
JS.callBack(callback,scope,[xhr]);
}
},
/**
* 以GET方式向服务器发送请求,并得到服务返回的xhr对象。<br>
* <pre>如:JS.Ajax.get('/someurl.do','keyword=xxx',function(xhr){
alert(xhr.responseText);
});</pre>
* @method
* @param {String} url 网址
* @param {String|DOM} param 参数
* @param {Function} callback 回调函数 function(xhr){alert(xhr.responseText)}
* @param {Object} scope 作用域
* @param {Boolean} asyn 是否异步调用,默认true
*/
get : function(url,param,callback,scope,asyn){
if(typeof url!=='string'){
throw new Error(this.urlError);
}
//默认为异步请求
var asynchronous = true;
if(asyn===false){
asynchronous = false;
}
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && asynchronous){
JS.callBack(callback,scope,[xhr]);
}
};
xhr.open('GET', url, asynchronous);
xhr.setRequestHeader("Content-Type","html/text;charset=UTF8");
xhr.send(param || null);
if(!asynchronous){
JS.callBack(callback,scope,[xhr]);
}
},
/**
* 以GET方式向服务器发送请求,并得到服务返回的文本信息。<br>
* <pre>如:JS.Ajax.getText('/someurl.do','keyword=xxx',function(text){
alert(text);
});</pre>
* @method
* @param {String} url 网址
* @param {String|DOM} param 参数
* @param {Function} callback 回调函数 function(text){alert(text)}
* @param {Object} asyn 作用域
* @param {Boolean} asyn 是否异步调用,默认true
*/
getText : function(url,jsonData,callback,scope,asyn){
this.get(url,jsonData,function(xhr){
if(scope){
callback.call(scope,xhr.responseText);
}else{
callback(xhr.responseText);
}
},this,asyn);
},
/**
* 以GET方式向服务器发送请求,并得到服务返回的JSON对象。<br>
* <pre>如:JS.Ajax.getJson('/someurl.do','keyword=xxx',function(obj){
alert(obj.someField);
});</pre>
* @method
* @param {String} url 网址
* @param {String|DOM} param 参数
* @param {Function} callback 回调函数 function(obj){alert(alert(obj.someField);)}
* @param {Object} scope 作用域
* @param {Boolean} asyn 是否异步调用,默认true
*/
getJson : function(url,jsonData,callback,scope,asyn){
this.get(url,jsonData,function(xhr){
var json = null;
try{
json = eval("("+xhr.responseText+")");
}catch(e){
throw new Error(this.dataFormatError);
}
JS.callBack(callback,scope,[json]);
},this,asyn);
}
};
})();
@@ -0,0 +1,43 @@
/**
* @(#)CometContextEventListener.java 2011-3-9 Copyright 2011 it.kedacom.com,
* Inc. All rights reserved.
*/
package org.comet4j.demo.eventmonitor;
import org.comet4j.core.event.CometContextEvent;
import org.comet4j.core.listener.CometContextListener;
/**
* (用一句话描述类的主要功能)
* @author xiaojinghai
* @date 2011-3-9
*/
public class CometContextEventListener extends CometContextListener {
/*
* (non-Jsdoc)
* @see
* org.comet4j.core.listener.CometContextListener#onInitialized(org.comet4j
* .core.event.CometContextEvent)
*/
@Override
public boolean onInitialized(CometContextEvent event) {
System.out.println("[CometContextEvent]:subType=" + event.getSubType());
return false;
}
/*
* (non-Jsdoc)
* @see
* org.comet4j.core.listener.CometContextListener#onDestroyed(org.comet4j
* .core.event.CometContextEvent)
*/
@Override
public boolean onDestroyed(CometContextEvent event) {
// TODO 该方法尚未实现
return false;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 845 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 919 B

@@ -0,0 +1,327 @@
/**
* @class JS.Observable
* 事件模型
* @author jinghai.xiao@gmail.com
*/
JS.ns("JS.Observable");
JS.Observable = function(o){
JS.apply(this,o || JS.toArray(arguments)[0]);
if(this.events){
this.addEvents(this.events);
}
if(this.listeners){
this.on(this.listeners);
delete this.listeners;
}
};
JS.Observable.prototype = {
/**
* 添加侦听
* @method
* @param {String | Map<String|Function>} channelName 事件名称或多个事件名称和侦听函数的键值对
* @param {Function} fn 侦听函数
* @param {Object} scope 侦听函数作用域
*/
on : function(eventName, fn, scope, o){
if(JS.isString(eventName)){
this.addListener(eventName, fn, scope, o);
}else if(JS.isObject(eventName)){
this.addListeners(eventName,scope, o);
}
},
/**
* 触发事件
* @method
* @param {String} eventName 事件名称
* @param {[AnyType0~n...]} eventParam 事件参数,可以是0到N个
* @return {Boolean}
*/
fireEvent : function(){
var arg = JS.toArray(arguments),
eventName = arg[0].toLowerCase(),
e = this.events[eventName];
if(e && !JS.isBoolean(e)){
return e.fire.apply(e,arg.slice(1));
}
},
/**
* 注册事件类型
* @method
* @param {String} eventName 事件名称
*/
addEvent : function(eventName){
if(!JS.isObject(this.events)){
this.events = {};
}
if(this.events[eventName]){
return;
}
if(JS.isString(eventName)){
this.events[eventName.toLowerCase()] = true;
}else if(eventName instanceof JS.Event){
this.events[eventName.name.toLowerCase()] = eventName;
}
},
/**
* 批量注册事件类型
* @method
* @param {Array<String>} eventNames 事件名称
*/
addEvents : function(arr){
if(JS.isArray(arr)){
for(var i = 0,len = arr.length; i < len; i++){
this.addEvent(arr[i]);
}
}
},
/**
* 注册事件侦听
* @method
* @param {String} eventName 事件名称
* @param {Function} fn 侦听函数
* @param {Object} scope 侦听函数作用域
*/
addListener : function(eventName, fn, scope, o){//o配置项尚未实现
eventName = eventName.toLowerCase();
this.addEvent(eventName);
var e = this.events[eventName];
if(e){
if(JS.isBoolean(e)){
e = this.events[eventName] = new JS.Event(eventName,this);
}
e.addListener(fn, scope , o);
}
},
/**
* 批量注册事件侦听
* @method
* @param {Map<String,Function>} eventMap 事件名称与侦听函数的键值对
* @param {Function} fn 侦听函数
* @param {Object} scope 侦听函数作用域
*/
addListeners : function(obj,scope, o){
if(JS.isObject(obj)){
for(var p in obj){
this.addListener(p,obj[p],scope, o);
}
}
},
/**
* 移除事件侦听
* @method
* @param {String} eventName 事件名称
* @param {Function} fn 侦听函数
* @param {Object} scope 侦听函数作用域
*/
removeListener : function(eventName, fn, scope){
eventName = eventName.toLowerCase();
var e = this.events[eventName];
if(e && !JS.isBoolean(e)){
e.removeListener(fn, scope);
}
},
/**
* 移除所有事件侦听
* @method
*/
clearListeners : function(){
var events = this.events,
e;
for(var p in events){
e = events[p];
if(!JS.isBoolean(e)){
e.clearListeners();
}
}
},
/**
* 移除所有事件类型及事件侦听
* @method
*/
clearEvents : function(){
var events = this.events;
this.clearListeners();
for(var p in events){
this.removeEvent(p);
}
},
/**
* 移除事件类型
* @method
* @param {String} eventName 事件类型名称
*/
removeEvent : function(eventName){
var events = this.events,
e;
if(events[eventName]){
e = events[eventName];
if(!JS.isBoolean(e)){
e.clearListeners();
}
delete events[eventName];
}
},
/**
* 批量移除事件类型
* @method
* @param {Array<String>} 事件类型名称列表
*/
removeEvents : function(eventName){
if(JS.isString(eventName)){
this.removeEvent(eventName);
}else if(JS.isArray(eventName) && eventName.length > 0){
for(var i=0, len=eventName.length; i<len ;i++){
this.removeEvent(eventName[i]);
}
}
},
/**
* 检测是否具有指定的事件类型
* @method
* @param {String} 事件类型名称
*/
hasEvent : function(eventName){
return this.events[eventName.toLowerCase()]?true:false;
},
/**
* 检测是否具有指定的事件侦听
* @method
* @param {String} 事件类型名称
* @param {Function} fn 侦听函数
* @param {Object} scope 侦听函数作用域
*/
hasListener : function(eventName,fn,scope){
var events = this.events,
e = events[eventName];
if(!JS.isBoolean(e)){
return e.hasListener(fn,scope);
}
return false;
},
suspendEvents : function(){
//TODO:
},
resumeEvents : function(){
//TODO:
}
};
/**
* 事件源,代表一类事件,负责管理事件侦听
* @class JS.Event
* @author jinghai.xiao@gmail.com
*/
JS.Event = function(name,caller){
this.name = name.toLowerCase();
this.caller = caller;
this.listeners = [];
};
JS.Event.prototype = {
/**
* @method
* @return {Boolean}
*/
fire : function(){
var
listeners = this.listeners,
//len = listeners.length,
i = listeners.length-1;
for(; i > -1; i--){//TODO:fix 倒序
if(listeners[i].execute.apply(listeners[i],arguments) === false){
return false;
}
}
return true;
},
/**
* @method
* @param {Function} fn
* @param {Object} scope
*/
addListener : function(fn, scope,o){
scope = scope || this.caller;
if(this.hasListener(fn, scope) == -1){
this.listeners.push(new JS.Listener(fn, scope ,o));
}
},
/**
*
* @method
* @param {Function} fn
* @param {Object} scope
*/
removeListener : function(fn, scope){
var index = this.hasListener(fn, scope);
if(index!=-1){
this.listeners.splice(index, 1);
}
},
/**
*
* @method
* @param {Function} fn
* @param {Object} scope
*/
hasListener : function(fn, scope){
var i = 0,
listeners = this.listeners,
len = listeners.length;
for(; i<len; i++){
if(listeners[i].equal(fn, scope)){
return i;
}
}
return -1;
},
/**
*
* @method
*/
clearListeners : function(){
var i = 0,
listeners = this.listeners,
len = listeners.length;
for(; i<len; i++){
listeners[i].clear();
}
this.listeners.splice(0);
}
};
/**
* 事件侦听器,包装并统一侦听的调用方式
* @class JS.Listener
* @author jinghai.xiao@gmail.com
*/
JS.Listener = function(fn, scope,o){
this.handler = fn;
this.scope = scope;
this.o = o;//配置项,delay,buffer,once,
};
JS.Listener.prototype = {
/**
*
* @method
* @return {Boolean}
*/
execute : function(){
return JS.callBack(this.handler,this.scope,arguments);
},
/**
*
* @method
* @return {Boolean}
*/
equal : function(fn, scope){
return this.handler === fn /*&& this.scope === scope*/ ? true : false;
},
/**
*
* @method
*/
clear : function(){
delete this.handler;
delete this.scope ;
delete this.o ;
}
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 874 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 889 B

@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<doc>
<!--
Source section (required)
Use <source> to specify directory with JavaScript source files to be
processed or just one JS file. Directories are processed recursively.
Attributes:
src: (required) - source directory name or file name
match: (optional) - wildcard for the files. Default: "*.js"
skipHidden: (optional) - True to skip processing files and
directories with hidden attribute.
Default: true.
Custom tags section(optional)
Tags to be added to the list of custom tags, for every
"documantable item" i.e. class, cfg, property, event.
Custom tag list is accessible in XSLT-template and has two
properties: title and value.
name: (required) tag name. ex: "author" => "@author"
title: (optional) title of custom tag
format: (optional) pattern string used for formatting value
Usage example:
XML: <tag name="author" title="Author"/>
JS: /**
* @class MyClass
* @author I'm the
* author
*/
XSLT:
<xsl:if test="customTags">
<b><xsl:value-of select="customTags/title"/></b> :
<xsl:value-of select="customTags/value"/>
</xsl:if>
Resulting HTML:
<b>Author</b>:I'm the author
-->
<sources>
<source src="../build/source" match="*.js"/>
<!--<source src="ext" match="Ext*.js"/>-->
<!--source src="sample.js" /-->
</sources>
<tags>
<tag name="author" title="Author"/>
<tag name="version" title="Version"/>
<tag name="note" title="Note" format="&lt;i&gt;{0}&lt;/i&gt;"/>
<tag name="demo" title="Demo" format="&lt;a href=&quot;{0}&quot;&gt;{0}&lt;/a&gt;" />
</tags>
</doc>
Binary file not shown.

After

Width:  |  Height:  |  Size: 915 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 853 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 879 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 891 B

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="WebContent"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.WebProject">
<attributes>
<attribute name="hide" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.wst.jsdt.launching.baseBrowserLibrary"/>
<classpathentry kind="output" path=""/>
</classpath>
Binary file not shown.

After

Width:  |  Height:  |  Size: 300 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 911 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 930 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 830 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 898 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 839 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 988 B

@@ -0,0 +1,16 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.core.listener;
import org.comet4j.core.event.RemovedEvent;
import org.comet4j.event.Listener;
/**
* 移除连接事件侦听抽象类
*/
public abstract class RemovedListener extends Listener<RemovedEvent> {
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 835 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 851 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

@@ -0,0 +1,16 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.core.listener;
import org.comet4j.core.event.RevivalEvent;
import org.comet4j.event.Listener;
/**
* 连接复活事件侦听抽象类
*/
public abstract class RevivalListener extends Listener<RevivalEvent> {
}
@@ -0,0 +1,16 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.core.listener;
import org.comet4j.core.event.BeforeDropEvent;
import org.comet4j.event.Listener;
/**
* 连接即将断开事件侦听抽象类
*/
public abstract class BeforeDropListener extends Listener<BeforeDropEvent> {
}
@@ -0,0 +1,29 @@
/**
* @(#)BeforeDropEventListener.java 2011-3-9 Copyright 2011 it.kedacom.com, Inc.
* All rights reserved.
*/
package org.comet4j.demo.eventmonitor;
import org.comet4j.core.event.BeforeDropEvent;
import org.comet4j.core.listener.BeforeDropListener;
/**
* (用一句话描述类的主要功能)
* @author xiaojinghai
* @date 2011-3-9
*/
public class BeforeDropEventListener extends BeforeDropListener {
/*
* (non-Jsdoc)
* @see org.comet4j.event.Listener#handleEvent(org.comet4j.event.Event)
*/
@Override
public boolean handleEvent(BeforeDropEvent anEvent) {
System.out.println("[BeforeDropEvent]:cId=" + anEvent.getRequest().getParameter("cid"));
return true;
}
}
@@ -0,0 +1,55 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.demo.talker;
import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;
import org.comet4j.demo.talker.dto.HealthDTO;
/**
* 系统健康信息发送器
* @author xiaojinghai
* @date 2011-4-7
*/
public class HealthSender implements Runnable {
private static final CometEngine engine = CometContext.getInstance().getEngine();
private static final HealthDTO healthDto = new HealthDTO();
private static final long startup = System.currentTimeMillis();
@Override
public void run() {
while (true) {
try {
Thread.sleep(5000);
} catch (Exception ex) {
ex.printStackTrace();
}
long totalMemory = Runtime.getRuntime().totalMemory();
long freeMemory = Runtime.getRuntime().freeMemory();
long maxMemory = Runtime.getRuntime().maxMemory();
long usedMemory = totalMemory - freeMemory;
Integer connectorCount = engine.getConnections().size();
healthDto.setConnectorCount(connectorCount.toString());
healthDto.setFreeMemory(freeMemory);
healthDto.setMaxMemory(maxMemory);
healthDto.setTotalMemory(totalMemory);
healthDto.setUsedMemory(usedMemory);
long dif = System.currentTimeMillis() - startup;
long day_mill = 86400000;// 一天的毫秒数 60*60*1000*24
long hour_mill = 3600000;// 一小时的毫秒数 60*60*1000
Long day = dif / day_mill;
Long hour = (dif % day_mill) / hour_mill;
String str = day.toString() + "天 " + hour.toString() + "小时";
healthDto.setStartup(str);
engine.sendToAll(Constant.APP_CHANNEL, healthDto);
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,65 @@
/**
* @(#)WalleAPPListenner.java 2011-2-25 Copyright 2011 it.kedacom.com, Inc. All
* rights reserved.
*/
package org.comet4j.demo.sender;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;
/**
* (用一句话描述类的主要功能)
* @author xiaojinghai
* @date 2011-2-25
*/
public class AppInit implements ServletContextListener {
/**
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
// ServletContextListener
public void contextInitialized(ServletContextEvent arg0) {
CometContext cc = CometContext.getInstance();
cc.registChannel(Constant.AppChannel);
Thread helloAppModule = new Thread(new HelloAppModule(), "Sender App Module");
helloAppModule.setDaemon(true);
helloAppModule.start();
}
class HelloAppModule implements Runnable {
private int inc = 0;
public void run() {
while (true) {
try {
Thread.sleep(5000);
} catch (Exception ex) {
ex.printStackTrace();
}
CometEngine engine = CometContext.getInstance().getEngine();
engine.sendTo(Constant.AppChannel, engine.getConnections(), "This is the SenderAppModule Test,来自Sender"
+ inc);
inc++;
}
}
}
/**
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
// ServletContextListener
public void contextDestroyed(ServletContextEvent arg0) {
// TODO 该方法尚未实现
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 955 B

@@ -0,0 +1,31 @@
/**
* @(#)MessageEventListener.java 2011-3-9 Copyright 2011 it.kedacom.com, Inc.
* All rights reserved.
*/
package org.comet4j.demo.eventmonitor;
import org.comet4j.core.event.MessageEvent;
import org.comet4j.core.listener.MessageListener;
import org.comet4j.core.util.JSONUtil;
/**
* (用一句话描述类的主要功能)
* @author xiaojinghai
* @date 2011-3-9
*/
public class MessageEventListener extends MessageListener {
/*
* (non-Jsdoc)
* @see org.comet4j.event.Listener#handleEvent(org.comet4j.event.Event)
*/
@Override
public boolean handleEvent(MessageEvent anEvent) {
System.out.println("[MessageEvent]:cId=" + anEvent.getConn().getId() + "\ndata="
+ JSONUtil.object2json(anEvent.getData()));
return false;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 272 B

@@ -0,0 +1,10 @@
<html>
<head>
<title>The source code</title>
<link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="../resources/prettify/prettify.js"></script>
</head>
<body onload="prettyPrint();">
<pre class="prettyprint lang-js">###SOURCE###</pre>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1016 B

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="comet4j-war-tomcat7">
<wb-resource deploy-path="/" source-path="/WebContent"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src"/>
<property name="java-output-path" value="/comet4j-war-tomcat7/build/classes"/>
<property name="context-root" value="/"/>
</wb-module>
</project-modules>
Binary file not shown.

After

Width:  |  Height:  |  Size: 844 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 983 B

@@ -0,0 +1,484 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.core;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.comet4j.core.dto.ConnectionDTO;
import org.comet4j.core.event.BeforeConnectEvent;
import org.comet4j.core.event.BeforeDropEvent;
import org.comet4j.core.event.BeforeRemoveEvent;
import org.comet4j.core.event.ConnectEvent;
import org.comet4j.core.event.DropEvent;
import org.comet4j.core.event.DyingEvent;
import org.comet4j.core.event.ErrorEvent;
import org.comet4j.core.event.MessageEvent;
import org.comet4j.core.event.RemovedEvent;
import org.comet4j.core.event.RevivalEvent;
import org.comet4j.core.listener.BeforeConnectListener;
import org.comet4j.core.listener.BeforeDropListener;
import org.comet4j.core.listener.BeforeRemoveListener;
import org.comet4j.core.listener.ConnectListener;
import org.comet4j.core.listener.DropListener;
import org.comet4j.core.listener.DyingListener;
import org.comet4j.core.listener.MessageListener;
import org.comet4j.core.listener.RemovedListener;
import org.comet4j.core.listener.RevivalListener;
import org.comet4j.event.Observable;
/**
* 引擎,负责管理和维持连接,并能够必要的发送服务
*/
@SuppressWarnings({
"unchecked", "rawtypes"
})
public class CometEngine extends Observable {
private CometConnector ct;
private CometSender sender;
public CometEngine() {
this.addEvent(BeforeConnectEvent.class);
this.addEvent(ConnectEvent.class);
this.addEvent(BeforeDropEvent.class);
this.addEvent(DropEvent.class);
this.addEvent(DyingEvent.class);
this.addEvent(RevivalEvent.class);
this.addEvent(MessageEvent.class);
this.addEvent(ErrorEvent.class);// TODO:
CometContext cc = CometContext.getInstance();
sender = new CometSender(cc.getCacheExpires(), cc.getCacheFrequency());
ct = new CometConnector(cc.getConnExpires(), cc.getConnFrequency());
}
/**
* 建立用户连接
* @param request
* @param response
* @throws IOException
*/
void connect(HttpServletRequest request, HttpServletResponse response) throws IOException {
String uId = request.getParameter("uid");
CometContext.getInstance().log("【CometDebug】-->【connect】-->uid:" + uId);
CometConnection conn = new CometConnection(request, response);
BeforeConnectEvent be = new BeforeConnectEvent(this, request, response);
if (!this.fireEvent(be)) {
conn.getResponse().setStatus(HttpServletResponse.SC_BAD_REQUEST);
conn.getResponse().getWriter().close();
return;
}
ct.addConnection(conn);
CometContext cc = CometContext.getInstance();
ConnectionDTO cdto = new ConnectionDTO(conn.getId(), conn.getWorkStyle(), cc.getAppModules(), cc.getTimeout());
sendTo(CometProtocol.SYS_CHANNEL, conn, cdto);
try {// 强制关闭长连接工作模式下的输出
conn.getResponse().getWriter().close();
conn.setState(CometProtocol.STATE_DYING);
conn.setResponse(null);
conn.setDyingTime(System.currentTimeMillis());
} catch (Exception ex) {
} finally {
ConnectEvent e = new ConnectEvent(this, conn);
this.fireEvent(e);
}
}
void dying(HttpServletRequest request, HttpServletResponse response) throws IOException {
// response.setStatus(CometProtocol.HTTPSTATUS_TIMEOUT);
String uId = request.getParameter("uid");
String cId = request.getParameter("cid");
CometContext.getInstance().log("【CometDebug】-->【dying】-->cid:" + cId + "," + "uid:" + uId);
CometConnection conn = ct.getConnection(request);
if (conn != null) {
CometContext.getInstance().getEngine().sendTo(CometProtocol.SYS_CHANNEL, conn, CometProtocol.STATE_DYING);
}
try {
conn.getResponse().getWriter().close();
} catch (Exception exc) {
try {
response.getWriter().close();
} catch (Exception excp) {
excp.printStackTrace();
}
}
if (conn != null) {
conn.setState(CometProtocol.STATE_DYING);
conn.setResponse(null);
conn.setDyingTime(System.currentTimeMillis());
DyingEvent e = new DyingEvent(this, conn);
this.fireEvent(e);
}
}
void revival(HttpServletRequest request, HttpServletResponse response) throws IOException {
String cId = getConnectionId(request);
String uId = request.getParameter("uid");
CometContext.getInstance().log("【CometDebug】-->【revival】-->cid:" + cId + "," + "uid:" + uId);
if (cId == null) {
drop(request, response);
// throw new CometException("无法复活,断开连接。");
}
CometConnection conn = ct.getConnection(cId);
if (conn != null /* && CometProtocol.STATE_DYING.equals(conn.getState()) */) {
conn.setRequest(request);
conn.setResponse(response);
conn.setDyingTime(System.currentTimeMillis());
conn.setState(CometProtocol.STATE_ALIVE);
RevivalEvent e = new RevivalEvent(this, conn);
this.fireEvent(e);
sender.sendCacheMessage(conn);
} else {
drop(request, response);
// throw new CometException("非正常复活,断开连接。conn=" + conn);
}
}
/**
* 断开一个连接
* @param request
* @param response
* @throws IOException
*/
public void drop(HttpServletRequest request, HttpServletResponse response) throws IOException {
BeforeDropEvent be = new BeforeDropEvent(this, request);
if (!this.fireEvent(be)) {
return;
}
String cId = getConnectionId(request);
String uId = request.getParameter("uid");
CometContext.getInstance().log("【CometDebug】-->【drop】-->cid:" + cId + "," + "uid:" + uId);
CometConnection conn = null;
if (cId != null) {
conn = ct.getConnection(cId);
} else {
conn = ct.getConnection(request);
}
if (conn != null) {
remove(conn);
}
// response.setStatus(CometProtocol.HTTPSTATUS_ERROR);
response.getWriter().close();
}
void remove(CometConnection aConn) {
BeforeRemoveEvent be = new BeforeRemoveEvent(this, aConn);
if (!this.fireEvent(be)) {
return;
}
sender.getCacheMessage(aConn);
ct.removeConnection(aConn);
// Fixed nio endpoint exception
/*
* try { aConn.getResponse().getWriter().close(); } catch (Exception
* exc) { // 连接有可能是dying,此时getResponse为空是正常的,这里仅保证对有效的Response做出回应 }
*/
RemovedEvent re = new RemovedEvent(this, aConn);
this.fireEvent(re);
DropEvent de = new DropEvent(this, aConn);
this.fireEvent(de);
}
/**
* 按ID获取已有
* @param id
* @return
*/
public CometConnection getConnection(String id) {
return ct.getConnection(id);
}
/**
* 按Request对象获得连接对象
* @param request
* @return
*/
public CometConnection getConnection(HttpServletRequest request) {
String cId = getConnectionId(request);
CometConnection conn = null;
if (cId != null) {
conn = ct.getConnection(cId);
} else {
conn = ct.getConnection(request);
}
return conn;
}
/**
* 获得所有连接对象
* @return
*/
public List<CometConnection> getConnections() {
return ct.getConnections();
}
/**
* 向连接发送消息
* @param channel 应用通道标识
* @param c 连接对象
* @param data 数据
*/
public void sendTo(String channel, CometConnection c, Object data) {
CometMessage msg = new CometMessage(data, channel);
sender.sendTo(c, msg);
MessageEvent e = new MessageEvent(this, c, msg);
this.fireEvent(e);
}
/**
* 向连接发送批量数据
* @param channel 应用通道标识
* @param c 连接对象
* @param data 数据列表
*/
public void sendTo(String channel, CometConnection c, List<Object> data) {
for (Object o : data) {
sendTo(channel, c, o);
}
}
/**
* 向多个连接发送数据
* @param channel 应用通道标识
* @param list 连接对象列表
* @param data 数据
*/
public void sendTo(String channel, List<CometConnection> list, Object data) {
if (list.isEmpty()) {
return;
}
for (CometConnection c : list) {
sendTo(channel, c, data);
}
}
/**
* 向所有连接发送数据
* @param channel 应用通道标识
* @param data 数据
*/
public void sendToAll(String channel, Object data) {
List<CometConnection> list = this.getConnections();
if (list == null) {
return;
}
synchronized (list) {
for (CometConnection c : list) {
sendTo(channel, c, data);
}
}
}
/**
* 从Request对象中获取连接ID
* @param request
* @return
*/
public String getConnectionId(HttpServletRequest request) {
String id = request.getParameter(CometProtocol.FLAG_ID);
if (id == null || "".equals(id)) {
id = null;
}
return id;
}
/**
* 增加即将连接事件侦听,此事件动作可以被终止。
* @param li
*/
public void addBeforeConnectListener(BeforeConnectListener li) {
this.addListener(BeforeConnectEvent.class, li);
}
/**
* 移除即将连接事件侦听,此事件动作可以被终止。
* @param li
*/
public void removeBeforeConnectListener(BeforeConnectListener li) {
this.removeListener(BeforeConnectEvent.class, li);
}
/**
* 增加即将断开事件侦听,此事件动作可以被终止。
* @param li
*/
public void addBeforeDropListener(BeforeDropListener li) {
this.addListener(BeforeDropEvent.class, li);
}
/**
* 移除即将断开事件侦听,此事件动作可以被终止。
* @param li
*/
public void removeBeforeDropListener(BeforeDropListener li) {
this.removeListener(BeforeDropEvent.class, li);
}
/**
* 增加连接即将移除事件侦听,此事件动作可以被终止。
* @param li
*/
public void addBeforeRemoveListener(BeforeRemoveListener li) {
this.addListener(BeforeRemoveEvent.class, li);
}
/**
* 移除连接即将移除事件侦听,此事件动作可以被终止。
* @param li
*/
public void removeBeforeRemoveListener(BeforeRemoveListener li) {
this.removeListener(BeforeRemoveEvent.class, li);
}
/**
* 增加连接事件侦听
* @param li
*/
public void addConnectListener(ConnectListener li) {
this.addListener(ConnectEvent.class, li);
}
/**
* 移除连接事件侦听
* @param li
*/
public void removeConnectListener(ConnectListener li) {
this.removeListener(ConnectEvent.class, li);
}
/**
* 增加连接断开事件侦听
* @param li
*/
public void addDropListener(DropListener li) {
this.addListener(DropEvent.class, li);
}
/**
* 移除连接断开事件侦听
* @param li
*/
public void removeDropListener(DropListener li) {
this.removeListener(DropEvent.class, li);
}
/**
* 增加连接变为濒死状态事件侦听
* @param li
*/
public void addDyingListener(DyingListener li) {
this.addListener(DyingEvent.class, li);
}
/**
* 移除连接变为濒死状态事件侦听
* @param li
*/
public void removeDyingListener(DyingListener li) {
this.removeListener(DyingEvent.class, li);
}
/**
* 增加发送消息事件侦听
* @param li
*/
public void addMessageListener(MessageListener li) {
this.addListener(MessageEvent.class, li);
}
/**
* 移除发送消息事件侦听
* @param li
*/
public void removeMessageListener(MessageListener li) {
this.removeListener(MessageEvent.class, li);
}
/**
* 增加连接已删除事件侦听
* @param li
*/
public void addRemovedListener(RemovedListener li) {
this.addListener(RemovedEvent.class, li);
}
/**
* 移除连接已删除事件侦听
* @param li
*/
public void removeRemovedListener(RemovedListener li) {
this.removeListener(RemovedEvent.class, li);
}
/**
* 增加连接变为复活状态事件侦听
* @param li
*/
public void addRevivalListener(RevivalListener li) {
this.addListener(RevivalEvent.class, li);
}
/**
* 移除连接变为复活状态事件侦听
* @param li
*/
public void removeRevivalListener(RevivalListener li) {
this.removeListener(RevivalEvent.class, li);
}
@Override
public void destroy() {
super.destroy();
ct.init = false;
ct.destroy();
sender.destroy();
ct = null;
sender = null;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 908 B

@@ -0,0 +1,29 @@
/**
* @(#)DyingEventListener.java 2011-3-9 Copyright 2011 it.kedacom.com, Inc. All
* rights reserved.
*/
package org.comet4j.demo.eventmonitor;
import org.comet4j.core.event.DyingEvent;
import org.comet4j.core.listener.DyingListener;
/**
* (用一句话描述类的主要功能)
* @author xiaojinghai
* @date 2011-3-9
*/
public class DyingEventListener extends DyingListener {
/*
* (non-Jsdoc)
* @see org.comet4j.event.Listener#handleEvent(org.comet4j.event.Event)
*/
@Override
public boolean handleEvent(DyingEvent anEvent) {
System.out.println("[DyingEvent]:cId=" + anEvent.getConn().getId());
return false;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 871 B

@@ -0,0 +1,49 @@
/*
* Comet4J Copyright(c) 2011, http://code.google.com/p/comet4j/ This code is
* licensed under BSD license. Use it as you wish, but keep this copyright
* intact.
*/
package org.comet4j.demo.talker.dto;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 用户信息传输对象
* @author jinghai.xiao@gmail.com
* @date 2011-4-7
*/
public class UserDTO {
private final String transtime;
private String id;
private String name;
public UserDTO(String id, String name) {
this.id = id;
this.name = name;
Date d = new Date(System.currentTimeMillis());
SimpleDateFormat f = new SimpleDateFormat("HH:mm");
transtime = f.format(d);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTranstime() {
return transtime;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 834 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 925 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 853 B

Some files were not shown because too many files have changed in this diff Show More