├── bdb ├── je.lck ├── je.info.0.lck ├── 00000000.jdb └── je.info.0 ├── .gitignore ├── lib ├── asm-1.5.3.jar ├── h2-1.3.170.jar ├── javamelody.jar ├── je-5.0.58.jar ├── antlr-2.7.7.jar ├── cglib-2.1_3.jar ├── jetty-6.1.26.jar ├── log4j-1.2.15.jar ├── aopalliance-1.0.jar ├── aspectjrt-1.6.1.jar ├── fastjson-1.1.15.jar ├── jrobin-1.5.9.1.jar ├── memcached-2.0.1.jar ├── servlet-api-3.0.jar ├── slf4j-api-1.6.1.jar ├── commons-codec-1.5.jar ├── commons-dbcp-1.4.jar ├── commons-jexl-1.1.jar ├── commons-lang-2.5.jar ├── commons-pool-1.5.6.jar ├── jetty-util-6.1.26.jar ├── netty-3.2.2.Final.jar ├── aspectjweaver-1.6.1.jar ├── slf4j-log4j12-1.6.1.jar ├── commons-beanutils-1.8.3.jar ├── commons-httpclient-3.1.jar ├── commons-logging-1.1.1.jar ├── mybatis-3.1.0-SNAPSHOT.jar ├── commons-collections-3.2.1.jar ├── mybatis-spring-1.1.0-SNAPSHOT.jar ├── org.springframework.aop-3.1.0.RELEASE.jar ├── org.springframework.asm-3.1.0.RELEASE.jar ├── org.springframework.core-3.1.0.RELEASE.jar ├── org.springframework.jdbc-3.1.0.RELEASE.jar ├── org.springframework.orm-3.1.0.RELEASE.jar ├── org.springframework.test-3.1.0.RELEASE.jar ├── org.springframework.beans-3.1.0.RELEASE.jar ├── org.springframework.context-3.1.0.RELEASE.jar ├── org.springframework.expression-3.1.0.RELEASE.jar ├── org.springframework.transaction-3.1.0.RELEASE.jar └── org.springframework.context.support-3.1.0.RELEASE.jar ├── doc └── img │ └── performance.jpg ├── bin ├── rest-nettyserver-0.1.jar └── restart-server.sh ├── src ├── org │ └── langke │ │ ├── core │ │ ├── service │ │ │ ├── IService.java │ │ │ ├── DemoService.java │ │ │ └── impl │ │ │ │ └── DemoServiceImpl.java │ │ ├── dao │ │ │ ├── IDemoDao.java │ │ │ ├── mappers │ │ │ │ └── HelloTableMapper.java │ │ │ └── DemoDaoImpl.java │ │ ├── handler │ │ │ └── DemoHandler.java │ │ └── server │ │ │ ├── SpringApplicationContext.java │ │ │ ├── JavaMelodyMonitorServer.java │ │ │ └── RestNettyServer.java │ │ ├── common │ │ ├── server │ │ │ ├── Handler.java │ │ │ ├── Server.java │ │ │ ├── resp │ │ │ │ ├── RespData.java │ │ │ │ ├── ErrorResp.java │ │ │ │ └── Resp.java │ │ │ ├── ServerAddress.java │ │ │ ├── BaseNioServer.java │ │ │ ├── PathTrie.java │ │ │ ├── NettyHttpRequest.java │ │ │ ├── NetworkUtils.java │ │ │ └── RestChannelHandler.java │ │ ├── CostTime.java │ │ ├── bdb │ │ │ ├── BrekeleyDB.java │ │ │ ├── AbstractBerkeleyDB.java │ │ │ └── BrekeleyDBImpl.java │ │ ├── ExecutorFactory.java │ │ ├── CommonException.java │ │ ├── StringPair.java │ │ ├── StrIntBag.java │ │ ├── cache │ │ │ ├── PK.java │ │ │ ├── MemFlush.java │ │ │ ├── MemCaching.java │ │ │ ├── MemcachedUtil.java │ │ │ └── CacheManager.java │ │ ├── ServerAddress.java │ │ ├── ConnManager.java │ │ ├── Config.java │ │ └── Strings.java │ │ ├── bean │ │ └── HelloTable.java │ │ └── util │ │ ├── EncreptUtil.java │ │ ├── logging │ │ ├── slf4j │ │ │ ├── Slf4jESLoggerFactory.java │ │ │ └── Slf4jESLogger.java │ │ ├── jdk │ │ │ ├── JdkESLoggerFactory.java │ │ │ └── JdkESLogger.java │ │ ├── log4j │ │ │ ├── Log4jESLoggerFactory.java │ │ │ ├── Log4jESLogger.java │ │ │ └── ConsoleAppender.java │ │ ├── ESLoggerFactory.java │ │ ├── ESLogger.java │ │ ├── Loggers.java │ │ └── support │ │ │ ├── AbstractESLogger.java │ │ │ └── LoggerMessageFormat.java │ │ ├── MD5Util.java │ │ ├── DateUtil.java │ │ ├── FileUtil.java │ │ └── HttpClientUtil.java └── resources │ └── mappers │ └── hellotableMapper.xml ├── conf ├── config.properties ├── log4j.properties └── applicationContext.xml ├── .project ├── README.md └── .classpath /bdb/je.lck: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /bdb/je.info.0.lck: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /helloDB 2 | /h2 3 | /logs 4 | /.settings 5 | /build 6 | -------------------------------------------------------------------------------- /bdb/00000000.jdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/bdb/00000000.jdb -------------------------------------------------------------------------------- /lib/asm-1.5.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/asm-1.5.3.jar -------------------------------------------------------------------------------- /lib/h2-1.3.170.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/h2-1.3.170.jar -------------------------------------------------------------------------------- /lib/javamelody.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/javamelody.jar -------------------------------------------------------------------------------- /lib/je-5.0.58.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/je-5.0.58.jar -------------------------------------------------------------------------------- /lib/antlr-2.7.7.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/antlr-2.7.7.jar -------------------------------------------------------------------------------- /lib/cglib-2.1_3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/cglib-2.1_3.jar -------------------------------------------------------------------------------- /lib/jetty-6.1.26.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/jetty-6.1.26.jar -------------------------------------------------------------------------------- /lib/log4j-1.2.15.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/log4j-1.2.15.jar -------------------------------------------------------------------------------- /doc/img/performance.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/doc/img/performance.jpg -------------------------------------------------------------------------------- /lib/aopalliance-1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/aopalliance-1.0.jar -------------------------------------------------------------------------------- /lib/aspectjrt-1.6.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/aspectjrt-1.6.1.jar -------------------------------------------------------------------------------- /lib/fastjson-1.1.15.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/fastjson-1.1.15.jar -------------------------------------------------------------------------------- /lib/jrobin-1.5.9.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/jrobin-1.5.9.1.jar -------------------------------------------------------------------------------- /lib/memcached-2.0.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/memcached-2.0.1.jar -------------------------------------------------------------------------------- /lib/servlet-api-3.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/servlet-api-3.0.jar -------------------------------------------------------------------------------- /lib/slf4j-api-1.6.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/slf4j-api-1.6.1.jar -------------------------------------------------------------------------------- /lib/commons-codec-1.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/commons-codec-1.5.jar -------------------------------------------------------------------------------- /lib/commons-dbcp-1.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/commons-dbcp-1.4.jar -------------------------------------------------------------------------------- /lib/commons-jexl-1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/commons-jexl-1.1.jar -------------------------------------------------------------------------------- /lib/commons-lang-2.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/commons-lang-2.5.jar -------------------------------------------------------------------------------- /lib/commons-pool-1.5.6.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/commons-pool-1.5.6.jar -------------------------------------------------------------------------------- /lib/jetty-util-6.1.26.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/jetty-util-6.1.26.jar -------------------------------------------------------------------------------- /lib/netty-3.2.2.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/netty-3.2.2.Final.jar -------------------------------------------------------------------------------- /bin/rest-nettyserver-0.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/bin/rest-nettyserver-0.1.jar -------------------------------------------------------------------------------- /lib/aspectjweaver-1.6.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/aspectjweaver-1.6.1.jar -------------------------------------------------------------------------------- /lib/slf4j-log4j12-1.6.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/slf4j-log4j12-1.6.1.jar -------------------------------------------------------------------------------- /lib/commons-beanutils-1.8.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/commons-beanutils-1.8.3.jar -------------------------------------------------------------------------------- /lib/commons-httpclient-3.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/commons-httpclient-3.1.jar -------------------------------------------------------------------------------- /lib/commons-logging-1.1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/commons-logging-1.1.1.jar -------------------------------------------------------------------------------- /lib/mybatis-3.1.0-SNAPSHOT.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/mybatis-3.1.0-SNAPSHOT.jar -------------------------------------------------------------------------------- /lib/commons-collections-3.2.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/commons-collections-3.2.1.jar -------------------------------------------------------------------------------- /src/org/langke/core/service/IService.java: -------------------------------------------------------------------------------- 1 | package org.langke.core.service; 2 | 3 | public interface IService { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /lib/mybatis-spring-1.1.0-SNAPSHOT.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/mybatis-spring-1.1.0-SNAPSHOT.jar -------------------------------------------------------------------------------- /lib/org.springframework.aop-3.1.0.RELEASE.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/org.springframework.aop-3.1.0.RELEASE.jar -------------------------------------------------------------------------------- /lib/org.springframework.asm-3.1.0.RELEASE.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/org.springframework.asm-3.1.0.RELEASE.jar -------------------------------------------------------------------------------- /lib/org.springframework.core-3.1.0.RELEASE.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/org.springframework.core-3.1.0.RELEASE.jar -------------------------------------------------------------------------------- /lib/org.springframework.jdbc-3.1.0.RELEASE.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/org.springframework.jdbc-3.1.0.RELEASE.jar -------------------------------------------------------------------------------- /lib/org.springframework.orm-3.1.0.RELEASE.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/org.springframework.orm-3.1.0.RELEASE.jar -------------------------------------------------------------------------------- /lib/org.springframework.test-3.1.0.RELEASE.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/org.springframework.test-3.1.0.RELEASE.jar -------------------------------------------------------------------------------- /lib/org.springframework.beans-3.1.0.RELEASE.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/org.springframework.beans-3.1.0.RELEASE.jar -------------------------------------------------------------------------------- /lib/org.springframework.context-3.1.0.RELEASE.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/org.springframework.context-3.1.0.RELEASE.jar -------------------------------------------------------------------------------- /lib/org.springframework.expression-3.1.0.RELEASE.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/org.springframework.expression-3.1.0.RELEASE.jar -------------------------------------------------------------------------------- /lib/org.springframework.transaction-3.1.0.RELEASE.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/org.springframework.transaction-3.1.0.RELEASE.jar -------------------------------------------------------------------------------- /bdb/je.info.0: -------------------------------------------------------------------------------- 1 | 121228 09:44:29:229 INFO [bdb]Chose lowest utilized file for cleaning. totalUtilization: 46 bestFileUtilization: 101 lnSizeCorrectionFactor: NaN isProbe: false 2 | -------------------------------------------------------------------------------- /lib/org.springframework.context.support-3.1.0.RELEASE.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/langke93/rest-nettyserver/HEAD/lib/org.springframework.context.support-3.1.0.RELEASE.jar -------------------------------------------------------------------------------- /src/org/langke/common/server/Handler.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.server; 2 | 3 | import org.langke.common.server.resp.Resp; 4 | 5 | 6 | /* 7 | * @copyright (c) langke 2011 8 | * @author langke 2011-5-1 9 | */ 10 | public interface Handler { 11 | 12 | public Resp handleRequest(NettyHttpRequest request); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/org/langke/core/dao/IDemoDao.java: -------------------------------------------------------------------------------- 1 | package org.langke.core.dao; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | public interface IDemoDao { 7 | public void create(); 8 | public int insert(); 9 | public int update(String name); 10 | public List> select(); 11 | public void drop(); 12 | } 13 | -------------------------------------------------------------------------------- /src/org/langke/common/server/Server.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.server; 2 | 3 | /* 4 | * @copyright (c) langke 2011 5 | * @author langke 2011-5-1 6 | */ 7 | public interface Server { 8 | 9 | public void init(); 10 | 11 | public void start(); 12 | 13 | public void stop(); 14 | 15 | public String serverName(); 16 | } 17 | -------------------------------------------------------------------------------- /conf/config.properties: -------------------------------------------------------------------------------- 1 | server.name = rest-netty-server 2 | server.listen.port = 9090 3 | server.writeTimeout = 60 4 | server.readTimeout = 60 5 | jetty.pool.MinThread = 3 6 | jetty.pool.MaxThread = 32 7 | 8 | isUsedMemcached=false 9 | tt.cache.server = memcached0:11211,memcached1:11211 10 | memcachedPre = api_ 11 | #memcached expiry time ms 12 | memcachedExpiryTime=600000 -------------------------------------------------------------------------------- /src/org/langke/common/CostTime.java: -------------------------------------------------------------------------------- 1 | package org.langke.common; 2 | 3 | /* 4 | * @copyright (c) langke 2011 5 | * @author langke Aug 11, 2011 6 | */ 7 | 8 | public class CostTime { 9 | 10 | private transient long start; 11 | 12 | public void start(){ 13 | this.start = System.currentTimeMillis(); 14 | } 15 | 16 | public long cost(){ 17 | return System.currentTimeMillis() - start; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/org/langke/core/dao/mappers/HelloTableMapper.java: -------------------------------------------------------------------------------- 1 | package org.langke.core.dao.mappers; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import org.apache.ibatis.annotations.Param; 7 | import org.langke.bean.HelloTable; 8 | 9 | public interface HelloTableMapper { 10 | 11 | public int insert(@Param("demo") HelloTable helloTable); 12 | 13 | public List> select(HelloTable helloTable); 14 | } 15 | -------------------------------------------------------------------------------- /src/org/langke/bean/HelloTable.java: -------------------------------------------------------------------------------- 1 | package org.langke.bean; 2 | 3 | public class HelloTable { 4 | 5 | private String name; 6 | private Integer score; 7 | public String getName() { 8 | return name; 9 | } 10 | public void setName(String name) { 11 | this.name = name; 12 | } 13 | public Integer getScore() { 14 | return score; 15 | } 16 | public void setScore(Integer score) { 17 | this.score = score; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | rest-nettyserver 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/org/langke/common/bdb/BrekeleyDB.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.bdb; 2 | 3 | import java.util.List; 4 | 5 | public interface BrekeleyDB { 6 | public Object poll() ; 7 | public List poll(int limit) ; 8 | public void put(Object key,Object value); 9 | public Object get(Object key); 10 | public List get(int limit); 11 | public Object delete(Object key); 12 | public int size(); 13 | public boolean isEmpty(); 14 | public boolean contains(Object key); 15 | public void clear(); 16 | public void close(); 17 | } 18 | -------------------------------------------------------------------------------- /src/org/langke/util/EncreptUtil.java: -------------------------------------------------------------------------------- 1 | package org.langke.util; 2 | 3 | import org.apache.commons.codec.digest.DigestUtils; 4 | 5 | /* 6 | * @copyright (c) langke 2011 7 | * @author langke 2011-5-1 8 | */ 9 | public class EncreptUtil { 10 | 11 | public static String md5(String input){ 12 | if(input != null){ 13 | return DigestUtils.md5Hex(input); 14 | } 15 | return null; 16 | } 17 | 18 | public static void main(String[] args){ 19 | String data = "_T_ONLINE_K_W无线网卡"; 20 | System.out.println(md5(data)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | rest-nettyserver 2 | =============== 3 | 4 | rest-nettyserver是基于netty通信框架的轻量级、高性能RESTful服务,用于构建分布式系统。
5 | 集成了netty、spring、fastjson、mybatis、h2、BrekeleyDB、javamelody及memcached通用缓存模块 6 | 7 | ![性能测试结果](https://raw.github.com/langke93/rest-nettyserver/master/doc/img/performance.jpg) 8 | 9 | 上图是性能测试结果:在c10k环境下,平均每秒处理2w个请求,前面一部分是rest-testscript测试结果,后面是webbench测试结果 10 |   11 | 测试环境:
12 | CPU:2*E5620 @ 2.40GHz
13 | 内存:16GB
14 | JDK:Java HotSpot(TM) 64-Bit Server VM 1.6.0_33 -------------------------------------------------------------------------------- /src/org/langke/core/service/DemoService.java: -------------------------------------------------------------------------------- 1 | package org.langke.core.service; 2 | 3 | import org.langke.common.server.NettyHttpRequest; 4 | import org.langke.common.server.resp.RespData; 5 | 6 | public interface DemoService extends IService{ 7 | 8 | public RespData test(NettyHttpRequest request); 9 | public RespData create(NettyHttpRequest request); 10 | public RespData select(NettyHttpRequest request); 11 | public RespData insert(NettyHttpRequest request); 12 | public RespData update(NettyHttpRequest request); 13 | public RespData mybatis(NettyHttpRequest request); 14 | public RespData bdb(NettyHttpRequest request); 15 | } 16 | -------------------------------------------------------------------------------- /src/org/langke/common/ExecutorFactory.java: -------------------------------------------------------------------------------- 1 | package org.langke.common; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.ScheduledExecutorService; 6 | 7 | /* 8 | * @copyright (c) langke 2011 9 | * @author langke 2011-5-1 10 | */ 11 | public class ExecutorFactory { 12 | 13 | public static ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); 14 | public static ExecutorService fixedExecutor = Executors.newFixedThreadPool(10); 15 | public static ExecutorService cachedExecutor = Executors.newCachedThreadPool(); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/org/langke/common/CommonException.java: -------------------------------------------------------------------------------- 1 | package org.langke.common; 2 | 3 | /* 4 | * @copyright (c) langke 2011 5 | * @author langke 2011-5-1 6 | */ 7 | /** 8 | * 知道明确的错误原因的异常 9 | */ 10 | public class CommonException extends RuntimeException { 11 | 12 | private static final long serialVersionUID = 1L; 13 | public int errorCode = 502; 14 | public CommonException(String message) { 15 | super(message); 16 | } 17 | 18 | public CommonException(String message, Throwable cause) { 19 | super(message, cause); 20 | } 21 | 22 | public CommonException(String message,int errcode) { 23 | super(message); 24 | this.errorCode=errcode; 25 | } 26 | 27 | public CommonException(String message, Throwable cause,int errcode) { 28 | super(message, cause); 29 | this.errorCode=errcode; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/org/langke/common/StringPair.java: -------------------------------------------------------------------------------- 1 | package org.langke.common; 2 | 3 | import java.io.*; 4 | 5 | /* 6 | * @copyright (c) langke 2011 7 | * @author langke 2011-5-1 8 | */ 9 | public class StringPair implements Serializable { 10 | private static final long serialVersionUID = 3454234325353654757L; 11 | private String name; 12 | private String value; 13 | 14 | public StringPair() { 15 | } 16 | 17 | public StringPair(String name, String value) { 18 | this.name = name; 19 | this.value = value; 20 | } 21 | 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public void setName(String name) { 27 | this.name = name; 28 | } 29 | 30 | public String getValue() { 31 | return value; 32 | } 33 | 34 | public void setValue(String value) { 35 | this.value = value; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/org/langke/common/server/resp/RespData.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.server.resp; 2 | 3 | import java.io.Serializable; 4 | 5 | public class RespData implements Serializable{ 6 | private static final long serialVersionUID = 2018006821325666212L; 7 | private short code = 200; 8 | private long time; 9 | private Object content; 10 | private String msg; 11 | public short getCode() { 12 | return code; 13 | } 14 | public void setCode(short code) { 15 | this.code = code; 16 | } 17 | public long getTime() { 18 | return time; 19 | } 20 | public void setTime(long time) { 21 | this.time = time; 22 | } 23 | public Object getContent() { 24 | return content; 25 | } 26 | public void setContent(Object content) { 27 | this.content = content; 28 | } 29 | public String getMsg() { 30 | return msg; 31 | } 32 | public void setMsg(String msg) { 33 | this.msg = msg; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/resources/mappers/hellotableMapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 13 | 14 | 15 | 16 | SELECT LAST_INSERT_ID() 17 | 18 | insert into hellotable (name, score) 19 | values (#{demo.name,jdbcType=VARCHAR}, #{demo.score,jdbcType=INTEGER} ) 20 | 21 | -------------------------------------------------------------------------------- /src/org/langke/core/handler/DemoHandler.java: -------------------------------------------------------------------------------- 1 | package org.langke.core.handler; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | import org.langke.common.server.Handler; 6 | import org.langke.common.server.NettyHttpRequest; 7 | import org.langke.common.server.resp.Resp; 8 | import org.langke.common.server.resp.RespData; 9 | import org.langke.core.server.SpringApplicationContext; 10 | import org.langke.core.service.IService; 11 | 12 | public class DemoHandler implements Handler{ 13 | 14 | 15 | private IService service = (IService) SpringApplicationContext.getInstance().getService("demoService"); 16 | 17 | @Override 18 | public Resp handleRequest(NettyHttpRequest request) { 19 | Method method; 20 | RespData data; 21 | try { 22 | method = service.getClass().getMethod(request.param("label"), NettyHttpRequest.class); 23 | data = (RespData) method.invoke(service, request); 24 | } catch (Exception e) { 25 | throw new RuntimeException(e); 26 | } 27 | return new Resp(data); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/org/langke/common/StrIntBag.java: -------------------------------------------------------------------------------- 1 | package org.langke.common; 2 | 3 | import java.io.Serializable; 4 | 5 | /* 6 | * @copyright (c) langke 2011 7 | * @author langke 2011-5-1 8 | */ 9 | public class StrIntBag implements Serializable { 10 | private static final long serialVersionUID = 3454388888654757L; 11 | public String _str; 12 | public int _int; 13 | 14 | public StringPair toStringPair() { 15 | return new StringPair(_str, _int + ""); 16 | } 17 | 18 | public StrIntBag() { 19 | } 20 | 21 | public StrIntBag(String name, int value) { 22 | this._str = name; 23 | this._int = value; 24 | } 25 | 26 | public static StringPair[] toStringPairs(StrIntBag[] strIntBags) { 27 | if (strIntBags == null) { 28 | return null; 29 | } 30 | StringPair[] strPairs = new StringPair[strIntBags.length]; 31 | for (int i = 0; i < strIntBags.length; i++) { 32 | strPairs[i] = strIntBags[i].toStringPair(); 33 | } 34 | return strPairs; 35 | } 36 | 37 | @Override 38 | public String toString() { 39 | return _str + ":" + _int; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/org/langke/core/dao/DemoDaoImpl.java: -------------------------------------------------------------------------------- 1 | package org.langke.core.dao; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import org.springframework.jdbc.core.support.JdbcDaoSupport; 7 | 8 | public class DemoDaoImpl extends JdbcDaoSupport implements IDemoDao{ 9 | public void create(){ 10 | drop(); 11 | String sql = "create table hellotable(name varchar(40), score int)"; 12 | this.getJdbcTemplate().execute(sql); 13 | } 14 | 15 | public int insert(){ 16 | int res = this.getJdbcTemplate().update("insert into hellotable values('Ruth Cao', 86)"); 17 | //this.getJdbcTemplate().execute("insert into hellotable values ('Flora Shi', 92)"); 18 | return res; 19 | } 20 | 21 | public int update(String name){ 22 | int res = 0; 23 | if(name != null) 24 | res = this.getJdbcTemplate().update("update hellotable set name=? where score=86",name); 25 | return res; 26 | } 27 | 28 | public List> select(){ 29 | String sql = "SELECT name, score FROM hellotable ORDER BY score"; 30 | return this.getJdbcTemplate().queryForList(sql); 31 | } 32 | 33 | public void drop(){ 34 | this.getJdbcTemplate().execute("DROP TABLE IF EXISTS hellotable"); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /bin/restart-server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | #if [ "`whoami`" != "root" ] ; then 3 | # echo Must start use root 4 | # exit 1 5 | #fi 6 | 7 | DIRNAME=/usr/bin/dirname 8 | BASE_PATH=`$DIRNAME $0` 9 | cd $BASE_PATH 10 | echo `pwd` 11 | 12 | #export JAVA_HOME=/usr/local/jdk1.6.0_26 13 | #export PATH=/usr/local/jdk1.6.0_26/bin:$PATH 14 | 15 | for i in ./*.jar; do 16 | CLASSPATH=$i:$CLASSPATH; 17 | done 18 | 19 | for j in ../lib/*.jar; do 20 | CLASSPATH=$j:$CLASSPATH; 21 | done 22 | 23 | SEARCH_VER=0 24 | #DEFAULT_OPTS="-server -Xms300M -Xmx100M -Xss128k" 25 | DEFAULT_OPTS="$DEFAULT_OPTS -Dcom.sun.management.jmxremote.port=89${SEARCH_VER}6" 26 | DEFAULT_OPTS="$DEFAULT_OPTS -Dcom.sun.management.jmxremote.authenticate=false" 27 | DEFAULT_OPTS="$DEFAULT_OPTS -Dcom.sun.management.jmxremote.ssl=false" 28 | DEBUG_INFO=" -Xdebug -Xrunjdwp:transport=dt_socket,address=1527${SEARCH_VER},server=y,suspend=n " 29 | DEBUG="" 30 | case $1 in 31 | "debug") DEBUG=${DEBUG_INFO};; 32 | esac; 33 | shift; 34 | PNAME=org.langke.core.server.RestNettyServer 35 | if test $(pgrep -f ${PNAME}|wc -l) -ne 0;then 36 | echo "closing...... $PNAME" 37 | pkill -f $PNAME 38 | sleep 1 39 | fi 40 | 41 | 42 | # process 43 | CMD="java -cp $CLASSPATH $DEFAULT_OPTS $DEBUG ${PNAME} > /dev/null 2>&1 &" 44 | eval $CMD 45 | echo "start ~~ $CMD" 46 | echo "as pid:`pgrep -f ${PNAME}`" 47 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/slf4j/Slf4jESLoggerFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging.slf4j; 21 | 22 | import org.langke.util.logging.ESLogger; 23 | import org.langke.util.logging.ESLoggerFactory; 24 | import org.slf4j.LoggerFactory; 25 | 26 | 27 | /** 28 | * @author kimchy (shay.banon) 29 | */ 30 | public class Slf4jESLoggerFactory extends ESLoggerFactory { 31 | 32 | @Override 33 | public ESLogger newInstance(String prefix, String name) { 34 | return new Slf4jESLogger(prefix, LoggerFactory.getLogger(name)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/jdk/JdkESLoggerFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging.jdk; 21 | 22 | import org.langke.util.logging.ESLogger; 23 | import org.langke.util.logging.ESLoggerFactory; 24 | 25 | /** 26 | * @author kimchy (shay.banon) 27 | */ 28 | public class JdkESLoggerFactory extends ESLoggerFactory { 29 | 30 | public ESLogger newInstance(String prefix, String name) { 31 | final java.util.logging.Logger logger = java.util.logging.Logger 32 | .getLogger(name); 33 | return new JdkESLogger(prefix, logger); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/log4j/Log4jESLoggerFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging.log4j; 21 | 22 | import org.langke.util.logging.ESLogger; 23 | import org.langke.util.logging.ESLoggerFactory; 24 | 25 | /** 26 | * @author kimchy (shay.banon) 27 | */ 28 | public class Log4jESLoggerFactory extends ESLoggerFactory { 29 | 30 | @Override 31 | public ESLogger newInstance(String prefix, String name) { 32 | final org.apache.log4j.Logger logger = org.apache.log4j.Logger 33 | .getLogger(name); 34 | return new Log4jESLogger(prefix, logger); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/org/langke/core/server/SpringApplicationContext.java: -------------------------------------------------------------------------------- 1 | package org.langke.core.server; 2 | 3 | import java.io.File; 4 | 5 | import org.langke.util.logging.ESLogger; 6 | import org.langke.util.logging.Loggers; 7 | import org.springframework.context.ApplicationContext; 8 | import org.springframework.context.support.FileSystemXmlApplicationContext; 9 | 10 | 11 | public class SpringApplicationContext { 12 | private ESLogger log = Loggers.getLogger(SpringApplicationContext.class); 13 | 14 | private static ApplicationContext ctx; 15 | private static SpringApplicationContext instance=new SpringApplicationContext(); 16 | 17 | public static SpringApplicationContext getInstance(){ 18 | return instance; 19 | } 20 | 21 | private SpringApplicationContext() { 22 | initCtx(); 23 | } 24 | 25 | private void initCtx(){ 26 | if(ctx == null) { 27 | String location = null; 28 | if(System.getProperty("os.name").toLowerCase().contains("windows")){ 29 | location = "conf/applicationContext.xml"; 30 | }else{ 31 | location = "../conf/applicationContext.xml"; 32 | } 33 | File file = new File(location); 34 | log.info("applicationContext: [{}]", file.getAbsolutePath() ); 35 | ctx = new FileSystemXmlApplicationContext(location); 36 | } 37 | } 38 | 39 | public Object getService(String serviceName){ 40 | return ctx.getBean(serviceName); 41 | } 42 | public ApplicationContext getApplicationContext(){ 43 | return ctx; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/org/langke/common/cache/PK.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.cache; 2 | import java.lang.annotation.Documented; 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Inherited; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * Title: codegen
11 | * Description:
12 | * Copyright: Copyright (c) 2010
13 | * Create DateTime: 2010-12-21
14 | * @author langke 15 | */ 16 | /* 17 | * 元注解@Target,@Retention,@Documented,@Inherited 18 | * 19 | * @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括: 20 | * ElemenetType.CONSTRUCTOR 构造器声明 21 | * ElemenetType.FIELD 域声明(包括 enum 实例) 22 | * ElemenetType.LOCAL_VARIABLE 局部变量声明 23 | * ElemenetType.METHOD 方法声明 24 | * ElemenetType.PACKAGE 包声明 25 | * ElemenetType.PARAMETER 参数声明 26 | * ElemenetType.TYPE 类,接口(包括注解类型)或enum声明 27 | * 28 | * @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括: 29 | * RetentionPolicy.SOURCE 注解将被编译器丢弃 30 | * RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃 31 | * RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。 32 | * 33 | * @Documented 将此注解包含在 javadoc 中 34 | * 35 | * @Inherited 允许子类继承父类中的注解 36 | * 37 | */ 38 | @Target(ElementType.METHOD) 39 | @Retention(RetentionPolicy.RUNTIME) 40 | @Documented 41 | @Inherited 42 | public @interface PK { 43 | 44 | public String key() default "";//指定实体类中的组件getXXX()方法 45 | 46 | 47 | } -------------------------------------------------------------------------------- /conf/log4j.properties: -------------------------------------------------------------------------------- 1 | ############################################################ 2 | # Define some default values that can be overridden by system properties 3 | log.dir=../logs 4 | log.file=rest-nettyserver.log 5 | 6 | log4j.rootLogger=INFO,console,DRFA 7 | #,SOCKET_CLIENT 8 | 9 | # Logging Threshold 10 | log4j.threshhold=ALL 11 | 12 | # Custom Logging levels 13 | 14 | log4j.logger.org.apache.hadoop=INFO 15 | #remote logging 16 | log4j.appender.SOCKET_CLIENT = org.apache.log4j.net.SocketAppender 17 | log4j.appender.SOCKET_CLIENT.RemoteHost = log4server 18 | log4j.appender.SOCKET_CLIENT.Port = 5001 19 | log4j.appender.SOCKET_CLIENT.LocationInfo = true 20 | # 21 | # Daily Rolling File Appender 22 | # 23 | log4j.appender.DRFA=org.apache.log4j.DailyRollingFileAppender 24 | log4j.appender.DRFA.File=${log.dir}/${log.file} 25 | 26 | # Rollver at midnight 27 | log4j.appender.DRFA.DatePattern=.yyyy-MM-dd 28 | 29 | # 30-day backup 30 | #log4j.appender.DRFA.MaxBackupIndex=30 31 | log4j.appender.DRFA.layout=org.apache.log4j.PatternLayout 32 | 33 | # Pattern format: Date LogLevel LoggerName LogMessage 34 | log4j.appender.DRFA.layout.ConversionPattern=%d{ISO8601} %p %c: %m%n 35 | 36 | # Debugging Pattern format 37 | #log4j.appender.DRFA.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} (%F:%M(%L)) - %m%n 38 | 39 | 40 | # 41 | # console 42 | # Add "console" to rootlogger above if you want to use this 43 | # 44 | log4j.appender.console=org.apache.log4j.ConsoleAppender 45 | log4j.appender.console.target=System.err 46 | log4j.appender.console.layout=org.apache.log4j.PatternLayout 47 | log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p %c{2}: %m%n 48 | -------------------------------------------------------------------------------- /src/org/langke/common/ServerAddress.java: -------------------------------------------------------------------------------- 1 | package org.langke.common; 2 | 3 | import java.io.Serializable; 4 | 5 | /* 6 | * @copyright (c) langke 2011 7 | * @author langke 2011-5-1 8 | */ 9 | public class ServerAddress implements Serializable { 10 | 11 | private static final long serialVersionUID = 5142207361335126957L; 12 | private String host; 13 | private int port; 14 | 15 | public ServerAddress(String host, int port){ 16 | this.host = host; 17 | this.port = port; 18 | } 19 | 20 | public ServerAddress(String addressAndPort) { 21 | int pIndex = addressAndPort.indexOf(':'); 22 | if (pIndex < 0) { 23 | throw new IllegalArgumentException("Must have a : in addressAndPort,got:" + addressAndPort); 24 | } 25 | this.host = addressAndPort.substring(0, pIndex); 26 | this.port = Integer.parseInt(addressAndPort.substring(pIndex + 1)); 27 | } 28 | 29 | @Override 30 | public boolean equals(Object obj) { 31 | if (this == obj) { 32 | return true; 33 | } 34 | if (!(obj instanceof ServerAddress)) { 35 | return false; 36 | } 37 | ServerAddress n = (ServerAddress) obj; 38 | return n.host.equals(this.host) && n.port == this.port; 39 | } 40 | 41 | @Override 42 | public int hashCode() { 43 | return (host+":"+port).hashCode(); 44 | } 45 | 46 | public String getHost() { 47 | return host; 48 | } 49 | 50 | public int getPort() { 51 | return port; 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return this.host + ":" + this.port; 57 | } 58 | 59 | public static void main(String[] p) { 60 | System.out.println(new ServerAddress("192.178.2.4:12").toString()); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/org/langke/common/cache/MemFlush.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.cache; 2 | import java.lang.annotation.Documented; 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Inherited; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * Title: memFlush
11 | * Description:
12 | * Copyright: Copyright (c) 2011
13 | * Create DateTime: 2011-10-28
14 | * @author langke 15 | */ 16 | /* 17 | * 元注解@Target,@Retention,@Documented,@Inherited 18 | * 19 | * @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括: 20 | * ElemenetType.CONSTRUCTOR 构造器声明 21 | * ElemenetType.FIELD 域声明(包括 enum 实例) 22 | * ElemenetType.LOCAL_VARIABLE 局部变量声明 23 | * ElemenetType.METHOD 方法声明 24 | * ElemenetType.PACKAGE 包声明 25 | * ElemenetType.PARAMETER 参数声明 26 | * ElemenetType.TYPE 类,接口(包括注解类型)或enum声明 27 | * 28 | * @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括: 29 | * RetentionPolicy.SOURCE 注解将被编译器丢弃 30 | * RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃 31 | * RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。 32 | * 33 | * @Documented 将此注解包含在 javadoc 中 34 | * 35 | * @Inherited 允许子类继承父类中的注解 36 | * 37 | */ 38 | @Target(ElementType.METHOD) 39 | @Retention(RetentionPolicy.RUNTIME) 40 | @Documented 41 | @Inherited 42 | public @interface MemFlush { 43 | 44 | /* 45 | * 指定要刷新的方法名,多个方法用“,”分隔
46 | * 不指定,默认刷新对应实体类中所有带@MemCache的所有方法 47 | * 格式: 48 | */ 49 | public String key() default ""; 50 | 51 | } -------------------------------------------------------------------------------- /src/org/langke/common/ConnManager.java: -------------------------------------------------------------------------------- 1 | package org.langke.common; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | 7 | import org.langke.common.Config; 8 | 9 | 10 | /* 11 | * @copyright (c) langke 2011 12 | * @author langke 2011-5-1 13 | */ 14 | public class ConnManager { 15 | 16 | public static Connection createConn() throws ClassNotFoundException, SQLException { 17 | Connection connection = null; 18 | String conn_url = Config.get().get("mall.connection.url"); 19 | String username = Config.get().get("mall.connection.username"); 20 | String password = Config.get().get("mall.connection.password"); 21 | Class.forName("com.mysql.jdbc.Driver" ); 22 | connection = DriverManager.getConnection(conn_url,username,password ); 23 | return connection; 24 | } 25 | 26 | public static Connection createCmsConn() throws ClassNotFoundException, SQLException { 27 | Connection connection = null; 28 | String conn_url = Config.get().get("cms.connection.url"); 29 | String username = Config.get().get("cms.connection.username"); 30 | String password = Config.get().get("cms.connection.password"); 31 | Class.forName("com.mysql.jdbc.Driver" ); 32 | connection = DriverManager.getConnection(conn_url,username,password ); 33 | return connection; 34 | } 35 | 36 | public static void main(String[] args) { 37 | Connection conn; 38 | try { 39 | conn = createConn(); 40 | conn = createCmsConn(); 41 | System.out.println(conn); 42 | } catch (ClassNotFoundException e) { 43 | e.printStackTrace(); 44 | } catch (SQLException e) { 45 | e.printStackTrace(); 46 | } 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/org/langke/common/cache/MemCaching.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.cache; 2 | import java.lang.annotation.Documented; 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Inherited; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | /** 10 | * Title: memCaching
11 | * Description:
12 | * Copyright: Copyright (c) 2011
13 | * Create DateTime: 2011-10-28
14 | * @author langke 15 | */ 16 | /* 17 | * 元注解@Target,@Retention,@Documented,@Inherited 18 | * 19 | * @Target 表示该注解用于什么地方,可能的 ElemenetType 参数包括: 20 | * ElemenetType.CONSTRUCTOR 构造器声明 21 | * ElemenetType.FIELD 域声明(包括 enum 实例) 22 | * ElemenetType.LOCAL_VARIABLE 局部变量声明 23 | * ElemenetType.METHOD 方法声明 24 | * ElemenetType.PACKAGE 包声明 25 | * ElemenetType.PARAMETER 参数声明 26 | * ElemenetType.TYPE 类,接口(包括注解类型)或enum声明 27 | * 28 | * @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括: 29 | * RetentionPolicy.SOURCE 注解将被编译器丢弃 30 | * RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃 31 | * RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。 32 | * 33 | * @Documented 将此注解包含在 javadoc 中 34 | * 35 | * @Inherited 允许子类继承父类中的注解 36 | * 37 | */ 38 | @Target(ElementType.METHOD) 39 | @Retention(RetentionPolicy.RUNTIME) 40 | @Documented 41 | @Inherited 42 | public @interface MemCaching { 43 | 44 | public String key() default "";//指定缓存的key字段名,key 可以是参数中的一个或几个,多个用“,”分隔,不指定为mysql自增id 45 | 46 | public String group() default "";//指定缓存到某个组 47 | 48 | } -------------------------------------------------------------------------------- /src/org/langke/common/server/ServerAddress.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.server; 2 | 3 | import java.io.Serializable; 4 | 5 | /* 6 | * @copyright (c) langke 2011 7 | * @author langke 2011-5-1 8 | */ 9 | public class ServerAddress implements Serializable { 10 | 11 | private static final long serialVersionUID = 5142207361335126957L; 12 | private String host; 13 | private int port; 14 | 15 | public ServerAddress(String host, int port){ 16 | this.host = host; 17 | this.port = port; 18 | } 19 | 20 | public ServerAddress(String addressAndPort) { 21 | int pIndex = addressAndPort.indexOf(':'); 22 | if (pIndex < 0) { 23 | throw new IllegalArgumentException("Must have a : in addressAndPort,got:" + addressAndPort); 24 | } 25 | this.host = addressAndPort.substring(0, pIndex); 26 | this.port = Integer.parseInt(addressAndPort.substring(pIndex + 1)); 27 | } 28 | 29 | @Override 30 | public boolean equals(Object obj) { 31 | if (this == obj) { 32 | return true; 33 | } 34 | if (!(obj instanceof ServerAddress)) { 35 | return false; 36 | } 37 | ServerAddress n = (ServerAddress) obj; 38 | return n.host.equals(this.host) && n.port == this.port; 39 | } 40 | 41 | @Override 42 | public int hashCode() { 43 | return (host+":"+port).hashCode(); 44 | } 45 | 46 | public String getHost() { 47 | return host; 48 | } 49 | 50 | public int getPort() { 51 | return port; 52 | } 53 | 54 | @Override 55 | public String toString() { 56 | return this.host + ":" + this.port; 57 | } 58 | 59 | public static void main(String[] p) { 60 | System.out.println(new ServerAddress("192.178.2.4:12").toString()); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/org/langke/util/MD5Util.java: -------------------------------------------------------------------------------- 1 | package org.langke.util; 2 | 3 | import java.security.MessageDigest; 4 | 5 | /* 6 | * @copyright (c) langke 2011 7 | * @author langke 2011-5-1 8 | */ 9 | public class MD5Util { 10 | 11 | // Use to translate the byte into hex char 12 | static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', 13 | '9', 'a', 'b', 'c', 'd', 'e', 'f' }; 14 | 15 | /** 16 | * Encript string with MD5 17 | * @param message: String to be Encripted 18 | * @return : String that have been Encripted 19 | */ 20 | public static String getMD5(String message) { 21 | try { 22 | MessageDigest md = MessageDigest.getInstance("MD5"); 23 | byte[] b = md.digest(message.getBytes("UTF-8")); 24 | return byteToHexString(b); 25 | } catch (Exception e) { 26 | e.printStackTrace(); 27 | return null; 28 | } 29 | } 30 | 31 | /** 32 | * convert byte[] into hex string 33 | * 34 | * @param tmp byte[] to be converted 35 | * @return hex string that have been converted 36 | */ 37 | private static String byteToHexString(byte[] tmp) { 38 | String s; 39 | 40 | char str[] = new char[16 * 2]; 41 | 42 | int k = 0; 43 | for (int i = 0; i < 16; i++) { 44 | 45 | byte byte0 = tmp[i]; 46 | str[k++] = hexDigits[byte0 >>> 4 & 0xf]; 47 | 48 | str[k++] = hexDigits[byte0 & 0xf]; 49 | } 50 | s = new String(str); 51 | return s; 52 | } 53 | 54 | public static void main(String[] args){ 55 | String to_md5 = "_T_ONLINE_K_W无线网卡"; 56 | System.out.println(getMD5(to_md5)); 57 | String s = "8888.999:00 88.99:99"; 58 | String[] array = s.replaceAll(",", " ").split("\\s+"); 59 | System.out.println(array.length+"/"+array[0]+"|"+array[1]); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/org/langke/common/server/resp/ErrorResp.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.server.resp; 2 | 3 | import java.nio.charset.Charset; 4 | 5 | import org.jboss.netty.buffer.ChannelBuffer; 6 | import org.jboss.netty.buffer.ChannelBuffers; 7 | import org.langke.common.CommonException; 8 | import org.langke.common.Strings; 9 | 10 | import com.alibaba.fastjson.JSONObject; 11 | import com.alibaba.fastjson.serializer.SerializerFeature; 12 | 13 | 14 | public class ErrorResp extends Resp { 15 | private static final long serialVersionUID = 34687954757L; 16 | private RespData respData = new RespData(); 17 | 18 | public RespData getRespData() { 19 | return respData; 20 | } 21 | 22 | public void setRespData(RespData respData) { 23 | this.respData = respData; 24 | } 25 | 26 | @Override 27 | public ChannelBuffer toJson() { 28 | return ChannelBuffers.copiedBuffer(JSONObject.toJSONString(respData, SerializerFeature.BrowserCompatible), Charset.forName("UTF-8")); 29 | } 30 | 31 | public ErrorResp(String msg) { 32 | respData.setMsg(Strings.quote(msg)); 33 | respData.setCode((short) 500); 34 | } 35 | 36 | public ErrorResp(String msg, int errorCode) { 37 | respData.setMsg(Strings.quote(msg)); 38 | respData.setCode((short) errorCode); 39 | } 40 | 41 | public ErrorResp(Throwable t) { 42 | this(Strings.throwableToString(t)); 43 | if (t instanceof CommonException) { 44 | respData.setMsg(((CommonException) t).getMessage()); 45 | respData.setCode((short)((CommonException) t).errorCode); 46 | } 47 | } 48 | 49 | public ErrorResp(String errors, Throwable t) { 50 | if (t instanceof CommonException) { 51 | respData.setMsg(errors + "\n" + Strings.throwableToString(t)); 52 | respData.setCode((short)((CommonException) t).errorCode); 53 | } 54 | } 55 | 56 | public ErrorResp(Throwable t, int errorCode) { 57 | this(Strings.throwableToString(t), errorCode); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/org/langke/common/bdb/AbstractBerkeleyDB.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.bdb; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | 6 | import com.sleepycat.bind.serial.StoredClassCatalog; 7 | import com.sleepycat.je.Database; 8 | import com.sleepycat.je.DatabaseConfig; 9 | import com.sleepycat.je.DatabaseException; 10 | import com.sleepycat.je.Environment; 11 | import com.sleepycat.je.EnvironmentConfig; 12 | 13 | public abstract class AbstractBerkeleyDB { 14 | public Environment env; 15 | private static final String CLASS_CATALOG = "java_class_catalog"; 16 | protected StoredClassCatalog javaCatalog; 17 | protected Database catalogdatabase; 18 | protected Database database; 19 | 20 | public AbstractBerkeleyDB(String homeDirectory,String dbname) { 21 | // 打开env 22 | EnvironmentConfig envConfig = new EnvironmentConfig(); 23 | envConfig.setTransactional(true); 24 | envConfig.setAllowCreate(true); 25 | File bdbHomeFile = new File(homeDirectory); 26 | if(!bdbHomeFile.exists()) 27 | bdbHomeFile.mkdirs(); 28 | env = new Environment(bdbHomeFile, envConfig); 29 | 30 | if(database != null) 31 | return; 32 | // 设置DatabaseConfig 33 | DatabaseConfig dbConfig = new DatabaseConfig(); 34 | dbConfig.setTransactional(true); 35 | dbConfig.setAllowCreate(true); 36 | // 打开 37 | catalogdatabase = env.openDatabase(null, CLASS_CATALOG, dbConfig); 38 | javaCatalog = new StoredClassCatalog(catalogdatabase); 39 | // 设置DatabaseConfig 40 | DatabaseConfig dbConfig0 = new DatabaseConfig(); 41 | dbConfig0.setTransactional(true); 42 | dbConfig0.setAllowCreate(true); 43 | // 打开 44 | database = env.openDatabase(null, dbname, dbConfig); 45 | } 46 | //关闭数据库,关闭环境 47 | public void close() throws DatabaseException { 48 | if(database!=null) 49 | database.close(); 50 | if(javaCatalog!=null) 51 | javaCatalog.close(); 52 | if(env!=null) 53 | env.close(); 54 | } 55 | //put方法 56 | protected abstract void put(Object key,Object value); 57 | //get方法 58 | protected abstract Object get(Object key); 59 | //delete方法 60 | protected abstract Object delete(Object key); 61 | } 62 | -------------------------------------------------------------------------------- /src/org/langke/common/server/resp/Resp.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.server.resp; 2 | 3 | import java.io.Serializable; 4 | import java.nio.charset.Charset; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | 9 | import org.jboss.netty.buffer.ChannelBuffer; 10 | import org.jboss.netty.buffer.ChannelBuffers; 11 | import org.langke.common.Strings; 12 | 13 | import com.alibaba.fastjson.JSONObject; 14 | import com.alibaba.fastjson.serializer.SerializerFeature; 15 | 16 | public class Resp implements Serializable { 17 | 18 | private static final long serialVersionUID = 34543654757L; 19 | protected transient List warningList = null; 20 | private RespData respData = new RespData(); 21 | public Resp() { 22 | } 23 | public Resp(String content) { 24 | super(); 25 | respData.setContent(content); 26 | } 27 | public Resp(RespData data) { 28 | respData = data; 29 | } 30 | 31 | public RespData getRespData() { 32 | return respData; 33 | } 34 | public void setRespData(RespData respData) { 35 | this.respData = respData; 36 | } 37 | public ChannelBuffer body(){ 38 | return ChannelBuffers.copiedBuffer(JSONObject.toJSONString(respData.getContent(), SerializerFeature.BrowserCompatible), Charset.forName("UTF-8")); 39 | } 40 | 41 | public ChannelBuffer toJson() { 42 | return ChannelBuffers.copiedBuffer(JSONObject.toJSONString(respData, SerializerFeature.BrowserCompatible), Charset.forName("UTF-8")); 43 | } 44 | 45 | public void addWarning(String s) { 46 | if (s == null || s.trim().equals("")) { 47 | return; 48 | } 49 | if (warningList == null) { 50 | warningList = new ArrayList(4); 51 | } 52 | warningList.add(s); 53 | } 54 | 55 | protected void addWarnings(StringBuilder sb) { 56 | if (this.warningList != null && warningList.size() > 0) { 57 | Strings.quoteSafeJson(sb, "warnings"); 58 | sb.append(":["); 59 | for (String s : warningList) { 60 | if (s != null) { 61 | Strings.quoteSafeJson(sb, s); 62 | sb.append(","); 63 | } 64 | } 65 | sb.setCharAt(sb.length() - 1, ']'); 66 | } 67 | } 68 | 69 | public String toString() { 70 | return this.toJson().toString(Charset.forName("UTF-8")); 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/org/langke/util/DateUtil.java: -------------------------------------------------------------------------------- 1 | package org.langke.util; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Calendar; 6 | import java.util.Date; 7 | 8 | /** 9 | * 日期转换工具 10 | */ 11 | public class DateUtil 12 | { 13 | private static final String FORMAT_DATETIME = "yyyy-MM-dd HH:mm:ss"; 14 | private static final String FORMAT_DATE = "yyyy-MM-dd"; 15 | 16 | public static boolean isDate(String date){ 17 | return date.matches("\\d{4}-\\d{2}-\\d{2}"); 18 | } 19 | 20 | public static String getCurrentDateStr(){ 21 | return getCurrentDateStr(FORMAT_DATETIME); 22 | } 23 | 24 | public static String getDatetimeStr(long datetime){ 25 | return format(new Date(datetime),FORMAT_DATETIME); 26 | } 27 | 28 | public static String getDateStr(long datetime){ 29 | return format(new Date(datetime),FORMAT_DATE); 30 | } 31 | 32 | public static Date getCurrentDate(){ 33 | Calendar cal = Calendar.getInstance(); 34 | Date currDate = cal.getTime(); 35 | return currDate; 36 | } 37 | 38 | /** 39 | * param 2010-09-01 40 | */ 41 | public static Date parseStringToDate(String date_str){ 42 | SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATE); 43 | Date date = null; 44 | try { 45 | date = sdf.parse(date_str); 46 | } catch (ParseException e) { 47 | e.printStackTrace(); 48 | } 49 | return date; 50 | } 51 | /** 52 | * param 2010-09-01 19:29:10 53 | */ 54 | public static Date parseStringToDateTime(String date_str){ 55 | SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_DATETIME); 56 | Date date = null; 57 | try { 58 | date = sdf.parse(date_str); 59 | } catch (ParseException e) { 60 | e.printStackTrace(); 61 | } 62 | return date; 63 | } 64 | 65 | private static String getCurrentDateStr(String strFormat){ 66 | Calendar cal = Calendar.getInstance(); 67 | Date currDate = cal.getTime(); 68 | return format(currDate, strFormat); 69 | } 70 | 71 | private static String format(Date aTs_Datetime, String as_Pattern){ 72 | if (aTs_Datetime == null || as_Pattern == null){ 73 | return null; 74 | } 75 | SimpleDateFormat dateFromat = new SimpleDateFormat(as_Pattern); 76 | return dateFromat.format(aTs_Datetime); 77 | } 78 | public static void main(String[] args){ 79 | System.out.println(getCurrentDateStr()); 80 | System.out.println(parseStringToDateTime(getCurrentDateStr()).getTime()); 81 | System.out.println(getDatetimeStr(System.currentTimeMillis())); 82 | System.out.println(getCurrentDateStr("yyyy.MM.dd HH:mm:ss")); 83 | System.out.println(format(new Date(System.currentTimeMillis()),"yyyy.MM.dd HH:mm:ss")); 84 | } 85 | } 86 | 87 | 88 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/slf4j/Slf4jESLogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging.slf4j; 21 | 22 | import org.langke.util.logging.support.AbstractESLogger; 23 | import org.slf4j.Logger; 24 | 25 | 26 | /** 27 | * @author kimchy (shay.banon) 28 | */ 29 | public class Slf4jESLogger extends AbstractESLogger { 30 | 31 | private final Logger logger; 32 | 33 | public Slf4jESLogger(String prefix, Logger logger) { 34 | super(prefix); 35 | this.logger = logger; 36 | } 37 | 38 | public String getName() { 39 | return logger.getName(); 40 | } 41 | 42 | public boolean isTraceEnabled() { 43 | return logger.isTraceEnabled(); 44 | } 45 | 46 | public boolean isDebugEnabled() { 47 | return logger.isDebugEnabled(); 48 | } 49 | 50 | public boolean isInfoEnabled() { 51 | return logger.isInfoEnabled(); 52 | } 53 | 54 | public boolean isWarnEnabled() { 55 | return logger.isWarnEnabled(); 56 | } 57 | 58 | public boolean isErrorEnabled() { 59 | return logger.isErrorEnabled(); 60 | } 61 | 62 | protected void internalTrace(String msg) { 63 | logger.trace(msg); 64 | } 65 | 66 | protected void internalTrace(String msg, Throwable cause) { 67 | logger.trace(msg, cause); 68 | } 69 | 70 | protected void internalDebug(String msg) { 71 | logger.debug(msg); 72 | } 73 | 74 | protected void internalDebug(String msg, Throwable cause) { 75 | logger.debug(msg, cause); 76 | } 77 | 78 | protected void internalInfo(String msg) { 79 | logger.info(msg); 80 | } 81 | 82 | protected void internalInfo(String msg, Throwable cause) { 83 | logger.info(msg, cause); 84 | } 85 | 86 | protected void internalWarn(String msg) { 87 | logger.warn(msg); 88 | } 89 | 90 | protected void internalWarn(String msg, Throwable cause) { 91 | logger.warn(msg, cause); 92 | } 93 | 94 | protected void internalError(String msg) { 95 | logger.error(msg); 96 | } 97 | 98 | protected void internalError(String msg, Throwable cause) { 99 | logger.error(msg, cause); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/ESLoggerFactory.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging; 21 | 22 | import java.io.File; 23 | 24 | import org.apache.log4j.PropertyConfigurator; 25 | import org.langke.util.logging.jdk.JdkESLoggerFactory; 26 | import org.langke.util.logging.log4j.Log4jESLoggerFactory; 27 | 28 | 29 | /** 30 | * @author kimchy (shay.banon) 31 | */ 32 | public abstract class ESLoggerFactory { 33 | 34 | private static volatile ESLoggerFactory defaultFactory = new JdkESLoggerFactory(); 35 | 36 | static { 37 | // try { 38 | // Class.forName("org.slf4j.Logger"); 39 | // defaultFactory = new Slf4jESLoggerFactory(); 40 | // } catch (Throwable e) { 41 | // throw new RuntimeException(e); 42 | // no slf4j 43 | try { 44 | Class.forName("org.apache.log4j.Logger"); 45 | String location=""; 46 | if(System.getProperty("os.name").toLowerCase().contains("windows")){ 47 | location = "conf/log4j.properties"; 48 | }else{ 49 | location = "../conf/log4j.properties"; 50 | } 51 | File f = new File(location); 52 | if (!f.exists()) { 53 | System.out.println("Cannot find log config file:" 54 | + f.getAbsolutePath()); 55 | } 56 | PropertyConfigurator.configureAndWatch(f.getAbsolutePath()); 57 | defaultFactory = new Log4jESLoggerFactory(); 58 | 59 | } catch (Throwable e1) { 60 | // no log4j 61 | } 62 | // } 63 | } 64 | 65 | /** 66 | * Changes the default factory. 67 | */ 68 | public static void setDefaultFactory(ESLoggerFactory defaultFactory) { 69 | if (defaultFactory == null) { 70 | throw new NullPointerException("defaultFactory"); 71 | } 72 | ESLoggerFactory.defaultFactory = defaultFactory; 73 | } 74 | 75 | public static ESLogger getLogger(String prefix, String name) { 76 | return defaultFactory.newInstance(prefix, name); 77 | } 78 | 79 | public static ESLogger getLogger(String name) { 80 | return defaultFactory.newInstance(name); 81 | } 82 | 83 | public ESLogger newInstance(String name) { 84 | return newInstance(null, name); 85 | } 86 | 87 | public abstract ESLogger newInstance(String prefix, String name); 88 | } 89 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/ESLogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging; 21 | 22 | /** 23 | * @author kimchy (shay.banon) 24 | */ 25 | public interface ESLogger { 26 | 27 | String getPrefix(); 28 | 29 | String getName(); 30 | 31 | /** 32 | * Returns {@code true} if a TRACE level message is logged. 33 | */ 34 | boolean isTraceEnabled(); 35 | 36 | /** 37 | * Returns {@code true} if a DEBUG level message is logged. 38 | */ 39 | boolean isDebugEnabled(); 40 | 41 | /** 42 | * Returns {@code true} if an INFO level message is logged. 43 | */ 44 | boolean isInfoEnabled(); 45 | 46 | /** 47 | * Returns {@code true} if a WARN level message is logged. 48 | */ 49 | boolean isWarnEnabled(); 50 | 51 | /** 52 | * Returns {@code true} if an ERROR level message is logged. 53 | */ 54 | boolean isErrorEnabled(); 55 | 56 | /** 57 | * Logs a DEBUG level message. 58 | */ 59 | void trace(String msg, Object... params); 60 | 61 | /** 62 | * Logs a DEBUG level message. 63 | */ 64 | void trace(String msg, Throwable cause, Object... params); 65 | 66 | /** 67 | * Logs a DEBUG level message. 68 | */ 69 | void debug(String msg, Object... params); 70 | 71 | /** 72 | * Logs a DEBUG level message. 73 | */ 74 | void debug(String msg, Throwable cause, Object... params); 75 | 76 | /** 77 | * Logs an INFO level message. 78 | */ 79 | void info(String msg, Object... params); 80 | 81 | /** 82 | * Logs an INFO level message. 83 | */ 84 | void info(String msg, Throwable cause, Object... params); 85 | 86 | /** 87 | * Logs a WARN level message. 88 | */ 89 | void warn(String msg, Object... params); 90 | 91 | /** 92 | * Logs a WARN level message. 93 | */ 94 | void warn(String msg, Throwable cause, Object... params); 95 | 96 | /** 97 | * Logs an ERROR level message. 98 | */ 99 | void error(String msg, Object... params); 100 | 101 | /** 102 | * Logs an ERROR level message. 103 | */ 104 | void error(String msg, Throwable cause, Object... params); 105 | 106 | } 107 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/Loggers.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging; 21 | 22 | 23 | /** 24 | * A set of utilities around Logging. 25 | * 26 | * @author kimchy (shay.banon) 27 | */ 28 | @SuppressWarnings("rawtypes") 29 | public class Loggers { 30 | 31 | private static boolean consoleLoggingEnabled = true; 32 | 33 | public static void disableConsoleLogging() { 34 | consoleLoggingEnabled = false; 35 | } 36 | 37 | public static void enableConsoleLogging() { 38 | consoleLoggingEnabled = true; 39 | } 40 | 41 | public static boolean consoleLoggingEnabled() { 42 | return consoleLoggingEnabled; 43 | } 44 | 45 | public static ESLogger getLogger(ESLogger parentLogger, String s) { 46 | return getLogger(parentLogger.getName() + s, parentLogger.getPrefix()); 47 | } 48 | 49 | public static ESLogger getLogger(String s) { 50 | return ESLoggerFactory.getLogger(s); 51 | } 52 | 53 | public static ESLogger getLogger(Class clazz) { 54 | return ESLoggerFactory.getLogger(getLoggerName(clazz)); 55 | } 56 | 57 | public static ESLogger getLogger(Class clazz, String... prefixes) { 58 | return getLogger(getLoggerName(clazz), prefixes); 59 | } 60 | 61 | public static ESLogger getLogger(String name, String... prefixes) { 62 | String prefix = null; 63 | if (prefixes != null && prefixes.length > 0) { 64 | StringBuilder sb = new StringBuilder(); 65 | for (String prefixX : prefixes) { 66 | if (prefixX != null) { 67 | sb.append("[").append(prefixX).append("]"); 68 | } 69 | } 70 | if (sb.length() > 0) { 71 | sb.append(" "); 72 | prefix = sb.toString(); 73 | } 74 | } 75 | return ESLoggerFactory.getLogger(prefix, getLoggerName(name)); 76 | } 77 | 78 | private static String getLoggerName(Class clazz) { 79 | String name = clazz.getName(); 80 | // if (name.startsWith("org.elasticsearch.")) { 81 | // name = Classes.getPackageName(clazz); 82 | // } 83 | return getLoggerName(name); 84 | } 85 | 86 | private static String getLoggerName(String name) { 87 | if (name.startsWith("org.elasticsearch.")) { 88 | return name.substring("org.elasticsearch.".length()); 89 | } 90 | return name; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/log4j/Log4jESLogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging.log4j; 21 | 22 | import org.apache.log4j.Level; 23 | import org.apache.log4j.Logger; 24 | import org.langke.util.logging.support.AbstractESLogger; 25 | 26 | 27 | /** 28 | * @author kimchy (shay.banon) 29 | */ 30 | public class Log4jESLogger extends AbstractESLogger { 31 | 32 | private final org.apache.log4j.Logger logger; 33 | 34 | public Log4jESLogger(String prefix, Logger logger) { 35 | super(prefix); 36 | this.logger = logger; 37 | 38 | } 39 | 40 | public String getName() { 41 | return logger.getName(); 42 | } 43 | 44 | public boolean isTraceEnabled() { 45 | return logger.isTraceEnabled(); 46 | } 47 | 48 | public boolean isDebugEnabled() { 49 | return logger.isDebugEnabled(); 50 | } 51 | 52 | public boolean isInfoEnabled() { 53 | return logger.isInfoEnabled(); 54 | } 55 | 56 | public boolean isWarnEnabled() { 57 | return logger.isEnabledFor(Level.WARN); 58 | } 59 | 60 | public boolean isErrorEnabled() { 61 | return logger.isEnabledFor(Level.ERROR); 62 | } 63 | 64 | protected void internalTrace(String msg) { 65 | logger.trace(msg); 66 | } 67 | 68 | protected void internalTrace(String msg, Throwable cause) { 69 | logger.trace(msg, cause); 70 | } 71 | 72 | protected void internalDebug(String msg) { 73 | logger.debug(msg); 74 | } 75 | 76 | protected void internalDebug(String msg, Throwable cause) { 77 | logger.debug(msg, cause); 78 | } 79 | 80 | protected void internalInfo(String msg) { 81 | logger.info(msg); 82 | } 83 | 84 | protected void internalInfo(String msg, Throwable cause) { 85 | logger.info(msg, cause); 86 | } 87 | 88 | protected void internalWarn(String msg) { 89 | logger.warn(msg); 90 | } 91 | 92 | protected void internalWarn(String msg, Throwable cause) { 93 | logger.warn(msg, cause); 94 | } 95 | 96 | protected void internalError(String msg) { 97 | logger.error(msg); 98 | } 99 | 100 | protected void internalError(String msg, Throwable cause) { 101 | logger.error(msg, cause); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/jdk/JdkESLogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging.jdk; 21 | 22 | import java.util.logging.Level; 23 | import java.util.logging.Logger; 24 | 25 | import org.langke.util.logging.support.AbstractESLogger; 26 | 27 | 28 | /** 29 | * @author kimchy (shay.banon) 30 | */ 31 | public class JdkESLogger extends AbstractESLogger { 32 | 33 | private final Logger logger; 34 | 35 | public JdkESLogger(String prefix, Logger logger) { 36 | super(prefix); 37 | this.logger = logger; 38 | } 39 | 40 | public String getName() { 41 | return logger.getName(); 42 | } 43 | 44 | public boolean isTraceEnabled() { 45 | return logger.isLoggable(Level.FINEST); 46 | } 47 | 48 | public boolean isDebugEnabled() { 49 | return logger.isLoggable(Level.FINE); 50 | } 51 | 52 | public boolean isInfoEnabled() { 53 | return logger.isLoggable(Level.INFO); 54 | } 55 | 56 | public boolean isWarnEnabled() { 57 | return logger.isLoggable(Level.WARNING); 58 | } 59 | 60 | public boolean isErrorEnabled() { 61 | return logger.isLoggable(Level.SEVERE); 62 | } 63 | 64 | protected void internalTrace(String msg) { 65 | logger.log(Level.FINEST, msg); 66 | } 67 | 68 | protected void internalTrace(String msg, Throwable cause) { 69 | logger.log(Level.FINEST, msg, cause); 70 | } 71 | 72 | protected void internalDebug(String msg) { 73 | logger.log(Level.FINE, msg); 74 | } 75 | 76 | protected void internalDebug(String msg, Throwable cause) { 77 | logger.log(Level.FINE, msg, cause); 78 | } 79 | 80 | protected void internalInfo(String msg) { 81 | logger.log(Level.INFO, msg); 82 | } 83 | 84 | protected void internalInfo(String msg, Throwable cause) { 85 | logger.log(Level.INFO, msg, cause); 86 | } 87 | 88 | protected void internalWarn(String msg) { 89 | logger.log(Level.WARNING, msg); 90 | } 91 | 92 | protected void internalWarn(String msg, Throwable cause) { 93 | logger.log(Level.WARNING, msg, cause); 94 | } 95 | 96 | protected void internalError(String msg) { 97 | logger.log(Level.SEVERE, msg); 98 | } 99 | 100 | protected void internalError(String msg, Throwable cause) { 101 | logger.log(Level.SEVERE, msg, cause); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/org/langke/common/bdb/BrekeleyDBImpl.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.bdb; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Map.Entry; 6 | 7 | import org.langke.util.logging.ESLogger; 8 | import org.langke.util.logging.Loggers; 9 | 10 | import com.sleepycat.bind.EntryBinding; 11 | import com.sleepycat.bind.serial.SerialBinding; 12 | import com.sleepycat.collections.StoredMap; 13 | import com.sleepycat.je.DatabaseException; 14 | 15 | public class BrekeleyDBImpl extends AbstractBerkeleyDB implements BrekeleyDB { 16 | private StoredMap storedMap = null; 17 | private static ESLogger log = Loggers.getLogger(BrekeleyDBImpl.class); 18 | 19 | //使用默认的路径和缓存大小构造函数 20 | public BrekeleyDBImpl(String homeDirectory,String dbname,Class valueBindClass) { 21 | super(homeDirectory,dbname); 22 | EntryBinding keyBinding =new SerialBinding (javaCatalog,String.class); 23 | EntryBinding valueBinding =new SerialBinding(javaCatalog, valueBindClass); 24 | storedMap = new StoredMap(database,keyBinding, valueBinding, true); 25 | log.info(homeDirectory+" dbname:"+dbname+" alivedb:"+env.getDatabaseNames()); 26 | } 27 | 28 | public Object poll() { 29 | if(!storedMap.isEmpty()){ 30 | Entry entry=(Entry)storedMap.entrySet().iterator().next(); 31 | delete(entry.getKey()); 32 | return entry; 33 | } 34 | return null; 35 | } 36 | 37 | public List poll(int limit) { 38 | List list = new ArrayList(); 39 | for(int i=0;i entry=(Entry)storedMap.entrySet().iterator().next(); 42 | list.add(entry); 43 | delete(entry.getKey()); 44 | } 45 | } 46 | return list; 47 | } 48 | 49 | // 存入 50 | public void put(Object key,Object value) { 51 | storedMap.put(key, value); 52 | } 53 | //取出 54 | public Object get(Object key){ 55 | return storedMap.get(key); 56 | } 57 | public List get(int limit){ 58 | List list = new ArrayList(); 59 | for(int i=0;i entry=(Entry)storedMap.entrySet().iterator().next(); 62 | list.add(entry); 63 | } 64 | } 65 | return list; 66 | } 67 | //删除 68 | public Object delete(Object key){ 69 | return storedMap.remove(key); 70 | } 71 | public int size(){ 72 | return storedMap.size(); 73 | } 74 | public boolean isEmpty(){ 75 | return storedMap.isEmpty(); 76 | } 77 | public boolean contains(Object key){ 78 | return storedMap.containsKey(key); 79 | } 80 | public void clear(){ 81 | storedMap.clear(); 82 | } 83 | 84 | // 测试函数 85 | public static void main(String[] strs) { 86 | BrekeleyDBImpl bdb = null ; 87 | try { 88 | bdb = new BrekeleyDBImpl("bdb","db_test",String.class); 89 | log.info("{}",bdb.env.getDatabaseNames()); 90 | bdb.put("key", "value"); 91 | log.info("{}", bdb.get("key")); 92 | } catch (Exception e) { 93 | e.printStackTrace(); 94 | }finally{ 95 | try { 96 | if (bdb != null) 97 | bdb.close(); 98 | } catch (DatabaseException e) { 99 | e.printStackTrace(); 100 | } 101 | } 102 | 103 | } 104 | 105 | 106 | } 107 | -------------------------------------------------------------------------------- /conf/applicationContext.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/org/langke/common/server/BaseNioServer.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.server; 2 | 3 | import java.net.InetSocketAddress; 4 | import java.net.SocketAddress; 5 | import java.net.SocketException; 6 | import java.util.concurrent.Executors; 7 | 8 | import org.jboss.netty.bootstrap.ServerBootstrap; 9 | import org.jboss.netty.channel.Channel; 10 | import org.jboss.netty.channel.ChannelFactory; 11 | import org.jboss.netty.channel.ChannelPipeline; 12 | import org.jboss.netty.channel.ChannelPipelineFactory; 13 | import org.jboss.netty.channel.ChannelUpstreamHandler; 14 | import org.jboss.netty.channel.Channels; 15 | import org.jboss.netty.channel.group.ChannelGroup; 16 | import org.jboss.netty.channel.group.ChannelGroupFuture; 17 | import org.jboss.netty.channel.group.DefaultChannelGroup; 18 | import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; 19 | import org.jboss.netty.handler.codec.serialization.ObjectDecoder; 20 | import org.jboss.netty.handler.codec.serialization.ObjectEncoder; 21 | import org.langke.util.logging.ESLogger; 22 | import org.langke.util.logging.Loggers; 23 | 24 | 25 | /* 26 | * @copyright (c) langke 2011 27 | * @author langke 2011-5-1 28 | */ 29 | public abstract class BaseNioServer implements Server { 30 | 31 | private final ChannelGroup allChannels = new DefaultChannelGroup("nio-server"); 32 | protected ESLogger log; 33 | protected ServerBootstrap bootstrap; 34 | protected ChannelFactory channelFactory = null; 35 | private static final int defaultPort = 10001; 36 | 37 | public BaseNioServer() { 38 | } 39 | @Override 40 | public void init() { 41 | log = Loggers.getLogger(this.serverName()); 42 | } 43 | @Override 44 | public void start() { 45 | this.channelFactory = this.createChannelFactory(); 46 | bootstrap = new ServerBootstrap(channelFactory); 47 | bootstrap.setPipelineFactory(getChannelPipelineFactory()); 48 | SocketAddress sa = this.getSocketAddress(); 49 | Channel serverChannel = bootstrap.bind(sa); 50 | allChannels.add(serverChannel); 51 | log.info("server started at/" + sa); 52 | } 53 | @Override 54 | public void stop() { 55 | ChannelGroupFuture closeFuture = allChannels.close(); 56 | closeFuture.awaitUninterruptibly(); 57 | if (channelFactory != null) 58 | channelFactory.releaseExternalResources(); 59 | } 60 | 61 | protected int defaultPort(){ 62 | return defaultPort; 63 | } 64 | 65 | protected ServerAddress getServerAddress() { 66 | String myip = "0.0.0.0"; 67 | int myport = defaultPort(); 68 | try { 69 | myip = NetworkUtils.getFirstNonLoopbackAddress(NetworkUtils.StackType.IPv4).getHostAddress(); 70 | } catch (SocketException e) { 71 | e.printStackTrace(); 72 | } 73 | return new ServerAddress(myip, myport); 74 | } 75 | 76 | protected final SocketAddress getSocketAddress() { 77 | ServerAddress sa = this.getServerAddress(); 78 | if(sa.getHost() == null){ 79 | return new InetSocketAddress(sa.getPort()); 80 | } 81 | return new InetSocketAddress(sa.getHost(), sa.getPort()); 82 | } 83 | 84 | protected ChannelFactory createChannelFactory() { 85 | return new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); 86 | } 87 | 88 | protected ChannelPipelineFactory getChannelPipelineFactory() { 89 | return new ChannelPipelineFactory() { 90 | public ChannelPipeline getPipeline() throws Exception { 91 | return Channels.pipeline(new ObjectEncoder(),new ObjectDecoder(), finalChannelUpstreamHandler()); 92 | } 93 | }; 94 | } 95 | 96 | protected abstract ChannelUpstreamHandler finalChannelUpstreamHandler(); 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/org/langke/core/service/impl/DemoServiceImpl.java: -------------------------------------------------------------------------------- 1 | package org.langke.core.service.impl; 2 | 3 | import org.apache.commons.lang.math.RandomUtils; 4 | import org.langke.bean.HelloTable; 5 | import org.langke.common.bdb.BrekeleyDB; 6 | import org.langke.common.server.NettyHttpRequest; 7 | import org.langke.common.server.resp.RespData; 8 | import org.langke.core.dao.IDemoDao; 9 | import org.langke.core.dao.mappers.HelloTableMapper; 10 | import org.langke.core.service.DemoService; 11 | import org.langke.util.logging.ESLogger; 12 | import org.langke.util.logging.Loggers; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.stereotype.Service; 15 | 16 | @Service("demoService") 17 | public class DemoServiceImpl implements DemoService{ 18 | private static ESLogger log = Loggers.getLogger(DemoServiceImpl.class); 19 | 20 | @Autowired 21 | private BrekeleyDB brekeleyDB; 22 | 23 | @Autowired 24 | private HelloTableMapper helloTableMapper; 25 | 26 | @Autowired 27 | private IDemoDao demoDao; 28 | public void setDemoDao(IDemoDao demoDao) { 29 | this.demoDao = demoDao; 30 | } 31 | @Override 32 | public RespData test(NettyHttpRequest request) { 33 | RespData data = new RespData(); 34 | data.setContent(request.params()); 35 | return data; 36 | } 37 | @Override 38 | public RespData create(NettyHttpRequest request) { 39 | RespData data = new RespData(); 40 | try{ 41 | data.setContent(request.params()); 42 | demoDao.create(); 43 | demoDao.insert(); 44 | demoDao.update(request.param("name")); 45 | data.setContent(demoDao.select()); 46 | }catch(Exception e){ 47 | log.error("{}", e); 48 | throw new RuntimeException(e); 49 | } 50 | return data; 51 | } 52 | @Override 53 | public RespData select(NettyHttpRequest request) { 54 | RespData data = new RespData(); 55 | try{ 56 | data.setContent(demoDao.select()); 57 | }catch(Exception e){ 58 | log.error("{}", e); 59 | throw new RuntimeException(e); 60 | } 61 | return data; 62 | } 63 | @Override 64 | public RespData insert(NettyHttpRequest request) { 65 | RespData data = new RespData(); 66 | try{ 67 | data.setContent(demoDao.insert()); 68 | }catch(Exception e){ 69 | log.error("{}", e); 70 | throw new RuntimeException(e); 71 | } 72 | return data; 73 | } 74 | @Override 75 | public RespData update(NettyHttpRequest request) { 76 | RespData data = new RespData(); 77 | try{ 78 | data.setContent(demoDao.update(request.param("name"))); 79 | }catch(Exception e){ 80 | log.error("{}", e); 81 | throw new RuntimeException(e); 82 | } 83 | return data; 84 | } 85 | 86 | 87 | public RespData mybatis(NettyHttpRequest request) { 88 | RespData data = new RespData(); 89 | try{ 90 | HelloTable helloTable = new HelloTable(); 91 | helloTable.setName("ibatis"); 92 | helloTable.setScore(100); 93 | helloTableMapper.insert(helloTable); 94 | data.setContent(helloTableMapper.select(new HelloTable())); 95 | }catch(Exception e){ 96 | log.error("{}", e); 97 | throw new RuntimeException(e); 98 | } 99 | return data; 100 | } 101 | 102 | 103 | /** 104 | * http://localhost:9090/demo/bdb?key=value 105 | * @param key 106 | * @param value 107 | * @return 108 | */ 109 | 110 | public RespData bdb(NettyHttpRequest request) { 111 | RespData data = new RespData(); 112 | try{ 113 | String key = request.param("key","key"); 114 | String value = request.param("value","value"); 115 | int random = RandomUtils.nextInt(); 116 | brekeleyDB.put(key+random, value+random); 117 | data.setContent(brekeleyDB.get(10)); 118 | }catch(Exception e){ 119 | log.error("{}", e); 120 | throw new RuntimeException(e); 121 | } 122 | return data; 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/support/AbstractESLogger.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging.support; 21 | 22 | import org.langke.util.logging.ESLogger; 23 | 24 | /** 25 | * @author kimchy (shay.banon) 26 | */ 27 | public abstract class AbstractESLogger implements ESLogger { 28 | 29 | private final String prefix; 30 | 31 | protected AbstractESLogger(String prefix) { 32 | this.prefix = prefix; 33 | } 34 | 35 | public String getPrefix() { 36 | return this.prefix; 37 | } 38 | 39 | public void trace(String msg, Object... params) { 40 | if (isTraceEnabled()) { 41 | internalTrace(LoggerMessageFormat.format(prefix, msg, params)); 42 | } 43 | } 44 | 45 | protected abstract void internalTrace(String msg); 46 | 47 | public void trace(String msg, Throwable cause, Object... params) { 48 | if (isTraceEnabled()) { 49 | internalTrace(LoggerMessageFormat.format(prefix, msg, params), 50 | cause); 51 | } 52 | } 53 | 54 | protected abstract void internalTrace(String msg, Throwable cause); 55 | 56 | public void debug(String msg, Object... params) { 57 | if (isDebugEnabled()) { 58 | internalDebug(LoggerMessageFormat.format(prefix, msg, params)); 59 | } 60 | } 61 | 62 | protected abstract void internalDebug(String msg); 63 | 64 | public void debug(String msg, Throwable cause, Object... params) { 65 | if (isDebugEnabled()) { 66 | internalDebug(LoggerMessageFormat.format(prefix, msg, params), 67 | cause); 68 | } 69 | } 70 | 71 | protected abstract void internalDebug(String msg, Throwable cause); 72 | 73 | public void info(String msg, Object... params) { 74 | if (isInfoEnabled()) { 75 | internalInfo(LoggerMessageFormat.format(prefix, msg, params)); 76 | } 77 | } 78 | 79 | protected abstract void internalInfo(String msg); 80 | 81 | public void info(String msg, Throwable cause, Object... params) { 82 | if (isInfoEnabled()) { 83 | internalInfo(LoggerMessageFormat.format(prefix, msg, params), cause); 84 | } 85 | } 86 | 87 | protected abstract void internalInfo(String msg, Throwable cause); 88 | 89 | public void warn(String msg, Object... params) { 90 | if (isWarnEnabled()) { 91 | internalWarn(LoggerMessageFormat.format(prefix, msg, params)); 92 | } 93 | } 94 | 95 | protected abstract void internalWarn(String msg); 96 | 97 | public void warn(String msg, Throwable cause, Object... params) { 98 | if (isWarnEnabled()) { 99 | internalWarn(LoggerMessageFormat.format(prefix, msg, params), cause); 100 | } 101 | } 102 | 103 | protected abstract void internalWarn(String msg, Throwable cause); 104 | 105 | public void error(String msg, Object... params) { 106 | if (isErrorEnabled()) { 107 | internalError(LoggerMessageFormat.format(prefix, msg, params)); 108 | } 109 | } 110 | 111 | protected abstract void internalError(String msg); 112 | 113 | public void error(String msg, Throwable cause, Object... params) { 114 | if (isErrorEnabled()) { 115 | internalError(LoggerMessageFormat.format(prefix, msg, params), 116 | cause); 117 | } 118 | } 119 | 120 | protected abstract void internalError(String msg, Throwable cause); 121 | } 122 | -------------------------------------------------------------------------------- /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/org/langke/util/FileUtil.java: -------------------------------------------------------------------------------- 1 | package org.langke.util; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.BufferedWriter; 5 | import java.io.File; 6 | import java.io.FileInputStream; 7 | import java.io.FileOutputStream; 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.io.InputStreamReader; 11 | import java.io.OutputStream; 12 | import java.io.OutputStreamWriter; 13 | import java.io.Reader; 14 | import java.net.URL; 15 | 16 | /* 17 | * @copyright (c) langke 2011 18 | * @author langke 2011-5-1 19 | */ 20 | public class FileUtil { 21 | 22 | public static BufferedReader getReader(String folder, String fileName) throws IOException { 23 | return getReader(new File(folder, fileName), "utf8"); 24 | } 25 | 26 | public static BufferedReader getReader(String path) throws IOException { 27 | return getReader(new File(path)); 28 | } 29 | 30 | public static BufferedReader getReader(URL path) throws IOException { 31 | return new BufferedReader(new InputStreamReader(path.openConnection().getInputStream())); 32 | } 33 | 34 | public static BufferedReader getReader(File file) throws IOException { 35 | return getReader(file, "utf8"); 36 | } 37 | 38 | public static BufferedWriter getWriter(String folder, String fileName) throws IOException { 39 | return getWriter(new File(folder, fileName), "utf8"); 40 | } 41 | 42 | public static BufferedWriter getWriter(String path) throws IOException { 43 | return getWriter(new File(path), "utf8"); 44 | } 45 | 46 | public static BufferedWriter getWriter(File file) throws IOException { 47 | return getWriter(file, "utf8"); 48 | } 49 | 50 | public static int lineCount(File file) throws IOException { 51 | BufferedReader reader = getReader(file); 52 | int count = 0; 53 | while (reader.readLine() != null) { 54 | count++; 55 | } 56 | return count; 57 | } 58 | 59 | public static BufferedWriter getWriter(File file, String encode) throws IOException { 60 | return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encode)); 61 | } 62 | 63 | public static BufferedReader getReader(File file, String encode) throws IOException { 64 | return new BufferedReader(new InputStreamReader(new FileInputStream(file), encode)); 65 | } 66 | 67 | public static boolean createNewFile(String path){ 68 | try { 69 | new File(path).createNewFile(); 70 | } catch (IOException e) { 71 | e.printStackTrace(); 72 | return false; 73 | } 74 | return true; 75 | } 76 | 77 | public static void move(String filepath,String dirpath){ 78 | move(new File(filepath),dirpath); 79 | } 80 | public static void move(File file,String dirpath){ 81 | File newfile = new File(dirpath,file.getName()); 82 | if(!newfile.exists()) 83 | file.renameTo(newfile); 84 | else 85 | file.delete(); 86 | } 87 | 88 | public static void delete(String filepath) { 89 | File file = new File(filepath); 90 | if(file.exists()) 91 | file.delete(); 92 | } 93 | 94 | public static void closeReader(Reader reader) { 95 | try { 96 | if(reader!=null) 97 | reader.close(); 98 | } catch (IOException e) { 99 | e.printStackTrace(); 100 | } 101 | } 102 | 103 | public static void copy(File src, File dst) throws IOException { 104 | InputStream in = new FileInputStream(src); 105 | OutputStream out = new FileOutputStream(dst); 106 | // Transfer bytes from in to out 107 | byte[] buf = new byte[1024]; 108 | int len; 109 | while ((len = in.read(buf)) > 0) { 110 | out.write(buf, 0, len); 111 | } 112 | if(in!=null) 113 | in.close(); 114 | if(out!=null) 115 | out.close(); 116 | } 117 | public static void copy(InputStream in, File dst) throws IOException { 118 | OutputStream out = new FileOutputStream(dst); 119 | // Transfer bytes from in to out 120 | byte[] buf = new byte[1024]; 121 | int len; 122 | while ((len = in.read(buf)) != -1) { 123 | out.write(buf, 0, len); 124 | } 125 | if(out!=null) 126 | out.close(); 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /src/org/langke/core/server/JavaMelodyMonitorServer.java: -------------------------------------------------------------------------------- 1 | package org.langke.core.server; 2 | 3 | import java.util.EventListener; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import javax.servlet.Filter; 8 | 9 | import org.langke.common.Config; 10 | import org.langke.util.logging.ESLogger; 11 | import org.langke.util.logging.Loggers; 12 | import org.mortbay.jetty.Connector; 13 | import org.mortbay.jetty.Handler; 14 | import org.mortbay.jetty.Server; 15 | import org.mortbay.jetty.bio.SocketConnector; 16 | import org.mortbay.jetty.handler.ContextHandlerCollection; 17 | import org.mortbay.jetty.handler.ResourceHandler; 18 | import org.mortbay.jetty.servlet.Context; 19 | import org.mortbay.jetty.servlet.DefaultServlet; 20 | import org.mortbay.jetty.servlet.FilterHolder; 21 | import org.mortbay.thread.QueuedThreadPool; 22 | 23 | 24 | /** 25 | * 启动一个jetty容器,结合javamelody用于监控应用性能 26 | * @author langke 27 | * 2012-12-21 28 | */ 29 | public class JavaMelodyMonitorServer { 30 | private ESLogger log = Loggers.getLogger(JavaMelodyMonitorServer.class); 31 | Server webServer; 32 | /** 33 | * 34 | * @param serverName 应用名称 35 | * @param host 绑定的IP地址 36 | * @param serverPort 应用端口,jetty启动的端口默认会在此基础上加1000,如果配置文件有配置jetty.listen.port则配置优先 37 | */ 38 | public JavaMelodyMonitorServer(String serverName,String host,int serverPort) { 39 | init(serverName, host, serverPort); 40 | start(); 41 | final JavaMelodyMonitorServer server = this; 42 | Runtime.getRuntime().addShutdownHook(new Thread() { 43 | @Override 44 | public void run() { 45 | try { 46 | log.info("shutdown mointorServer:{}", server); 47 | server.stop(); 48 | } catch (Exception e) { 49 | log.error("run main stop error!", e); 50 | } 51 | } 52 | 53 | }); 54 | } 55 | 56 | private void init(String serverName,String host,int serverPort){ 57 | int defaultValue = serverPort+1000; 58 | int port = Config.get().getInt("jetty.listen.port", defaultValue); 59 | Connector connector = new SocketConnector(); 60 | webServer = new Server(); 61 | QueuedThreadPool pool = new QueuedThreadPool(); 62 | pool.setMinThreads(Config.get().getInt("jetty.pool.MinThread", 3)); 63 | pool.setMaxThreads(Config.get().getInt("jetty.pool.MaxThread", 32)); 64 | String server = host; 65 | pool.setName(serverName+"-monitor"); 66 | pool.setDaemon(true); 67 | webServer.setThreadPool(pool); 68 | connector = new SocketConnector(); 69 | 70 | connector.setPort(port); 71 | connector.setHost(server); 72 | connector.setMaxIdleTime(60000); // 1 min 73 | webServer.addConnector(connector); 74 | 75 | ContextHandlerCollection col = new ContextHandlerCollection(); 76 | Context context = new Context(col, "/", Context.SESSIONS); 77 | ResourceHandler resourceHandler = new ResourceHandler(); 78 | webServer.setHandlers(new Handler[] {col,resourceHandler }); 79 | webServer.addHandler(context); 80 | // Set Java Melody storage Directory 81 | String user_dir = System.getProperty("user.dir",""); 82 | System.setProperty("javamelody.storage-directory", user_dir+"/logs/javamelody-"+pool.getName()); 83 | 84 | //add filter 85 | Filter monitoringFilter = new net.bull.javamelody.MonitoringFilter(); 86 | context.addFilter(new FilterHolder(monitoringFilter), "/monitoring", Handler.REQUEST); 87 | 88 | // Map initParams = new HashMap(); 89 | // initParams.put("contextConfigLocation", "classpath:net/bull/javamelody/monitoring-spring.xml,classpath:resource/*.xml,classpath:conf/applicationContext.xml"); 90 | // context.setInitParams(initParams); 91 | 92 | //add listener 93 | //EventListener listener = new ContextLoaderListener(); 94 | //context.addEventListener(listener); 95 | 96 | context.addServlet(DefaultServlet.class, "/*"); 97 | } 98 | 99 | public void start(){ 100 | try{ 101 | webServer.join(); 102 | webServer.start(); 103 | }catch (Exception e){ 104 | log.error("Error starting httpserver", e); 105 | } 106 | } 107 | 108 | public void stop(){ 109 | try{ 110 | webServer.stop(); 111 | webServer.destroy(); 112 | }catch (Exception e){ 113 | log.error("Error stop httpserver", e); 114 | } 115 | 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/org/langke/core/server/RestNettyServer.java: -------------------------------------------------------------------------------- 1 | package org.langke.core.server; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | import org.jboss.netty.channel.ChannelPipeline; 6 | import org.jboss.netty.channel.ChannelPipelineFactory; 7 | import org.jboss.netty.channel.ChannelUpstreamHandler; 8 | import org.jboss.netty.channel.Channels; 9 | import org.jboss.netty.handler.codec.http.HttpChunkAggregator; 10 | import org.jboss.netty.handler.codec.http.HttpMethod; 11 | import org.jboss.netty.handler.codec.http.HttpRequestDecoder; 12 | import org.jboss.netty.handler.codec.http.HttpResponseEncoder; 13 | import org.jboss.netty.handler.stream.ChunkedWriteHandler; 14 | import org.jboss.netty.handler.timeout.ReadTimeoutHandler; 15 | import org.jboss.netty.handler.timeout.WriteTimeoutHandler; 16 | import org.jboss.netty.util.HashedWheelTimer; 17 | import org.jboss.netty.util.Timer; 18 | import org.langke.common.Config; 19 | import org.langke.common.server.BaseNioServer; 20 | import org.langke.common.server.Handler; 21 | import org.langke.common.server.NettyHttpRequest; 22 | import org.langke.common.server.RestChannelHandler; 23 | import org.langke.common.server.ServerAddress; 24 | import org.langke.common.server.resp.Resp; 25 | import org.langke.core.handler.DemoHandler; 26 | import org.langke.util.logging.ESLogger; 27 | import org.langke.util.logging.Loggers; 28 | 29 | 30 | /** 31 | * 32 | * @author langke 33 | * @date 2012-9-11 34 | * 35 | */ 36 | public class RestNettyServer extends BaseNioServer { 37 | private static ESLogger log = Loggers.getLogger(RestNettyServer.class); 38 | 39 | private RestChannelHandler restHandler = null; 40 | 41 | public RestNettyServer() { 42 | restHandler = new RestChannelHandler(); 43 | restHandler.registerHandler(HttpMethod.GET, "/", new Handler() { 44 | @Override 45 | public Resp handleRequest(NettyHttpRequest request) { 46 | return new Resp("rest netty server 0.1"); 47 | } 48 | }); 49 | DemoHandler demo = new DemoHandler(); 50 | //Handler demo = net.bull.javamelody.MonitoringProxy.createProxy(new DemoHandler()); 51 | restHandler.registerHandler(HttpMethod.GET, "/demo/{label}", demo); 52 | restHandler.registerHandler(HttpMethod.POST, "/demo/{label}", demo); 53 | 54 | } 55 | 56 | @Override 57 | protected ChannelPipelineFactory getChannelPipelineFactory() { 58 | final Timer timer = new HashedWheelTimer(Config.get().getInt("readTimeout", 60), TimeUnit.SECONDS); 59 | return new ChannelPipelineFactory() { 60 | public ChannelPipeline getPipeline() throws Exception { 61 | // Create a default pipeline implementation. 62 | ChannelPipeline pipeline = Channels.pipeline(); 63 | pipeline.addLast("readTimeout", new ReadTimeoutHandler(timer, Config.get().getInt("readTimeout", 60))); 64 | pipeline.addLast("writeTimeout", new WriteTimeoutHandler(timer, Config.get().getInt("writeTimeout", 60))); 65 | pipeline.addLast("decoder", new HttpRequestDecoder()); 66 | pipeline.addLast("encoder", new HttpResponseEncoder()); 67 | pipeline.addLast("aggregator", new HttpChunkAggregator(1048576)); 68 | pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); 69 | pipeline.addLast("query", restHandler); 70 | return pipeline; 71 | } 72 | }; 73 | } 74 | 75 | @Override 76 | protected int defaultPort() { 77 | return 9005; 78 | } 79 | 80 | @Override 81 | public String serverName() { 82 | return Config.get().get("server.name", "rest-netty-server"); 83 | } 84 | 85 | @Override 86 | public void init() { 87 | super.init(); 88 | } 89 | 90 | @Override 91 | public void start() { 92 | super.start(); 93 | } 94 | 95 | protected ServerAddress getServerAddress() { 96 | String listen = Config.get().get("server.listen"); 97 | String address = Config.get().get("server.listen.address"); 98 | String port = Config.get().get("server.listen.port"); 99 | if(listen != null){ 100 | return new ServerAddress(listen); 101 | } 102 | return new ServerAddress(address, (port!=null?Integer.parseInt(port):defaultPort())); 103 | } 104 | 105 | @Override 106 | protected ChannelUpstreamHandler finalChannelUpstreamHandler() { 107 | return null; 108 | } 109 | 110 | public static void main(String[] args) { 111 | SpringApplicationContext.getInstance(); 112 | final RestNettyServer o = new RestNettyServer(); 113 | o.init(); 114 | o.start(); 115 | new JavaMelodyMonitorServer(o.serverName(),o.getServerAddress().getHost(),o.getServerAddress().getPort()); 116 | 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/org/langke/util/HttpClientUtil.java: -------------------------------------------------------------------------------- 1 | package org.langke.util; 2 | 3 | import org.apache.commons.httpclient.HttpClient; 4 | import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; 5 | import org.apache.commons.httpclient.methods.GetMethod; 6 | import org.apache.commons.httpclient.methods.PostMethod; 7 | import org.apache.commons.httpclient.methods.RequestEntity; 8 | import org.apache.commons.httpclient.methods.StringRequestEntity; 9 | import org.apache.commons.httpclient.params.HttpConnectionManagerParams; 10 | import org.apache.commons.httpclient.params.HttpMethodParams; 11 | import org.langke.common.StrIntBag; 12 | import org.langke.common.Strings; 13 | import org.langke.util.logging.ESLogger; 14 | import org.langke.util.logging.Loggers; 15 | 16 | 17 | /* 18 | * @copyright (c) langke 2011 19 | * @author langke Aug 9, 2011 20 | */ 21 | public class HttpClientUtil { 22 | 23 | private static ESLogger log = Loggers.getLogger(HttpClientUtil.class); 24 | private static HttpClient client = null; 25 | private static MultiThreadedHttpConnectionManager conn_manager = null; 26 | private static HttpConnectionManagerParams cmanager_params = null; 27 | static{ 28 | if(client==null) init(); 29 | } 30 | private static void init(){ 31 | if (conn_manager == null) 32 | conn_manager = new MultiThreadedHttpConnectionManager(); 33 | if (cmanager_params == null) 34 | cmanager_params = new HttpConnectionManagerParams(); 35 | // config the HTTP client visit performance. 36 | cmanager_params.setDefaultMaxConnectionsPerHost(90); 37 | cmanager_params.setMaxTotalConnections(256); 38 | cmanager_params.setConnectionTimeout(6000); 39 | conn_manager.setParams(cmanager_params); 40 | if (client == null) 41 | client = new HttpClient(conn_manager); 42 | } 43 | 44 | public static StrIntBag execute(String uri, String requestBody){ 45 | PostMethod post = null; 46 | StrIntBag bag = new StrIntBag(); 47 | try { 48 | post = new PostMethod(uri); 49 | post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); 50 | post.getParams().setParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); 51 | if(requestBody != null){ 52 | RequestEntity reqEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8"); 53 | post.setRequestEntity(reqEntity); 54 | } 55 | int status = client.executeMethod(post); 56 | String resp = post.getResponseBodyAsString(); 57 | bag._str = resp; 58 | bag._int = status; 59 | return bag; 60 | } catch (Exception e) { 61 | log.error("{}", Strings.throwableToString(e)); 62 | } finally{ 63 | if(post != null){ 64 | post.releaseConnection(); 65 | } 66 | } 67 | return null; 68 | } 69 | /** 70 | * 失败后,重试3次 71 | * @param uri 72 | * @param json 73 | * @return 74 | */ 75 | public static StrIntBag tryExecute(String uri, String json){ 76 | StrIntBag bag = execute(uri, json); 77 | if(bag != null){ 78 | return bag; 79 | } 80 | int tryCount = 3; 81 | while(bag == null && (tryCount--) > 0 ){ 82 | bag = execute(uri, json); 83 | try { 84 | Thread.sleep(20); 85 | } catch (InterruptedException e) { 86 | log.error("{}", Strings.throwableToString(e)); 87 | } 88 | } 89 | return bag; 90 | } 91 | 92 | public static StrIntBag executeGet(String url){ 93 | GetMethod get = null; 94 | StrIntBag bag = new StrIntBag(); 95 | try { 96 | get = new GetMethod(url); 97 | get.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8"); 98 | get.getParams().setParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); 99 | int status = client.executeMethod(get); 100 | String resp = get.getResponseBodyAsString(); 101 | bag._str = resp; 102 | bag._int = status; 103 | return bag; 104 | } catch (Exception e) { 105 | log.error("{}", Strings.throwableToString(e)); 106 | } finally{ 107 | if(get != null){ 108 | get.releaseConnection(); 109 | } 110 | } 111 | return null; 112 | } 113 | 114 | public static StrIntBag tryExecuteGet(String url){ 115 | StrIntBag bag = executeGet(url); 116 | if(bag != null){ 117 | return bag; 118 | } 119 | int tryCount = 3; 120 | while(bag == null && (tryCount--) > 0 ){ 121 | bag = executeGet(url); 122 | try { 123 | Thread.sleep(20); 124 | } catch (InterruptedException e) { 125 | log.error("{}", Strings.throwableToString(e)); 126 | } 127 | } 128 | return bag; 129 | } 130 | 131 | public static void main(String[] args) { 132 | StrIntBag resp = execute("http://10.10.10.201:9200/item/_search","{\"query\":\"地板\"}"); 133 | System.out.println(resp._str); 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/org/langke/common/Config.java: -------------------------------------------------------------------------------- 1 | package org.langke.common; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.util.Properties; 7 | 8 | import org.slf4j.Logger; 9 | import org.slf4j.LoggerFactory; 10 | 11 | public abstract class Config 12 | { 13 | public static Logger log = LoggerFactory.getLogger(Config.class); 14 | public static String getConfigDir(){ 15 | String configDir = null; 16 | String userDir = System.getProperty("user.dir"); 17 | if(System.getProperty("os.name").toLowerCase().contains("windows")){ 18 | configDir = userDir+"/conf"; 19 | }else{ 20 | configDir = userDir+"/../conf"; 21 | } 22 | return configDir; 23 | } 24 | public static String getConfigPath(){ 25 | return getConfigDir()+"/config.properties"; 26 | } 27 | private static final Config CONFIG = new Config() 28 | { 29 | Properties properties = new Properties(); 30 | boolean modified = false; 31 | private final File cf = new File(getConfigPath()); 32 | long time; 33 | { 34 | try{ 35 | if (!cf.exists()){ 36 | cf.getParentFile().mkdirs(); 37 | cf.createNewFile(); 38 | } 39 | //当进程关闭,如果properties有修改,则写入文件 40 | Runtime.getRuntime().addShutdownHook(new Thread("store-config"){ 41 | public void run(){ 42 | try{ 43 | if(modified){ 44 | boolean autoUpdate = properties.containsKey("autoUpdate"); 45 | if (autoUpdate){ 46 | FileOutputStream fos = new FileOutputStream(cf); 47 | properties.store(fos, "add an key to auto update config form default values"); 48 | fos.close(); 49 | } 50 | } 51 | }catch (Exception ex){ 52 | log.warn("store config", ex); 53 | } 54 | } 55 | }); 56 | properties.load(new java.io.FileInputStream(cf)); 57 | log.info("loading config from:" + cf.getAbsolutePath()); 58 | time = cf.lastModified(); 59 | //检测配置文件是否被修改,自动reload 60 | Thread t = new Thread(new Runnable(){ 61 | public void run(){ 62 | try{ 63 | Thread.sleep(60000); 64 | }catch (InterruptedException e){ 65 | } 66 | long newlmd = cf.lastModified(); 67 | if (newlmd > time){ 68 | time = newlmd; 69 | log.info("Config file {} is modified,reloading ...", cf.getAbsolutePath()); 70 | try{ 71 | properties.load(new java.io.FileInputStream(cf)); 72 | }catch (IOException e){ 73 | log.error("Error while loading config file:{}", cf.getAbsolutePath()); 74 | } 75 | } 76 | } 77 | }, "Config file refresher"); 78 | t.setDaemon(true); 79 | t.start(); 80 | }catch (IOException ex){ 81 | log.warn("cannot create log file", ex); 82 | } 83 | } 84 | 85 | public String get(String key) { 86 | return properties.getProperty(key); 87 | } 88 | 89 | public String get(String k, String defaultValue){ 90 | String s = properties.getProperty(k); 91 | if (s == null){ 92 | properties.setProperty(k, defaultValue); 93 | modified = true; 94 | return defaultValue; 95 | } 96 | return s; 97 | } 98 | 99 | public int getInt(String k, int defaultValue){ 100 | String s = this.get(k, defaultValue + ""); 101 | try{ 102 | return Integer.parseInt(s); 103 | }catch (Exception e){ 104 | return defaultValue; 105 | } 106 | } 107 | 108 | public boolean getBoolean(String k, boolean defaultValue){ 109 | String s = this.get(k, defaultValue + ""); 110 | try{ 111 | return Boolean.parseBoolean(s); 112 | }catch (Exception e){ 113 | return defaultValue; 114 | } 115 | } 116 | 117 | public boolean setProperty(String key, String value) { 118 | properties.setProperty(key, value); 119 | try{ 120 | FileOutputStream fos = new java.io.FileOutputStream(cf); 121 | properties.store(fos, ""); 122 | fos.close(); 123 | return true; 124 | }catch (Exception ex) { 125 | log.warn("store config", ex); 126 | return false; 127 | } 128 | } 129 | 130 | }; 131 | 132 | private Config(){ 133 | } 134 | public static final Config get(){ 135 | return CONFIG; 136 | } 137 | abstract public String get(String key); 138 | abstract public String get(String k, String defaultValue); 139 | abstract public int getInt(String k, int defaultValue); 140 | abstract public boolean getBoolean(String k, boolean defaultValue); 141 | abstract public boolean setProperty(String key, String value); 142 | 143 | } 144 | -------------------------------------------------------------------------------- /src/org/langke/common/server/PathTrie.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.server; 2 | 3 | import java.util.Collections; 4 | import java.util.Map; 5 | import java.util.concurrent.ConcurrentHashMap; 6 | import java.util.regex.Pattern; 7 | 8 | /* 9 | * @copyright (c) langke 2011 10 | * @author langke 2011-5-1 11 | */ 12 | @SuppressWarnings({"unused","unchecked","rawtypes"}) 13 | public class PathTrie { 14 | private final TrieNode root; 15 | private final Pattern pattern; 16 | private T rootValue; 17 | 18 | public PathTrie() { 19 | this("/", "*"); 20 | } 21 | 22 | public PathTrie(String separator, String wildcard) { 23 | pattern = Pattern.compile(separator); 24 | root = new TrieNode(separator, null, null, wildcard); 25 | } 26 | 27 | public static class TrieNode { 28 | private transient String key; 29 | private transient T value; 30 | private boolean isWildcard; 31 | private final String wildcard; 32 | 33 | private transient String namedWildcard; 34 | 35 | private Map> children; 36 | 37 | private final TrieNode parent; 38 | 39 | public TrieNode(String key, T value, TrieNode parent, String wildcard) { 40 | this.key = key; 41 | this.wildcard = wildcard; 42 | this.isWildcard = (key.equals(wildcard)); 43 | this.parent = parent; 44 | this.value = value; 45 | this.children = Collections.emptyMap(); 46 | if (isNamedWildcard(key)) { 47 | namedWildcard = key.substring(key.indexOf('{') + 1, 48 | key.indexOf('}')); 49 | } else { 50 | namedWildcard = null; 51 | } 52 | } 53 | 54 | public void updateKeyWithNamedWildcard(String key) { 55 | this.key = key; 56 | namedWildcard = key.substring(key.indexOf('{') + 1, 57 | key.indexOf('}')); 58 | } 59 | 60 | public boolean isWildcard() { 61 | return isWildcard; 62 | } 63 | 64 | public synchronized void addChild(TrieNode child) { 65 | Map m = new ConcurrentHashMap(children); 66 | m.put(child.key, child); 67 | children = Collections.unmodifiableMap(m); 68 | 69 | } 70 | 71 | public TrieNode getChild(String key) { 72 | return children.get(key); 73 | } 74 | 75 | public synchronized void insert(String[] path, int index, T value) { 76 | if (index >= path.length) 77 | return; 78 | 79 | String token = path[index]; 80 | String key = token; 81 | if (isNamedWildcard(token)) { 82 | key = wildcard; 83 | } 84 | TrieNode node = children.get(key); 85 | if (node == null) { 86 | if (index == (path.length - 1)) { 87 | node = new TrieNode(token, value, this, wildcard); 88 | } else { 89 | node = new TrieNode(token, null, this, wildcard); 90 | } 91 | Map m = new ConcurrentHashMap(children); 92 | m.put(key, node); 93 | children = Collections.unmodifiableMap(m); 94 | 95 | } else { 96 | if (isNamedWildcard(token)) { 97 | node.updateKeyWithNamedWildcard(token); 98 | } 99 | 100 | // in case the target(last) node already exist but without a 101 | // value 102 | // than the value should be updated. 103 | if (index == (path.length - 1)) { 104 | assert (node.value == null || node.value == value); 105 | if (node.value == null) { 106 | node.value = value; 107 | } 108 | } 109 | } 110 | 111 | node.insert(path, index + 1, value); 112 | } 113 | 114 | private boolean isNamedWildcard(String key) { 115 | return key.indexOf('{') != -1 && key.indexOf('}') != -1; 116 | } 117 | 118 | private String namedWildcard() { 119 | return namedWildcard; 120 | } 121 | 122 | private boolean isNamedWildcard() { 123 | return namedWildcard != null; 124 | } 125 | 126 | public T retrieve(String[] path, int index, Map params) { 127 | if (index >= path.length) 128 | return null; 129 | 130 | String token = path[index]; 131 | TrieNode node = children.get(token); 132 | boolean usedWildcard = false; 133 | if (node == null) { 134 | node = children.get(wildcard); 135 | if (node == null) { 136 | return null; 137 | } else { 138 | usedWildcard = true; 139 | if (params != null && node.isNamedWildcard()) { 140 | put(params, node.namedWildcard(), token); 141 | } 142 | } 143 | } 144 | 145 | if (index == (path.length - 1)) { 146 | return node.value; 147 | } 148 | 149 | T res = node.retrieve(path, index + 1, params); 150 | if (res == null && !usedWildcard) { 151 | node = children.get(wildcard); 152 | if (node != null) { 153 | if (params != null && node.isNamedWildcard()) { 154 | put(params, node.namedWildcard(), token); 155 | } 156 | res = node.retrieve(path, index + 1, params); 157 | } 158 | } 159 | 160 | return res; 161 | } 162 | } 163 | 164 | public void insert(String path, T value) { 165 | String[] strings = pattern.split(path); 166 | if (strings.length == 0) { 167 | rootValue = value; 168 | return; 169 | } 170 | int index = 0; 171 | // supports initial delimiter. 172 | if (strings.length > 0 && strings[0].isEmpty()) { 173 | index = 1; 174 | } 175 | root.insert(strings, index, value); 176 | } 177 | 178 | public T retrieve(String path) { 179 | return retrieve(path, null); 180 | } 181 | 182 | public T retrieve(String path, Map params) { 183 | if (path.length() == 0) { 184 | return rootValue; 185 | } 186 | String[] strings = pattern.split(path); 187 | if (strings.length == 0) { 188 | return rootValue; 189 | } 190 | int index = 0; 191 | // supports initial delimiter. 192 | if (strings.length > 0 && strings[0].isEmpty()) { 193 | index = 1; 194 | } 195 | return root.retrieve(strings, index, params); 196 | } 197 | 198 | private static void put(Map params, String key, String value) { 199 | params.put(key, value); 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /src/org/langke/common/server/NettyHttpRequest.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.server; 2 | 3 | /* 4 | * @copyright (c) langke 2011 5 | * @author langke 2011-5-1 6 | */ 7 | 8 | import java.io.UnsupportedEncodingException; 9 | 10 | import java.net.URLDecoder; 11 | 12 | import org.jboss.netty.channel.MessageEvent; 13 | import org.jboss.netty.handler.codec.http.HttpHeaders; 14 | import org.jboss.netty.handler.codec.http.HttpMethod; 15 | 16 | import java.nio.charset.Charset; 17 | import java.nio.charset.UnsupportedCharsetException; 18 | 19 | import java.util.HashMap; 20 | import java.util.List; 21 | import java.util.Map; 22 | import java.util.Set; 23 | import java.util.regex.Pattern; 24 | 25 | import org.jboss.netty.handler.codec.http.HttpRequest; 26 | 27 | public class NettyHttpRequest { 28 | 29 | private final HttpRequest request; 30 | private MessageEvent messageEvent; 31 | private final Map params; 32 | private final String path; 33 | private static final Pattern commaPattern = Pattern.compile(","); 34 | 35 | public NettyHttpRequest(HttpRequest request) { 36 | this.request = request; 37 | this.params = new HashMap(); 38 | String uri = request.getUri(); 39 | int pathEndPos = uri.indexOf('?'); 40 | if (pathEndPos < 0) { 41 | this.path = uri; 42 | } else { 43 | this.path = uri.substring(0, pathEndPos); 44 | decodeQueryString(uri, pathEndPos + 1, params); 45 | } 46 | } 47 | 48 | public HttpMethod method() { 49 | return this.request.getMethod(); 50 | } 51 | 52 | public static void decodeQueryString(String queryString, int fromIndex, 53 | Map params) { 54 | if (fromIndex < 0) { 55 | return; 56 | } 57 | if (fromIndex >= queryString.length()) { 58 | return; 59 | } 60 | int toIndex; 61 | while ((toIndex = queryString.indexOf('&', fromIndex)) >= 0) { 62 | int idx = queryString.indexOf('=', fromIndex); 63 | if (idx < 0) { 64 | continue; 65 | } 66 | params.put(decodeComponent(queryString.substring(fromIndex, idx)), 67 | decodeComponent(queryString.substring(idx + 1, toIndex))); 68 | fromIndex = toIndex + 1; 69 | } 70 | int idx = queryString.indexOf('=', fromIndex); 71 | if (idx < 0) { 72 | return; 73 | } 74 | params.put(decodeComponent(queryString.substring(fromIndex, idx)), 75 | decodeComponent(queryString.substring(idx + 1))); 76 | } 77 | 78 | private static String decodeComponent(String s) { 79 | if (s == null) { 80 | return ""; 81 | } 82 | try { 83 | return URLDecoder.decode(s, "UTF8"); 84 | } catch (UnsupportedEncodingException e) { 85 | throw new UnsupportedCharsetException("UTF8"); 86 | } 87 | } 88 | 89 | public float paramAsFloat(String key, float defaultValue) { 90 | String sValue = param(key); 91 | if (sValue == null) { 92 | return defaultValue; 93 | } 94 | 95 | return Float.parseFloat(sValue); 96 | 97 | } 98 | 99 | public int paramAsInt(String key, int defaultValue) { 100 | String sValue = param(key); 101 | if (sValue == null) { 102 | return defaultValue; 103 | } 104 | 105 | return Integer.parseInt(sValue); 106 | 107 | } 108 | 109 | public boolean paramAsBoolean(String key, boolean defaultValue) { 110 | return Boolean.parseBoolean(param(key)); 111 | } 112 | 113 | public Boolean paramAsBoolean(String key, Boolean defaultValue) { 114 | String sValue = param(key); 115 | if (sValue == null) { 116 | return defaultValue; 117 | } 118 | return !(sValue.equals("false") || sValue.equals("0") || sValue 119 | .equals("off")); 120 | } 121 | 122 | public String[] paramAsStringArray(String key, String[] defaultValue) { 123 | String value = param(key); 124 | if (value == null) { 125 | return defaultValue; 126 | } 127 | return commaPattern.split(value); 128 | } 129 | 130 | public String uri() { 131 | return request.getUri(); 132 | } 133 | 134 | public String path() { 135 | return path; 136 | } 137 | 138 | public Map params() { 139 | return params; 140 | } 141 | 142 | public boolean hasContent() { 143 | return request.getContent().readableBytes() > 0; 144 | } 145 | 146 | public int contentLength() { 147 | return request.getContent().readableBytes(); 148 | } 149 | 150 | public boolean contentUnsafe() { 151 | return request.getContent().hasArray(); 152 | } 153 | 154 | public int contentByteArrayOffset() { 155 | if (request.getContent().hasArray()) { 156 | // get the array offset, and the reader index offset within it 157 | return request.getContent().arrayOffset() + request.getContent().readerIndex(); 158 | } 159 | return 0; 160 | } 161 | 162 | private static Charset UTF8 = Charset.forName("UTF-8"); 163 | 164 | public String contentAsString() { 165 | return request.getContent().toString(UTF8); 166 | } 167 | 168 | public Set headerNames() { 169 | return request.getHeaderNames(); 170 | } 171 | 172 | public String header(String name) { 173 | return request.getHeader(name); 174 | } 175 | 176 | public List headers(String name) { 177 | return request.getHeaders(name); 178 | } 179 | 180 | public String cookie() { 181 | return request.getHeader(HttpHeaders.Names.COOKIE); 182 | } 183 | 184 | public boolean hasParam(String key) { 185 | return params.containsKey(key); 186 | } 187 | 188 | public String param(String key) { 189 | return params.get(key); 190 | } 191 | 192 | public String param(String key, String defaultValue) { 193 | String value = params.get(key); 194 | if (value == null) { 195 | return defaultValue; 196 | } 197 | return value; 198 | } 199 | 200 | public HttpRequest getRequest() { 201 | return request; 202 | } 203 | 204 | public MessageEvent getMessageEvent() { 205 | return messageEvent; 206 | } 207 | 208 | public void setMessageEvent(MessageEvent messageEvent) { 209 | this.messageEvent = messageEvent; 210 | } 211 | 212 | } 213 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/log4j/ConsoleAppender.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging.log4j; 21 | 22 | import java.io.IOException; 23 | import java.io.OutputStream; 24 | 25 | import org.apache.log4j.Layout; 26 | import org.apache.log4j.WriterAppender; 27 | import org.apache.log4j.helpers.LogLog; 28 | import org.langke.util.logging.Loggers; 29 | 30 | 31 | /** 32 | * ConsoleAppender appends log events to System.out or 33 | * System.err using a layout specified by the user. The default 34 | * target is System.out. 35 | *

36 | *

37 | * ElasticSearch: Adapter from log4j to allow to disable console logging... 38 | *

39 | * 40 | * @author Ceki Gülcü 41 | * @author Curt Arnold 42 | * @since 1.1 43 | */ 44 | public class ConsoleAppender extends WriterAppender { 45 | 46 | public static final String SYSTEM_OUT = "System.out"; 47 | public static final String SYSTEM_ERR = "System.err"; 48 | 49 | protected String target = SYSTEM_OUT; 50 | 51 | /** 52 | * Determines if the appender honors reassignments of System.out or 53 | * System.err made after configuration. 54 | */ 55 | private boolean follow = true; 56 | 57 | /** 58 | * Constructs an unconfigured appender. 59 | */ 60 | public ConsoleAppender() { 61 | } 62 | 63 | /** 64 | * Creates a configured appender. 65 | * 66 | * @param layout 67 | * layout, may not be null. 68 | */ 69 | public ConsoleAppender(Layout layout) { 70 | this(layout, SYSTEM_OUT); 71 | } 72 | 73 | /** 74 | * Creates a configured appender. 75 | * 76 | * @param layout 77 | * layout, may not be null. 78 | * @param target 79 | * target, either "System.err" or "System.out". 80 | */ 81 | public ConsoleAppender(Layout layout, String target) { 82 | setLayout(layout); 83 | setTarget(target); 84 | activateOptions(); 85 | } 86 | 87 | /** 88 | * Sets the value of the Target option. Recognized values are 89 | * "System.out" and "System.err". Any other value will be ignored. 90 | */ 91 | public void setTarget(String value) { 92 | String v = value.trim(); 93 | 94 | if (SYSTEM_OUT.equalsIgnoreCase(v)) { 95 | target = SYSTEM_OUT; 96 | } else if (SYSTEM_ERR.equalsIgnoreCase(v)) { 97 | target = SYSTEM_ERR; 98 | } else { 99 | targetWarn(value); 100 | } 101 | } 102 | 103 | /** 104 | * Returns the current value of the Target property. The default 105 | * value of the option is "System.out". 106 | *

107 | * See also {@link #setTarget}. 108 | */ 109 | public String getTarget() { 110 | return target; 111 | } 112 | 113 | /** 114 | * Sets whether the appender honors reassignments of System.out or 115 | * System.err made after configuration. 116 | * 117 | * @param newValue 118 | * if true, appender will use value of System.out or System.err 119 | * in force at the time when logging events are appended. 120 | * @since 1.2.13 121 | */ 122 | public final void setFollow(final boolean newValue) { 123 | follow = newValue; 124 | } 125 | 126 | /** 127 | * Gets whether the appender honors reassignments of System.out or 128 | * System.err made after configuration. 129 | * 130 | * @return true if appender will use value of System.out or System.err in 131 | * force at the time when logging events are appended. 132 | * @since 1.2.13 133 | */ 134 | public final boolean getFollow() { 135 | return follow; 136 | } 137 | 138 | void targetWarn(String val) { 139 | LogLog.warn("[" + val + "] should be System.out or System.err."); 140 | LogLog.warn("Using previously set target, System.out by default."); 141 | } 142 | 143 | /** 144 | * Prepares the appender for use. 145 | */ 146 | public void activateOptions() { 147 | if (follow) { 148 | if (target.equals(SYSTEM_ERR)) { 149 | setWriter(createWriter(new SystemErrStream())); 150 | } else { 151 | setWriter(createWriter(new SystemOutStream())); 152 | } 153 | } else { 154 | if (target.equals(SYSTEM_ERR)) { 155 | setWriter(createWriter(System.err)); 156 | } else { 157 | setWriter(createWriter(System.out)); 158 | } 159 | } 160 | 161 | super.activateOptions(); 162 | } 163 | 164 | /** 165 | * {@inheritDoc} 166 | */ 167 | protected final void closeWriter() { 168 | if (follow) { 169 | super.closeWriter(); 170 | } 171 | } 172 | 173 | /** 174 | * An implementation of OutputStream that redirects to the current 175 | * System.err. 176 | */ 177 | private static class SystemErrStream extends OutputStream { 178 | public SystemErrStream() { 179 | } 180 | 181 | public void close() { 182 | } 183 | 184 | public void flush() { 185 | System.err.flush(); 186 | } 187 | 188 | public void write(final byte[] b) throws IOException { 189 | if (!Loggers.consoleLoggingEnabled()) { 190 | return; 191 | } 192 | System.err.write(b); 193 | } 194 | 195 | public void write(final byte[] b, final int off, final int len) 196 | throws IOException { 197 | if (!Loggers.consoleLoggingEnabled()) { 198 | return; 199 | } 200 | System.err.write(b, off, len); 201 | } 202 | 203 | public void write(final int b) throws IOException { 204 | if (!Loggers.consoleLoggingEnabled()) { 205 | return; 206 | } 207 | System.err.write(b); 208 | } 209 | } 210 | 211 | /** 212 | * An implementation of OutputStream that redirects to the current 213 | * System.out. 214 | */ 215 | private static class SystemOutStream extends OutputStream { 216 | public SystemOutStream() { 217 | } 218 | 219 | public void close() { 220 | } 221 | 222 | public void flush() { 223 | System.out.flush(); 224 | } 225 | 226 | public void write(final byte[] b) throws IOException { 227 | if (!Loggers.consoleLoggingEnabled()) { 228 | return; 229 | } 230 | System.out.write(b); 231 | } 232 | 233 | public void write(final byte[] b, final int off, final int len) 234 | throws IOException { 235 | if (!Loggers.consoleLoggingEnabled()) { 236 | return; 237 | } 238 | System.out.write(b, off, len); 239 | } 240 | 241 | public void write(final int b) throws IOException { 242 | if (!Loggers.consoleLoggingEnabled()) { 243 | return; 244 | } 245 | System.out.write(b); 246 | } 247 | } 248 | 249 | } 250 | -------------------------------------------------------------------------------- /src/org/langke/common/cache/MemcachedUtil.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.cache; 2 | 3 | import java.util.Calendar; 4 | import java.util.Collection; 5 | import java.util.Date; 6 | import java.util.HashMap; 7 | import java.util.Iterator; 8 | import java.util.LinkedList; 9 | import java.util.List; 10 | import java.util.Map; 11 | import java.util.concurrent.atomic.AtomicInteger; 12 | 13 | import org.langke.common.Config; 14 | 15 | import com.danga.MemCached.MemCachedClient; 16 | import com.danga.MemCached.SockIOPool; 17 | 18 | public class MemcachedUtil { 19 | public static String MEMCACHED_PRE = Config.get().get("memcachedPre","api_");//cache key pre 20 | public static int MEMCACHED_EXPIRY_TIME = Config.get().getInt("memcachedExpiryTime",600000);//默认缓存过期时间,600s 21 | private static String ttcache_server = Config.get().get("tt.cache.server"); 22 | private static MemCachedClient memcachedClient; 23 | private static int initConn = 10; 24 | private static int minConn = 10; 25 | private static int maxConn = 200; 26 | protected static MemcachedUtil cache = new MemcachedUtil(); 27 | private final static String poolName = "memcached_pool";//poolName需要一至,否则会报attempting to get SockIO from uninitialized pool! 28 | /** 29 | * 保护型构造方法,不允许实例化! 30 | * */ 31 | protected MemcachedUtil() { 32 | 33 | } 34 | /** 35 | * 获取唯一实例 36 | * @return 37 | */ 38 | public static MemcachedUtil getInstance(){ 39 | return cache; 40 | } 41 | static{ 42 | if(memcachedClient == null) 43 | init(); 44 | } 45 | private static synchronized void init(){ 46 | try { 47 | if(!Config.get().getBoolean("isUsedMemcached", false)) 48 | return; 49 | if(ttcache_server == null){ 50 | throw new Exception("tt.cache.server is not in config"); 51 | } 52 | } catch (Exception e) { 53 | e.printStackTrace(); 54 | return; 55 | } 56 | String[] servers = ttcache_server.replaceAll(",", " ").split("\\s+"); 57 | SockIOPool pool = SockIOPool.getInstance(poolName); 58 | pool.setServers(servers); 59 | pool.setInitConn(initConn); 60 | pool.setMinConn(minConn); 61 | pool.setMaxConn(maxConn); 62 | pool.setHashingAlg(SockIOPool.CONSISTENT_HASH); 63 | pool.setMaintSleep(30 * 1000); 64 | // 设置TCP的参数,连接超时等 65 | pool.setNagle(false); 66 | pool.setSocketTO(3000); 67 | pool.setSocketConnectTO(0); 68 | pool.setAliveCheck(true); 69 | pool.initialize(); 70 | memcachedClient = new MemCachedClient(poolName); 71 | memcachedClient.setCompressEnable(true); 72 | memcachedClient.setCompressThreshold(64 * 1024); 73 | } 74 | 75 | public Object get(String key) { 76 | return getInstance().memcachedClient.get(key, key.hashCode(), true); 77 | } 78 | 79 | public Map gets(Collection keys) { 80 | if(keys == null || keys.size() == 0){ 81 | return null; 82 | } 83 | String[] param1 = new String[keys.size()]; 84 | Integer[] param2 =new Integer[keys.size()]; 85 | Iterator iterator = keys.iterator(); 86 | Object obj = null; 87 | int i = 0; 88 | while(iterator.hasNext()){ 89 | obj = iterator.next(); 90 | param1[i] = (String)obj; 91 | param2[i] = param1[i].hashCode(); 92 | i++; 93 | } 94 | return getInstance().memcachedClient.getMulti(param1, param2, true); 95 | } 96 | 97 | public boolean set(String key, Object obj) { 98 | return getInstance().memcachedClient.set(key, obj); 99 | } 100 | 101 | public boolean set(String key, Object obj,int expiry) { 102 | return getInstance().memcachedClient.set(key, obj, new Date(expiry)); 103 | } 104 | 105 | public boolean setDefault(String key, Object obj,int expiry) { 106 | return getInstance().memcachedClient.set(key, obj, new Date(MEMCACHED_EXPIRY_TIME)); 107 | } 108 | 109 | public boolean add(String key, Object value) { 110 | return getInstance().memcachedClient.add(key, value); 111 | } 112 | 113 | public boolean add(String key, Object value, int expiry) { 114 | return getInstance().memcachedClient.add(key, value, new Date(expiry)); 115 | } 116 | 117 | public boolean addDefault(String key, Object value) { 118 | return getInstance().memcachedClient.add(key, value, new Date(MEMCACHED_EXPIRY_TIME)); 119 | } 120 | 121 | public boolean replace(String key, Object value) { 122 | return getInstance().memcachedClient.replace(key, value); 123 | } 124 | 125 | public boolean replace(String key, Object value, int expiry) { 126 | return getInstance().memcachedClient.replace(key, value, new Date(expiry)); 127 | } 128 | 129 | public boolean replaceDefault(String key, Object value) { 130 | return getInstance().memcachedClient.replace(key, value, new Date(MEMCACHED_EXPIRY_TIME)); 131 | } 132 | 133 | public boolean delete(String key){ 134 | return getInstance().memcachedClient.delete(key); 135 | } 136 | 137 | public boolean flush() { 138 | return getInstance().memcachedClient.flushAll(); 139 | } 140 | 141 | public boolean shutdown() { 142 | try{ 143 | SockIOPool pool = SockIOPool.getInstance(poolName); 144 | if(pool != null){ 145 | pool.shutDown(); 146 | } 147 | return true; 148 | }catch(Exception e){ 149 | e.printStackTrace(); 150 | return false; 151 | } 152 | } 153 | 154 | public static void main(String[] args) throws InterruptedException{ 155 | final MemcachedUtil cache = MemcachedUtil.getInstance(); 156 | final String key = MEMCACHED_PRE+"FF121"; 157 | final AtomicInteger count = new AtomicInteger(); 158 | final Object lock = new Object(); 159 | //cache.delete(key); 160 | final int concurrent; 161 | final int run ; 162 | if(args.length==2){ 163 | concurrent = Integer.valueOf(args[0]); 164 | run = Integer.valueOf(args[1]); 165 | }else{ 166 | concurrent = 100; 167 | run = 1000; 168 | } 169 | for(int i=0;i> countList = new LinkedList>(); 191 | Map countMap ; 192 | while(total < run * concurrent ) { 193 | try { 194 | sleep(1000); 195 | } catch (InterruptedException e) { 196 | e.printStackTrace(); 197 | } 198 | synchronized(lock) { 199 | System.out.println(Calendar.getInstance().getTime()+" count:"+count); 200 | countMap = new HashMap(); 201 | countMap.put(Calendar.getInstance().getTime(),count.get()); 202 | countList.add(countMap); 203 | total += count.get(); 204 | count.set(0); 205 | } 206 | 207 | } 208 | cache.shutdown(); 209 | for(Map map:countList){ 210 | System.out.println(map); 211 | } 212 | } 213 | }.start(); 214 | //Thread.sleep(7000); 215 | //System.out.println(" count:"+count); 216 | } 217 | 218 | } 219 | -------------------------------------------------------------------------------- /src/org/langke/common/Strings.java: -------------------------------------------------------------------------------- 1 | package org.langke.common; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.File; 6 | import java.io.IOException; 7 | import java.io.PrintWriter; 8 | 9 | /* 10 | * @copyright (c) langke 2011 11 | * @author langke 2011-5-1 12 | */ 13 | public class Strings { 14 | 15 | public static int[] toIntArray(String[] array){ 16 | int[] arrayInt = new int[array.length]; 17 | for(int i=0;i 1024) { 73 | sb.append(buffer, 0, bufferIndex); 74 | bufferIndex = 0; 75 | } 76 | b = c; 77 | c = chars[i]; 78 | switch (c) { 79 | case '\\': 80 | case '"': 81 | buffer[bufferIndex++] = '\\'; 82 | buffer[bufferIndex++] = c; 83 | break; 84 | case '/': 85 | if (b == '<') { 86 | buffer[bufferIndex++] = '\\'; 87 | } 88 | buffer[bufferIndex++] = c; 89 | break; 90 | default: 91 | if (c < ' ') { 92 | switch (c) { 93 | case '\b': 94 | buffer[bufferIndex++] = '\\'; 95 | buffer[bufferIndex++] = 'b'; 96 | break; 97 | case '\t': 98 | buffer[bufferIndex++] = '\\'; 99 | buffer[bufferIndex++] = 't'; 100 | break; 101 | case '\n': 102 | buffer[bufferIndex++] = '\\'; 103 | buffer[bufferIndex++] = 'n'; 104 | break; 105 | case '\f': 106 | buffer[bufferIndex++] = '\\'; 107 | buffer[bufferIndex++] = 'f'; 108 | break; 109 | case '\r': 110 | buffer[bufferIndex++] = '\\'; 111 | buffer[bufferIndex++] = 'r'; 112 | break; 113 | default: 114 | t = "000" + Integer.toHexString(c); 115 | int tLength = t.length(); 116 | buffer[bufferIndex++] = '\\'; 117 | buffer[bufferIndex++] = 'u'; 118 | buffer[bufferIndex++] = t.charAt(tLength - 4); 119 | buffer[bufferIndex++] = t.charAt(tLength - 3); 120 | buffer[bufferIndex++] = t.charAt(tLength - 2); 121 | buffer[bufferIndex++] = t.charAt(tLength - 1); 122 | } 123 | } else { 124 | buffer[bufferIndex++] = c; 125 | } 126 | } 127 | } 128 | sb.append(buffer, 0, bufferIndex); 129 | sb.append('"'); 130 | return sb.toString(); 131 | } 132 | 133 | public static StringBuilder quoteJson(StringBuilder sb, String s){ 134 | return sb.append(quote(s)); 135 | } 136 | 137 | public static final void trimEndComma(StringBuilder sb) { 138 | int l = sb.length(); 139 | if (sb.charAt(l - 1) == ',') { 140 | sb.setLength(l - 1); 141 | } 142 | } 143 | public static final void trimEnd(StringBuilder sb) { 144 | int l = sb.length(); 145 | sb.setLength(l - 1); 146 | } 147 | public static String arrayToString(String[] values) { 148 | StringBuffer sb = new StringBuffer(); 149 | for(int i = 0; i < values.length; i++){ 150 | sb.append(values[i]); 151 | if(i != values.length-1){ 152 | sb.append(","); 153 | } 154 | } 155 | return sb.toString(); 156 | } 157 | public static final void arrayToString(StringBuilder sb, String name, Object[] os) { 158 | sb.append(name).append(":"); 159 | if (os == null) { 160 | sb.append(" null \n"); 161 | return; 162 | } 163 | sb.append("["); 164 | for (int i=0;i') 205 | return ">"; 206 | else if (i == '"') 207 | return """; 208 | else 209 | return "" + (char) i; 210 | } 211 | 212 | public final static void exec(String command, String dir, StringBuilder ret) { 213 | final String[] COMMAND_INTERPRETER = { "/bin/sh", "-c" }; 214 | final long MAX_PROCESS_RUNNING_TIME = 30 * 1000; // 30 seconds 215 | 216 | String[] comm = new String[3]; 217 | comm[0] = COMMAND_INTERPRETER[0]; 218 | comm[1] = COMMAND_INTERPRETER[1]; 219 | comm[2] = command; 220 | long start = System.currentTimeMillis(); 221 | try { 222 | // Start process 223 | Process ls_proc = Runtime.getRuntime().exec(comm, null, 224 | new File(dir)); 225 | // Get input and error streams 226 | BufferedInputStream ls_in = new BufferedInputStream(ls_proc 227 | .getInputStream()); 228 | BufferedInputStream ls_err = new BufferedInputStream(ls_proc 229 | .getErrorStream()); 230 | boolean end = false; 231 | while (!end) { 232 | int c = 0; 233 | while ((ls_err.available() > 0) && (++c <= 1000)) { 234 | ret.append(conv2Html(ls_err.read())); 235 | } 236 | c = 0; 237 | while ((ls_in.available() > 0) && (++c <= 1000)) { 238 | ret.append(conv2Html(ls_in.read())); 239 | } 240 | try { 241 | ls_proc.exitValue(); 242 | // if the process has not finished, an exception is thrown 243 | // else 244 | while (ls_err.available() > 0) 245 | ret.append(conv2Html(ls_err.read())); 246 | while (ls_in.available() > 0) 247 | ret.append(conv2Html(ls_in.read())); 248 | end = true; 249 | } catch (IllegalThreadStateException ex) { 250 | // Process is running 251 | } 252 | // The process is not allowed to run longer than given time. 253 | if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) { 254 | ls_proc.destroy(); 255 | end = true; 256 | ret.append("!!!! Process has timed out, destroyed !!!!!"); 257 | } 258 | try { 259 | Thread.sleep(50); 260 | } catch (InterruptedException ie) { 261 | } 262 | } 263 | } catch (IOException e) { 264 | ret.append("Error: " + e); 265 | } 266 | 267 | } 268 | 269 | public static void main(String[] args) { 270 | String json = "{\"title\":\"hello,\"jim\",haha\"}"; 271 | System.out.println(json); 272 | System.out.println(quote(json)); 273 | } 274 | 275 | } 276 | -------------------------------------------------------------------------------- /src/org/langke/util/logging/support/LoggerMessageFormat.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to Elastic Search and Shay Banon under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. Elastic Search licenses this 6 | * file to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | 20 | package org.langke.util.logging.support; 21 | 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | 25 | /** 26 | * @author kimchy (shay.banon) 27 | */ 28 | @SuppressWarnings("rawtypes") 29 | public class LoggerMessageFormat { 30 | 31 | static final char DELIM_START = '{'; 32 | static final char DELIM_STOP = '}'; 33 | static final String DELIM_STR = "{}"; 34 | private static final char ESCAPE_CHAR = '\\'; 35 | 36 | public static String format(final String messagePattern, 37 | final Object... argArray) { 38 | return format(null, messagePattern, argArray); 39 | } 40 | 41 | public static String format(final String prefix, 42 | final String messagePattern, final Object... argArray) { 43 | if (messagePattern == null) { 44 | return null; 45 | } 46 | if (argArray == null) { 47 | if (prefix == null) { 48 | return messagePattern; 49 | } else { 50 | return prefix + messagePattern; 51 | } 52 | } 53 | int i = 0; 54 | int j; 55 | StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50); 56 | if (prefix != null) { 57 | sbuf.append(prefix); 58 | } 59 | 60 | for (int L = 0; L < argArray.length; L++) { 61 | 62 | j = messagePattern.indexOf(DELIM_STR, i); 63 | 64 | if (j == -1) { 65 | // no more variables 66 | if (i == 0) { // this is a simple string 67 | return messagePattern; 68 | } else { // add the tail string which contains no variables and 69 | // return 70 | // the result. 71 | sbuf.append(messagePattern.substring(i, 72 | messagePattern.length())); 73 | return sbuf.toString(); 74 | } 75 | } else { 76 | if (isEscapedDelimeter(messagePattern, j)) { 77 | if (!isDoubleEscaped(messagePattern, j)) { 78 | L--; // DELIM_START was escaped, thus should not be 79 | // incremented 80 | sbuf.append(messagePattern.substring(i, j - 1)); 81 | sbuf.append(DELIM_START); 82 | i = j + 1; 83 | } else { 84 | // The escape character preceding the delimiter start is 85 | // itself escaped: "abc x:\\{}" 86 | // we have to consume one backward slash 87 | sbuf.append(messagePattern.substring(i, j - 1)); 88 | deeplyAppendParameter(sbuf, argArray[L], new HashMap()); 89 | i = j + 2; 90 | } 91 | } else { 92 | // normal case 93 | sbuf.append(messagePattern.substring(i, j)); 94 | deeplyAppendParameter(sbuf, argArray[L], new HashMap()); 95 | i = j + 2; 96 | } 97 | } 98 | } 99 | // append the characters following the last {} pair. 100 | sbuf.append(messagePattern.substring(i, messagePattern.length())); 101 | return sbuf.toString(); 102 | } 103 | 104 | static boolean isEscapedDelimeter(String messagePattern, 105 | int delimeterStartIndex) { 106 | 107 | if (delimeterStartIndex == 0) { 108 | return false; 109 | } 110 | char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1); 111 | if (potentialEscape == ESCAPE_CHAR) { 112 | return true; 113 | } else { 114 | return false; 115 | } 116 | } 117 | 118 | static boolean isDoubleEscaped(String messagePattern, 119 | int delimeterStartIndex) { 120 | if (delimeterStartIndex >= 2 121 | && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR) { 122 | return true; 123 | } else { 124 | return false; 125 | } 126 | } 127 | 128 | private static void deeplyAppendParameter(StringBuffer sbuf, Object o, 129 | Map seenMap) { 130 | if (o == null) { 131 | sbuf.append("null"); 132 | return; 133 | } 134 | if (!o.getClass().isArray()) { 135 | safeObjectAppend(sbuf, o); 136 | } else { 137 | // check for primitive array types because they 138 | // unfortunately cannot be cast to Object[] 139 | if (o instanceof boolean[]) { 140 | booleanArrayAppend(sbuf, (boolean[]) o); 141 | } else if (o instanceof byte[]) { 142 | byteArrayAppend(sbuf, (byte[]) o); 143 | } else if (o instanceof char[]) { 144 | charArrayAppend(sbuf, (char[]) o); 145 | } else if (o instanceof short[]) { 146 | shortArrayAppend(sbuf, (short[]) o); 147 | } else if (o instanceof int[]) { 148 | intArrayAppend(sbuf, (int[]) o); 149 | } else if (o instanceof long[]) { 150 | longArrayAppend(sbuf, (long[]) o); 151 | } else if (o instanceof float[]) { 152 | floatArrayAppend(sbuf, (float[]) o); 153 | } else if (o instanceof double[]) { 154 | doubleArrayAppend(sbuf, (double[]) o); 155 | } else { 156 | objectArrayAppend(sbuf, (Object[]) o, seenMap); 157 | } 158 | } 159 | } 160 | 161 | private static void safeObjectAppend(StringBuffer sbuf, Object o) { 162 | try { 163 | String oAsString = o.toString(); 164 | sbuf.append(oAsString); 165 | } catch (Throwable t) { 166 | System.err 167 | .println("Logger: Failed toString() invocation on an object of type [" 168 | + o.getClass().getName() + "]"); 169 | t.printStackTrace(); 170 | sbuf.append("[FAILED toString()]"); 171 | } 172 | 173 | } 174 | 175 | @SuppressWarnings("unchecked") 176 | private static void objectArrayAppend(StringBuffer sbuf, Object[] a, 177 | Map seenMap) { 178 | sbuf.append('['); 179 | if (!seenMap.containsKey(a)) { 180 | seenMap.put(a, null); 181 | final int len = a.length; 182 | for (int i = 0; i < len; i++) { 183 | deeplyAppendParameter(sbuf, a[i], seenMap); 184 | if (i != len - 1) 185 | sbuf.append(", "); 186 | } 187 | // allow repeats in siblings 188 | seenMap.remove(a); 189 | } else { 190 | sbuf.append("..."); 191 | } 192 | sbuf.append(']'); 193 | } 194 | 195 | private static void booleanArrayAppend(StringBuffer sbuf, boolean[] a) { 196 | sbuf.append('['); 197 | final int len = a.length; 198 | for (int i = 0; i < len; i++) { 199 | sbuf.append(a[i]); 200 | if (i != len - 1) 201 | sbuf.append(", "); 202 | } 203 | sbuf.append(']'); 204 | } 205 | 206 | private static void byteArrayAppend(StringBuffer sbuf, byte[] a) { 207 | sbuf.append('['); 208 | final int len = a.length; 209 | for (int i = 0; i < len; i++) { 210 | sbuf.append(a[i]); 211 | if (i != len - 1) 212 | sbuf.append(", "); 213 | } 214 | sbuf.append(']'); 215 | } 216 | 217 | private static void charArrayAppend(StringBuffer sbuf, char[] a) { 218 | sbuf.append('['); 219 | final int len = a.length; 220 | for (int i = 0; i < len; i++) { 221 | sbuf.append(a[i]); 222 | if (i != len - 1) 223 | sbuf.append(", "); 224 | } 225 | sbuf.append(']'); 226 | } 227 | 228 | private static void shortArrayAppend(StringBuffer sbuf, short[] a) { 229 | sbuf.append('['); 230 | final int len = a.length; 231 | for (int i = 0; i < len; i++) { 232 | sbuf.append(a[i]); 233 | if (i != len - 1) 234 | sbuf.append(", "); 235 | } 236 | sbuf.append(']'); 237 | } 238 | 239 | private static void intArrayAppend(StringBuffer sbuf, int[] a) { 240 | sbuf.append('['); 241 | final int len = a.length; 242 | for (int i = 0; i < len; i++) { 243 | sbuf.append(a[i]); 244 | if (i != len - 1) 245 | sbuf.append(", "); 246 | } 247 | sbuf.append(']'); 248 | } 249 | 250 | private static void longArrayAppend(StringBuffer sbuf, long[] a) { 251 | sbuf.append('['); 252 | final int len = a.length; 253 | for (int i = 0; i < len; i++) { 254 | sbuf.append(a[i]); 255 | if (i != len - 1) 256 | sbuf.append(", "); 257 | } 258 | sbuf.append(']'); 259 | } 260 | 261 | private static void floatArrayAppend(StringBuffer sbuf, float[] a) { 262 | sbuf.append('['); 263 | final int len = a.length; 264 | for (int i = 0; i < len; i++) { 265 | sbuf.append(a[i]); 266 | if (i != len - 1) 267 | sbuf.append(", "); 268 | } 269 | sbuf.append(']'); 270 | } 271 | 272 | private static void doubleArrayAppend(StringBuffer sbuf, double[] a) { 273 | sbuf.append('['); 274 | final int len = a.length; 275 | for (int i = 0; i < len; i++) { 276 | sbuf.append(a[i]); 277 | if (i != len - 1) 278 | sbuf.append(", "); 279 | } 280 | sbuf.append(']'); 281 | } 282 | } 283 | -------------------------------------------------------------------------------- /src/org/langke/common/server/NetworkUtils.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.server; 2 | 3 | import java.net.Inet4Address; 4 | import java.net.Inet6Address; 5 | import java.net.InetAddress; 6 | import java.net.NetworkInterface; 7 | import java.net.Socket; 8 | import java.net.SocketException; 9 | import java.net.UnknownHostException; 10 | import java.util.ArrayList; 11 | import java.util.Collection; 12 | import java.util.Enumeration; 13 | import java.util.HashSet; 14 | import java.util.List; 15 | import java.util.Set; 16 | 17 | import org.langke.util.logging.ESLogger; 18 | import org.langke.util.logging.Loggers; 19 | 20 | 21 | /* 22 | * @copyright (c) langke 2011 23 | * @author langke 2011-5-1 24 | */ 25 | 26 | public class NetworkUtils { 27 | 28 | private final static ESLogger logger = Loggers.getLogger(NetworkUtils.class); 29 | 30 | public static enum StackType { 31 | IPv4, IPv6, Unknown; 32 | } 33 | 34 | public static final String IPv4_SETTING = "java.net.preferIPv4Stack"; 35 | public static final String IPv6_SETTING = "java.net.preferIPv6Addresses"; 36 | 37 | public static final String NON_LOOPBACK_ADDRESS = "non_loopback_address"; 38 | 39 | private final static InetAddress localAddress; 40 | 41 | static { 42 | InetAddress localAddressX = null; 43 | try { 44 | localAddressX = InetAddress.getLocalHost(); 45 | } catch (UnknownHostException e) { 46 | logger.warn("Failed to find local host", e); 47 | } 48 | localAddress = localAddressX; 49 | } 50 | 51 | public static Boolean defaultReuseAddress() { 52 | return true; 53 | // return OsUtils.WINDOWS ? null : true; 54 | } 55 | 56 | public static boolean isIPv4() { 57 | return System.getProperty("java.net.preferIPv4Stack") != null 58 | && System.getProperty("java.net.preferIPv4Stack") 59 | .equals("true"); 60 | } 61 | 62 | public static InetAddress getIPv4Localhost() throws UnknownHostException { 63 | return getLocalhost(StackType.IPv4); 64 | } 65 | 66 | public static InetAddress getIPv6Localhost() throws UnknownHostException { 67 | return getLocalhost(StackType.IPv6); 68 | } 69 | 70 | public static InetAddress getLocalAddress() { 71 | return localAddress; 72 | } 73 | 74 | public static InetAddress getLocalhost(StackType ip_version) 75 | throws UnknownHostException { 76 | if (ip_version == StackType.IPv4) 77 | return InetAddress.getByName("127.0.0.1"); 78 | else 79 | return InetAddress.getByName("::1"); 80 | } 81 | 82 | public static boolean canBindToMcastAddress() { 83 | return true; 84 | // return OsUtils.LINUX || OsUtils.SOLARIS || OsUtils.HP; 85 | } 86 | 87 | /** 88 | * Returns the first non-loopback address on any interface on the current 89 | * host. 90 | * 91 | * @param ip_version 92 | * Constraint on IP version of address to be returned, 4 or 6 93 | */ 94 | public static InetAddress getFirstNonLoopbackAddress(StackType ip_version) 95 | throws SocketException { 96 | try { 97 | return InetAddress.getLocalHost(); 98 | } catch (UnknownHostException e) { 99 | throw new RuntimeException(e); 100 | } 101 | } 102 | 103 | /** 104 | * Returns the first non-loopback address on the given interface on the 105 | * current host. 106 | * 107 | * @param intf 108 | * the interface to be checked 109 | * @param ipVersion 110 | * Constraint on IP version of address to be returned, 4 or 6 111 | */ 112 | public static InetAddress getFirstNonLoopbackAddress(NetworkInterface intf, 113 | StackType ipVersion) throws SocketException { 114 | if (intf == null) 115 | throw new IllegalArgumentException( 116 | "Network interface pointer is null"); 117 | 118 | for (Enumeration addresses = intf.getInetAddresses(); addresses.hasMoreElements();) { 119 | InetAddress address = (InetAddress) addresses.nextElement(); 120 | if (!address.isLoopbackAddress()) { 121 | if ((address instanceof Inet4Address && ipVersion == StackType.IPv4) 122 | || (address instanceof Inet6Address && ipVersion == StackType.IPv6)) 123 | return address; 124 | } 125 | } 126 | return null; 127 | } 128 | 129 | /** 130 | * A function to check if an interface supports an IP version (i.e has 131 | * addresses defined for that IP version). 132 | * 133 | * @param intf 134 | * @return 135 | */ 136 | public static boolean interfaceHasIPAddresses(NetworkInterface intf, 137 | StackType ipVersion) throws SocketException, UnknownHostException { 138 | boolean supportsVersion = false; 139 | if (intf != null) { 140 | // get all the InetAddresses defined on the interface 141 | Enumeration addresses = intf.getInetAddresses(); 142 | while (addresses != null && addresses.hasMoreElements()) { 143 | // get the next InetAddress for the current interface 144 | InetAddress address = (InetAddress) addresses.nextElement(); 145 | 146 | // check if we find an address of correct version 147 | if ((address instanceof Inet4Address && (ipVersion == StackType.IPv4)) 148 | || (address instanceof Inet6Address && (ipVersion == StackType.IPv6))) { 149 | supportsVersion = true; 150 | break; 151 | } 152 | } 153 | } else { 154 | throw new UnknownHostException("network interface " + intf 155 | + " not found"); 156 | } 157 | return supportsVersion; 158 | } 159 | 160 | /** 161 | * Tries to determine the type of IP stack from the available interfaces and 162 | * their addresses and from the system properties (java.net.preferIPv4Stack 163 | * and java.net.preferIPv6Addresses) 164 | * 165 | * @return StackType.IPv4 for an IPv4 only stack, StackYTypeIPv6 for an IPv6 166 | * only stack, and StackType.Unknown if the type cannot be detected 167 | */ 168 | public static StackType getIpStackType() { 169 | boolean isIPv4StackAvailable = isStackAvailable(true); 170 | boolean isIPv6StackAvailable = isStackAvailable(false); 171 | 172 | // if only IPv4 stack available 173 | if (isIPv4StackAvailable && !isIPv6StackAvailable) { 174 | return StackType.IPv4; 175 | } 176 | // if only IPv6 stack available 177 | else if (isIPv6StackAvailable && !isIPv4StackAvailable) { 178 | return StackType.IPv6; 179 | } 180 | // if dual stack 181 | else if (isIPv4StackAvailable && isIPv6StackAvailable) { 182 | // get the System property which records user preference for a stack 183 | // on a dual stack machine 184 | if (Boolean.getBoolean(IPv4_SETTING)) // has preference over 185 | // java.net.preferIPv6Addresses 186 | return StackType.IPv4; 187 | if (Boolean.getBoolean(IPv6_SETTING)) 188 | return StackType.IPv6; 189 | return StackType.IPv6; 190 | } 191 | return StackType.Unknown; 192 | } 193 | 194 | public static boolean isStackAvailable(boolean ipv4) { 195 | Collection allAddrs = getAllAvailableAddresses(); 196 | for (InetAddress addr : allAddrs) 197 | if (ipv4 && addr instanceof Inet4Address 198 | || (!ipv4 && addr instanceof Inet6Address)) 199 | return true; 200 | return false; 201 | } 202 | 203 | public static List getAllAvailableInterfaces() 204 | throws SocketException { 205 | List allInterfaces = new ArrayList( 206 | 10); 207 | NetworkInterface intf; 208 | for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en 209 | .hasMoreElements();) { 210 | intf = (NetworkInterface) en.nextElement(); 211 | allInterfaces.add(intf); 212 | } 213 | return allInterfaces; 214 | } 215 | 216 | public static Collection getAllAvailableAddresses() { 217 | Set retval = new HashSet(); 218 | Enumeration en; 219 | try { 220 | en = NetworkInterface.getNetworkInterfaces(); 221 | if (en == null) 222 | return retval; 223 | while (en.hasMoreElements()) { 224 | NetworkInterface intf = (NetworkInterface) en.nextElement(); 225 | Enumeration addrs = intf.getInetAddresses(); 226 | while (addrs.hasMoreElements()) 227 | retval.add(addrs.nextElement()); 228 | } 229 | } catch (SocketException e) { 230 | logger.warn("Failed to derive all available interfaces", e); 231 | } 232 | 233 | return retval; 234 | } 235 | 236 | static public int getNextAliablePort(String address, int startport) 237 | throws UnknownHostException { 238 | InetAddress a = InetAddress.getByName(address); 239 | return getNextAliablePort(a, startport); 240 | } 241 | 242 | static public int getNextAliablePort(InetAddress address, int startport) { 243 | int port = startport; 244 | while (port < 65535) { 245 | try { 246 | Socket socket = new Socket(address, port); 247 | socket.close(); 248 | 249 | port++; 250 | } catch (Exception ex) { 251 | return port; 252 | } 253 | } 254 | return -1; 255 | } 256 | 257 | private NetworkUtils() { 258 | 259 | } 260 | 261 | public static void main(String[] ss) { 262 | try { 263 | System.out.println(getNextAliablePort("10.10.10.201", 10000)); 264 | } catch (Exception e) { 265 | e.printStackTrace(); 266 | } 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /src/org/langke/common/cache/CacheManager.java: -------------------------------------------------------------------------------- 1 | package org.langke.common.cache; 2 | 3 | import java.io.Serializable; 4 | import java.lang.reflect.Method; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.concurrent.Callable; 9 | 10 | import org.apache.commons.lang.ArrayUtils; 11 | import org.apache.commons.lang.ClassUtils; 12 | import org.apache.commons.lang.StringUtils; 13 | import org.aspectj.lang.ProceedingJoinPoint; 14 | import org.aspectj.lang.annotation.Around; 15 | import org.aspectj.lang.annotation.Aspect; 16 | import org.aspectj.lang.annotation.Pointcut; 17 | import org.langke.common.Config; 18 | import org.langke.common.CostTime; 19 | import org.langke.common.ExecutorFactory; 20 | import org.langke.util.logging.ESLogger; 21 | import org.langke.util.logging.Loggers; 22 | import org.springframework.stereotype.Component; 23 | 24 | import com.alibaba.fastjson.JSONObject; 25 | import com.alibaba.fastjson.serializer.SerializerFeature; 26 | 27 | /** 28 | * 29 | * @author langke 30 | * @created 2012-8-28 31 | * 如果参数是Map 取Map中的memKey作为key ,如果Map中没有memKey则取id作为key 32 | * 如果参数是基础类型java.lang.* 、数组、原始类型或基础类型: 所有参数相加作为key 33 | * 如果参数是实体类,取实体类中的PK,如果没有取实体类中id作为key 34 | * 缓存默认10分钟刷新,可以config.properties 设置 memcachedExpiryTime 35 | * 36 | * 在需要缓存的方法加注解:@MemCaching 37 | * 在需要清除缓存的方法加注解:@MemFlush 38 | * 39 | * 配置文件加: 40 | isUsedMemcached=true 41 | tt.cache.server = newmall.mem.tg.local:11211 42 | memcachedPre = api_review_ 43 | #memcached expiry time ms 44 | memcachedExpiryTime=600000 45 | 46 | * @version 0.1 入缓存走异步 47 | * @lastmodify 2012-09-28 48 | */ 49 | 50 | @Aspect 51 | @Component 52 | public class CacheManager { 53 | private static ESLogger log = Loggers.getLogger(CacheManager.class); 54 | 55 | MemcachedUtil memcachedClient = MemcachedUtil.getInstance(); 56 | @SuppressWarnings("unused") 57 | @Pointcut("@annotation (com.qjmall.common.cache.MemCaching) || @annotation (com.qjmall.common.cache.MemFlush)") 58 | private void anyMethod() {} 59 | 60 | @Around(value="anyMethod()") 61 | public Object doAccessCheck(ProceedingJoinPoint pjp) throws Throwable{ 62 | Object target=pjp.getTarget(); 63 | String methodName=pjp.getSignature().getName(); 64 | Object[] args=pjp.getArgs(); 65 | Method method=getMethod(target,methodName,args); 66 | if(method == null){//找不到方法 67 | log.warn("mot match method:{} {}", methodName,args); 68 | return pjp.proceed(args); 69 | } 70 | String memKey = null; 71 | boolean needCache=method.isAnnotationPresent(MemCaching.class);//有加些注解的加缓存 72 | boolean flushCache=method.isAnnotationPresent(MemFlush.class); //刷新缓存 73 | boolean isUsedMemcached = Config.get().getBoolean("isUsedMemcached", true);//是否启用缓存 74 | if((!needCache && !flushCache) ||!isUsedMemcached){//不需要走缓存 75 | return pjp.proceed(args); 76 | } 77 | CostTime cost = new CostTime(); 78 | cost.start(); 79 | for (Object obj :args){ 80 | if(obj instanceof Map){//如果参数是Map,取Map中的id作为key 81 | if(((Map)obj).containsKey("memKey")){//取Map中的memKey作为key 82 | memKey = (String) ((Map)obj).get("memKey"); 83 | } 84 | if(memKey == null && ((Map)obj).containsKey("id")){//如果没有设置,取Map中的id作为key 85 | memKey = (String) ((Map)obj).get("id"); 86 | } 87 | break; 88 | } 89 | } 90 | if(memKey==null){//参数不是map 91 | Class entryclass = null;//=args[0].getClass(); 92 | for(Object arg:args){ 93 | if(arg == null) 94 | continue; 95 | entryclass = arg.getClass();//找到一个非空的参数 96 | break; 97 | } 98 | if(entryclass!=null){ 99 | if(entryclass.isArray() || entryclass.isPrimitive() || entryclass.toString().indexOf("java.lang") > 0 || ClassUtils.isAssignable(entryclass, Map.class)){//数组、原始类型或基础类型 100 | memKey = ""; 101 | for(Object obj : args){ 102 | if(obj == null) 103 | continue; 104 | else if(obj.getClass().isArray()) 105 | obj = ArrayUtils.toString(obj); 106 | memKey += String.valueOf(obj);//所有参数相加做为memKey 107 | } 108 | }else if(entryclass.toString().indexOf("java.util") > 0){ 109 | log.warn("{}不支持java.util类型除Map以外的参数",methodName); 110 | }else{//实体类 111 | //如果参数是实体类,取实体类中的PK 112 | if(entryclass instanceof Serializable){ 113 | //取实体类中带PK注解的属性作为memkey 114 | Method[] Entrymethods = entryclass.getDeclaredMethods(); 115 | for(Method mhd : Entrymethods){ 116 | if(mhd.isAnnotationPresent(PK.class)){ 117 | memKey = (String) mhd.invoke(args[0]); 118 | break; 119 | } 120 | } 121 | if(memKey == null){ 122 | try{ 123 | Method m = entryclass.getMethod("getId"); 124 | memKey = (String) m.invoke(args[0]);//取属性名为id作为key 125 | }catch(Exception e){ 126 | log.warn("{}中没有id属性",args[0]); 127 | } 128 | } 129 | } 130 | } 131 | }//end if entryclass != null 132 | } 133 | if(memKey == null){ 134 | log.warn("方法{}运行时没有取到缓存key!",methodName); 135 | return pjp.proceed(args); 136 | } 137 | //取缓存 138 | memKey = getCacheKey(target, method.getName(), memKey); 139 | if(needCache){ 140 | Object value = memcachedClient.get(memKey); 141 | if(value != null){ 142 | value = JSONObject.parseObject(value.toString(), method.getGenericReturnType()); 143 | log.info("get data from cache:{} costTime:{}", memKey ,cost.cost()); 144 | return value; 145 | }else{ 146 | Object obj = pjp.proceed(args); 147 | /* if(obj instanceof NormalReturn){//不缓存错误结果 148 | if(((NormalReturn) obj).getStatusCode().equals("200")) 149 | return obj; 150 | ((NormalReturn) obj).setCache(true);//标记为已缓存 151 | }*/ 152 | int timeout = MemcachedUtil.MEMCACHED_EXPIRY_TIME;//默认10分钟刷新 153 | //boolean cached = memcachedClient.set(key, JSONObject.toJSONString(obj, SerializerFeature.BrowserCompatible),timeout); 154 | boolean cached = asycSetCache(memKey, obj, timeout); 155 | /* if(!cached && obj instanceof NormalReturn) 156 | ((NormalReturn) obj).setCache(false);//标记为未缓存 157 | */ log.info("cached:{} timeout:{} costTime:{}", memKey,timeout,cost.cost()); 158 | return obj; 159 | } 160 | } 161 | //刷新缓存 162 | if(flushCache){ 163 | List methodList = new ArrayList(); 164 | //取要刷新的key前缀,取不到则刷新所有带有@MemCaching注解的方法 165 | String flushKey = method.getAnnotation(MemFlush.class).key(); 166 | if(StringUtils.isNotEmpty(flushKey)){ 167 | String[] str1=flushKey.split(","); 168 | for(int i=0;i cmd = new Callable(){ 203 | @Override 204 | public Boolean call() throws Exception { 205 | return memcachedClient.set(key, JSONObject.toJSONString(obj, SerializerFeature.BrowserCompatible),timeout); 206 | } 207 | }; 208 | ExecutorFactory.fixedExecutor.submit(cmd); 209 | return true; 210 | } 211 | 212 | /** 213 | * 异步删除缓存 214 | * @param key 215 | * @return 216 | */ 217 | public boolean asycDelCache(final String key) { 218 | Callable cmd = new Callable(){ 219 | @Override 220 | public Boolean call() throws Exception { 221 | return memcachedClient.delete(key); 222 | } 223 | }; 224 | ExecutorFactory.fixedExecutor.submit(cmd); 225 | return true; 226 | } 227 | 228 | private Method getMethod(Object target,String methodName,Object[] args){ 229 | Method method = null; 230 | Class[] classes=new Class[args.length]; 231 | try { 232 | for(int i=0,j=args.length;i[] parameterTypes = ms[i].getParameterTypes(); 250 | if(ms[i].getName().equals(methodName) && parameterTypes.length == classes.length){ 251 | Boolean parmIsMatch = true; 252 | for(int j=0;j getHandlers = new PathTrie(); 32 | private final PathTrie postHandlers = new PathTrie(); 33 | private final PathTrie putHandlers = new PathTrie(); 34 | private final PathTrie deleteHandlers = new PathTrie(); 35 | 36 | public RestChannelHandler(){ 37 | } 38 | 39 | public void messageReceived(ChannelHandlerContext ctx, final MessageEvent me) throws Exception { 40 | CostTime cost = new CostTime(); 41 | cost.start(); 42 | final HttpRequest httpRequest = (HttpRequest) me.getMessage(); 43 | NettyHttpRequest request = new NettyHttpRequest(httpRequest); 44 | Channel channel = me.getChannel(); 45 | final Handler handler = getHandler(request); 46 | Resp response = null; 47 | int code = 200,content_length; 48 | if (handler == null) { 49 | code = 404; 50 | response = new ErrorResp("No handler found for uri ["+ request.uri() + "] and method [" + request.method() + "]",code); 51 | content_length = sendResponse(request, response, httpRequest, channel,cost); 52 | }else{ 53 | try { 54 | response = handler.handleRequest(request); 55 | } catch (JSONException e){ 56 | code = 400; 57 | response = new ErrorResp(e, 400); 58 | } catch (Exception e) { 59 | code = 500; 60 | response = new ErrorResp(e); 61 | }finally{ 62 | content_length = sendResponse(request, response, httpRequest, channel,cost); 63 | } 64 | } 65 | String referer = request.header("Referer"); 66 | String userAgent = request.header("User-Agent"); 67 | String content = request.contentAsString(); 68 | if(content!=null && content.length()>0 && content.indexOf('\n')!=-1) 69 | content = content.replace("\n", ""); 70 | StringBuffer sb = new StringBuffer(); 71 | sb.append(userAgent==null?"":userAgent).append(','); 72 | sb.append(referer==null?"":referer).append(','); 73 | sb.append(content); 74 | if(cost.cost()>100) 75 | log.warn("{} {} {} {} {} {} {}",channel.getRemoteAddress().toString(),httpRequest.getMethod().getName(),httpRequest.getUri(),code,content_length,"\""+sb.toString()+"\"",cost.cost()); 76 | else 77 | log.info("{} {} {} {} {} {} {}",channel.getRemoteAddress().toString(),httpRequest.getMethod().getName(),httpRequest.getUri(),code,content_length,"\""+sb.toString()+"\"",cost.cost()); 78 | 79 | } 80 | 81 | @SuppressWarnings("unused") 82 | public int sendResponse(NettyHttpRequest nettyRequest, Resp response, HttpRequest httpRequest, Channel channel,CostTime cost){ 83 | // Decide whether to close the connection or not. 84 | boolean http10 = httpRequest.getProtocolVersion().equals(HttpVersion.HTTP_1_0); 85 | boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(httpRequest.getHeader(HttpHeaders.Names.CONNECTION)) || 86 | (http10 && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(httpRequest.getHeader(HttpHeaders.Names.CONNECTION))); 87 | 88 | // Build the response object. 89 | HttpResponseStatus status = getStatus(response.getRespData().getCode()); 90 | org.jboss.netty.handler.codec.http.HttpResponse resp; 91 | if (http10) { 92 | resp = new DefaultHttpResponse(HttpVersion.HTTP_1_0, status); 93 | if (!close) { 94 | resp.addHeader(HttpHeaders.Names.CONNECTION, "Keep-Alive"); 95 | } 96 | } else { 97 | resp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status); 98 | } 99 | response.getRespData().setTime(cost.cost()); 100 | // Convert the response content to a ChannelBuffer. 101 | ChannelFutureListener releaseContentListener = null; 102 | ChannelBuffer buf = response.toJson(); 103 | resp.setContent(buf); 104 | resp.setHeader(HttpHeaders.Names.CONTENT_TYPE, CONTENT_TYPE); 105 | int content_length = buf.readableBytes(); 106 | resp.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(content_length)); 107 | resp.setHeader(HttpHeaders.Names.SERVER,Config.get().get("server.name", "rest-netty-server")); 108 | resp.setHeader("Via", NetworkUtils.getLocalAddress().getHostAddress()); 109 | 110 | // Write the response. 111 | ChannelFuture future = channel.write(resp); 112 | 113 | if (releaseContentListener != null) { 114 | future.addListener(releaseContentListener); 115 | } 116 | // Close the connection after the write operation is done if necessary. 117 | if (close) { 118 | future.addListener(ChannelFutureListener.CLOSE); 119 | } 120 | return content_length; 121 | } 122 | 123 | private HttpResponseStatus getStatus(int status) { 124 | switch (status) { 125 | case 100: 126 | return HttpResponseStatus.CONTINUE; 127 | case 101: 128 | return HttpResponseStatus.SWITCHING_PROTOCOLS; 129 | case 200: 130 | return HttpResponseStatus.OK; 131 | case 201: 132 | return HttpResponseStatus.CREATED; 133 | case 202: 134 | return HttpResponseStatus.ACCEPTED; 135 | case 203: 136 | return HttpResponseStatus.NON_AUTHORITATIVE_INFORMATION; 137 | case 204: 138 | return HttpResponseStatus.NO_CONTENT; 139 | case 205: 140 | return HttpResponseStatus.RESET_CONTENT; 141 | case 206: 142 | return HttpResponseStatus.PARTIAL_CONTENT; 143 | case 207: 144 | // no status for this?? 145 | return HttpResponseStatus.INTERNAL_SERVER_ERROR; 146 | case 300: 147 | return HttpResponseStatus.MULTIPLE_CHOICES; 148 | case 301: 149 | return HttpResponseStatus.MOVED_PERMANENTLY; 150 | case 302: 151 | return HttpResponseStatus.FOUND; 152 | case 303: 153 | return HttpResponseStatus.SEE_OTHER; 154 | case 304: 155 | return HttpResponseStatus.NOT_MODIFIED; 156 | case 305: 157 | return HttpResponseStatus.USE_PROXY; 158 | case 307: 159 | return HttpResponseStatus.TEMPORARY_REDIRECT; 160 | case 400: 161 | return HttpResponseStatus.BAD_REQUEST; 162 | case 401: 163 | return HttpResponseStatus.UNAUTHORIZED; 164 | case 402: 165 | return HttpResponseStatus.PAYMENT_REQUIRED; 166 | case 403: 167 | return HttpResponseStatus.FORBIDDEN; 168 | case 404: 169 | return HttpResponseStatus.NOT_FOUND; 170 | case 405: 171 | return HttpResponseStatus.METHOD_NOT_ALLOWED; 172 | case 406: 173 | return HttpResponseStatus.NOT_ACCEPTABLE; 174 | case 407: 175 | return HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED; 176 | case 408: 177 | return HttpResponseStatus.REQUEST_TIMEOUT; 178 | case 409: 179 | return HttpResponseStatus.CONFLICT; 180 | case 410: 181 | return HttpResponseStatus.GONE; 182 | case 411: 183 | return HttpResponseStatus.LENGTH_REQUIRED; 184 | case 412: 185 | return HttpResponseStatus.PRECONDITION_FAILED; 186 | case 413: 187 | return HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE; 188 | case 414: 189 | return HttpResponseStatus.REQUEST_URI_TOO_LONG; 190 | case 415: 191 | return HttpResponseStatus.UNSUPPORTED_MEDIA_TYPE; 192 | case 416: 193 | return HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE; 194 | case 417: 195 | return HttpResponseStatus.EXPECTATION_FAILED; 196 | case 422: 197 | return HttpResponseStatus.BAD_REQUEST; 198 | case 423: 199 | return HttpResponseStatus.BAD_REQUEST; 200 | case 424: 201 | return HttpResponseStatus.BAD_REQUEST; 202 | case 500: 203 | return HttpResponseStatus.INTERNAL_SERVER_ERROR; 204 | case 501: 205 | return HttpResponseStatus.NOT_IMPLEMENTED; 206 | case 502: 207 | return HttpResponseStatus.BAD_GATEWAY; 208 | case 503: 209 | return HttpResponseStatus.SERVICE_UNAVAILABLE; 210 | case 504: 211 | return HttpResponseStatus.GATEWAY_TIMEOUT; 212 | case 505: 213 | return HttpResponseStatus.HTTP_VERSION_NOT_SUPPORTED; 214 | default: 215 | return HttpResponseStatus.INTERNAL_SERVER_ERROR; 216 | } 217 | } 218 | 219 | public void registerHandler(HttpMethod method, String path, Handler handler) { 220 | if (method == HttpMethod.GET) { 221 | getHandlers.insert(path, handler); 222 | } else if (method == HttpMethod.POST) { 223 | postHandlers.insert(path, handler); 224 | } else if (method == HttpMethod.PUT) { 225 | putHandlers.insert(path, handler); 226 | } else if (method == HttpMethod.DELETE) { 227 | deleteHandlers.insert(path, handler); 228 | } else { 229 | throw new RuntimeException("HttpMethod is not supported"); 230 | } 231 | } 232 | 233 | private Handler getHandler(NettyHttpRequest request) { 234 | String path = request.path(); 235 | HttpMethod method = request.method(); 236 | if (method == HttpMethod.GET) { 237 | return getHandlers.retrieve(path, request.params()); 238 | } else if (method == HttpMethod.POST) { 239 | return postHandlers.retrieve(path, request.params()); 240 | } else if (method == HttpMethod.PUT) { 241 | return putHandlers.retrieve(path, request.params()); 242 | } else if (method == HttpMethod.DELETE) { 243 | return deleteHandlers.retrieve(path, request.params()); 244 | } else { 245 | return null; 246 | } 247 | } 248 | 249 | @Override 250 | public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { 251 | if (log.isTraceEnabled()) 252 | log.trace("Connection exceptionCaught:{}", e.getCause().toString()); 253 | e.getChannel().close(); 254 | } 255 | } 256 | --------------------------------------------------------------------------------