From 2502142dc489972d39822d8747cb58fcf27bd6ec Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Fri, 3 Aug 2012 20:03:48 +0800 Subject: [PATCH 001/200] add dubbo-maven --- dubbo-maven/pom.xml | 352 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 352 insertions(+) create mode 100644 dubbo-maven/pom.xml diff --git a/dubbo-maven/pom.xml b/dubbo-maven/pom.xml new file mode 100644 index 000000000000..a81bdbe992b9 --- /dev/null +++ b/dubbo-maven/pom.xml @@ -0,0 +1,352 @@ +opyright 1999-2011 Alibaba Group. + - + - Licensed under the Apache License, Version 2.0 (the "License"); + - you may not use this file except in compliance with the License. + - You may obtain a copy of the License at + - + - http://www.apache.org/licenses/LICENSE-2.0 + - + - Unless required by applicable law or agreed to in writing, software + - distributed under the License is distributed on an "AS IS" BASIS, + - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + - See the License for the specific language governing permissions and + - limitations under the License. +--> + + 4.0.0 + + org.sonatype.oss + oss-parent + 7 + + com.alibaba + dubbo + 2.4.3 + jar + Dubbo + Dubbo is a distributed service framework enpowers applications with service import/export capability with high performance RPC. + http://code.alibabatech.com/wiki/display/dubbo + 2012 + + + Apache 2 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + A business-friendly OSS license + + + + Alibaba + http://www.alibaba.com + + + + org.springframework + spring + 2.5.6.SEC03 + + + org.javassist + javassist + 3.15.0-GA + + + org.jboss.netty + netty + 3.2.5.Final + + + org.apache.mina + mina-core + 1.1.7 + provided + + + org.glassfish.grizzly + grizzly-core + 2.1.4 + provided + + + org.apache.httpcomponents + httpclient + 4.1.2 + provided + + + com.alibaba + fastjson + 1.1.18 + provided + + + com.thoughtworks.xstream + xstream + 1.4.1 + provided + + + org.apache.bsf + bsf-api + 3.1 + provided + + + org.apache.zookeeper + zookeeper + 3.3.3 + provided + + + com.github.sgroschupf + zkclient + 0.1 + provided + + + com.netflix.curator + curator-framework + 1.1.10 + provided + + + com.googlecode.xmemcached + xmemcached + 1.3.6 + provided + + + org.apache.cxf + cxf-rt-frontend-simple + 2.6.1 + provided + + + org.apache.cxf + cxf-rt-transports-http + 2.6.1 + provided + + + org.apache.thrift + libthrift + 0.8.0 + provided + + + com.caucho + hessian + 4.0.7 + provided + + + javax.servlet + servlet-api + 2.5 + provided + + + org.mortbay.jetty + jetty + 6.1.26 + provided + + + log4j + log4j + 1.2.16 + provided + + + org.slf4j + slf4j-api + 1.6.2 + provided + + + redis.clients + jedis + 2.0.0 + provided + + + javax.validation + validation-api + 1.0.0.GA + provided + + + org.hibernate + hibernate-validator + 4.2.0.Final + provided + + + javax.cache + cache-api + 0.4 + provided + + + ch.qos.logback + logback-classic + 1.0.6 + + + + + + maven-source-plugin + + + attach-sources + + jar + + + + + + maven-compiler-plugin + + 1.5 + 1.5 + UTF-8 + + + + maven-jar-plugin + + + true + true + + true + true + + + + + + maven-javadoc-plugin + + + attach-javadoc + + jar + + + + + public + UTF-8 + UTF-8 + UTF-8 + com.alibaba.com.* + + http://docs.oracle.com/javase/6/docs/api + + + + + maven-gpg-plugin + + + sign-artifacts + verify + + sign + + + + + + + + true + + + jira + http://code.alibabatech.com/jira/browse/DUBBO + + + http://code.alibabatech.com/svn/dubbo/trunk + scm:svn:http://code.alibabatech.com/svn/dubbo/trunk + scm:svn:http://code.alibabatech.com/svn/dubbo/trunk + + + + Dubbo User Mailling List + dubbo-subscribe AT googlegroups DOT com + dubbo-unsubscribe AT googlegroups DOT com + dubbo AT googlegroups DOT com + http://groups.google.com/group/dubbo + + + + + QianXiao(Shawn) + shawn.qianx + shawn.qianx (AT) alibaba-inc.com + + Developer + + +8 + + + LiangFei(William) + william.liangf + william.liangf (AT) alibaba-inc.com + + Developer + + +8 + + + LiDing(Jerry) + ding.lid + ding.lid (AT) alibaba-inc.com + + Developer + + +8 + + + LiuChao(Charles) + chao.liuc + chao.liuc (AT) alibaba-inc.com + + Developer + + +8 + + + LiuHaoMin(Ludvik) + haoming.liuhm + haoming.liuhm (AT) alibaba-inc.com + + Developer + + +8 + + + ChenLei(Tony) + tony.chenl + tony.chenl (AT) alibaba-inc.com + + Developer + + +8 + + + LuGang(Kimi) + gang.lvgm + gang.lvgm (AT) alibaba-inc.com + + Developer + + +8 + + + From f4f11304ddd613a5c58770426072c4ecfbbc23ef Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Fri, 3 Aug 2012 20:09:17 +0800 Subject: [PATCH 002/200] add dubbo-maven --- dubbo-maven/pom.xml | 66 ++++++++++++++++++++++----------------------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/dubbo-maven/pom.xml b/dubbo-maven/pom.xml index a81bdbe992b9..2c1543789fdb 100644 --- a/dubbo-maven/pom.xml +++ b/dubbo-maven/pom.xml @@ -4,7 +4,7 @@ opyright 1999-2011 Alibaba Group. - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - - http://www.apache.org/licenses/LICENSE-2.0 + - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, @@ -108,31 +108,31 @@ opyright 1999-2011 Alibaba Group. com.netflix.curator curator-framework 1.1.10 - provided + provided com.googlecode.xmemcached xmemcached 1.3.6 - provided + provided org.apache.cxf cxf-rt-frontend-simple 2.6.1 - provided + provided org.apache.cxf cxf-rt-transports-http 2.6.1 - provided + provided org.apache.thrift libthrift 0.8.0 - provided + provided com.caucho @@ -188,25 +188,25 @@ opyright 1999-2011 Alibaba Group. 0.4 provided - - ch.qos.logback - logback-classic - 1.0.6 - + + ch.qos.logback + logback-classic + 1.0.6 + - - - - maven-source-plugin - - - attach-sources - - jar - - - - + + + + maven-source-plugin + + + attach-sources + + jar + + + + maven-compiler-plugin @@ -231,13 +231,13 @@ opyright 1999-2011 Alibaba Group. maven-javadoc-plugin - - attach-javadoc - - jar - - - + + attach-javadoc + + jar + + + public UTF-8 @@ -261,8 +261,8 @@ opyright 1999-2011 Alibaba Group. - - + + true From 36dcd399e0eb340a696fd2cbdc9db67ad13403d8 Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Fri, 3 Aug 2012 20:15:56 +0800 Subject: [PATCH 003/200] add dubbo-maven --- dubbo-maven/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dubbo-maven/pom.xml b/dubbo-maven/pom.xml index 2c1543789fdb..3b61248ddd40 100644 --- a/dubbo-maven/pom.xml +++ b/dubbo-maven/pom.xml @@ -1,4 +1,4 @@ -opyright 1999-2011 Alibaba Group. +Copyright 1999-2011 Alibaba Group. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. @@ -192,6 +192,7 @@ opyright 1999-2011 Alibaba Group. ch.qos.logback logback-classic 1.0.6 + provided From bdf15583176e620e92b443e0e8f9380bb514b113 Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Fri, 3 Aug 2012 20:23:34 +0800 Subject: [PATCH 004/200] add dubbo-maven --- dubbo-maven/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dubbo-maven/pom.xml b/dubbo-maven/pom.xml index 3b61248ddd40..3df8cb6e8f8e 100644 --- a/dubbo-maven/pom.xml +++ b/dubbo-maven/pom.xml @@ -1,4 +1,5 @@ -Copyright 1999-2011 Alibaba Group. + provider: " + channel.getLocalAddress() + ", message:" + inv); - - return exporter.getInvoker(); - } - + } + + Map> getExporterMap(){ + return exporterMap; + } + + private boolean isClientSide(Channel channel) { + InetSocketAddress address = channel.getRemoteAddress(); + URL url = channel.getUrl(); + return url.getPort() == address.getPort() && + NetUtils.filterLocalHost(channel.getUrl().getIp()) + .equals(NetUtils.filterLocalHost(address.getAddress().getHostAddress())); + } + + Invoker getInvoker(Channel channel, Invocation inv) throws RemotingException{ + boolean isCallBackServiceInvoke = false; + boolean isStubServiceInvoke = false; + int port = channel.getLocalAddress().getPort(); + String path = inv.getAttachments().get(Constants.PATH_KEY); + //濡傛灉鏄鎴风鐨勫洖璋冩湇鍔. + isStubServiceInvoke = Boolean.TRUE.toString().equals(inv.getAttachments().get(Constants.STUB_EVENT_KEY)); + if (isStubServiceInvoke){ + port = channel.getRemoteAddress().getPort(); + } + //callback + isCallBackServiceInvoke = isClientSide(channel) && !isStubServiceInvoke; + if(isCallBackServiceInvoke){ + path = inv.getAttachments().get(Constants.PATH_KEY)+"."+inv.getAttachments().get(Constants.CALLBACK_SERVICE_KEY); + inv.getAttachments().put(IS_CALLBACK_SERVICE_INVOKE, Boolean.TRUE.toString()); + } + String serviceKey = serviceKey(port, path, inv.getAttachments().get(Constants.VERSION_KEY), inv.getAttachments().get(Constants.GROUP_KEY)); + + DubboExporter exporter = (DubboExporter) exporterMap.get(serviceKey); + + if (exporter == null) + throw new RemotingException(channel, "Not found exported service: " + serviceKey + " in " + exporterMap.keySet() + ", may be version or group mismatch " + ", channel: consumer: " + channel.getRemoteAddress() + " --> provider: " + channel.getLocalAddress() + ", message:" + inv); + + return exporter.getInvoker(); + } + public Collection> getInvokers() { return Collections.unmodifiableCollection(invokers); } @@ -242,38 +242,39 @@ public Exporter export(Invoker invoker) throws RpcException { String stubServiceMethods = url.getParameter(Constants.STUB_EVENT_METHODS_KEY); if (stubServiceMethods == null || stubServiceMethods.length() == 0 ){ if (logger.isWarnEnabled()){ - logger.warn( new IllegalStateException("consumer ["+url.getParameter(Constants.INTERFACE_KEY)+"], has set stubproxy support event ,but no stub methods founded.")); + logger.warn(new IllegalStateException("consumer [" +url.getParameter(Constants.INTERFACE_KEY) + + "], has set stubproxy support event ,but no stub methods founded.")); } } else { stubServiceMethodsMap.put(url.getServiceKey(), stubServiceMethods); } - } - - openServer(url); - - return exporter; - } - - private void openServer(URL url) { - // find server. - String key = url.getAddress(); - //client 涔熷彲浠ユ毚闇蹭竴涓彧鏈塻erver鍙互璋冪敤鐨勬湇鍔° - boolean isServer = url.getParameter(Constants.IS_SERVER_KEY,true); - if (isServer) { - ExchangeServer server = serverMap.get(key); - if (server == null) { - serverMap.put(key, getServer(url)); - } else { - //server鏀寔reset,閰嶅悎override鍔熻兘浣跨敤 - server.reset(url); - } - } - } + } + + openServer(url); + + return exporter; + } + + private void openServer(URL url) { + // find server. + String key = url.getAddress(); + //client 涔熷彲浠ユ毚闇蹭竴涓彧鏈塻erver鍙互璋冪敤鐨勬湇鍔° + boolean isServer = url.getParameter(Constants.IS_SERVER_KEY,true); + if (isServer) { + ExchangeServer server = serverMap.get(key); + if (server == null) { + serverMap.put(key, createServer(url)); + } else { + //server鏀寔reset,閰嶅悎override鍔熻兘浣跨敤 + server.reset(url); + } + } + } - private ExchangeServer getServer(URL url) { - //榛樿寮鍚痵erver鍏抽棴鏃跺彂閫乺eadonly浜嬩欢 - url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); - //榛樿寮鍚痟eartbeat + private ExchangeServer createServer(URL url) { + //榛樿寮鍚痵erver鍏抽棴鏃跺彂閫乺eadonly浜嬩欢 + url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); + //榛樿寮鍚痟eartbeat url = url.addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT)); String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER); @@ -295,92 +296,92 @@ private ExchangeServer getServer(URL url) { } } return server; - } + } - public Invoker refer(Class serviceType, URL url) throws RpcException { + public Invoker refer(Class serviceType, URL url) throws RpcException { // create rpc invoker. DubboInvoker invoker = new DubboInvoker(serviceType, url, getClients(url), invokers); - invokers.add(invoker); + invokers.add(invoker); return invoker; - } - - private ExchangeClient[] getClients(URL url){ - //鏄惁鍏变韩杩炴帴 - boolean service_share_connect = false; - int connections = url.getParameter(Constants.CONNECTIONS_KEY, 0); - //濡傛灉connections涓嶉厤缃紝鍒欏叡浜繛鎺ワ紝鍚﹀垯姣忔湇鍔℃瘡杩炴帴 - if (connections == 0){ - service_share_connect = true; - connections = 1; - } - - ExchangeClient[] clients = new ExchangeClient[connections]; - for (int i = 0; i < clients.length; i++) { - if (service_share_connect){ - clients[i] = getSharedClient(url); - } else { - clients[i] = initClient(url); - } - } - return clients; - } - - /** - *鑾峰彇鍏变韩杩炴帴 - */ - private ExchangeClient getSharedClient(URL url){ - String key = url.getAddress(); - ReferenceCountExchangeClient client = referenceClientMap.get(key); - if ( client != null ){ - if ( !client.isClosed()){ - client.incrementAndGetCount(); - return client; - } else { -// logger.warn(new IllegalStateException("client is closed,but stay in clientmap .client :"+ client)); - referenceClientMap.remove(key); - } - } - ExchangeClient exchagneclient = initClient(url); - - client = new ReferenceCountExchangeClient(exchagneclient, ghostClientMap); - referenceClientMap.put(key, client); - ghostClientMap.remove(key); - return client; + } + + private ExchangeClient[] getClients(URL url){ + //鏄惁鍏变韩杩炴帴 + boolean service_share_connect = false; + int connections = url.getParameter(Constants.CONNECTIONS_KEY, 0); + //濡傛灉connections涓嶉厤缃紝鍒欏叡浜繛鎺ワ紝鍚﹀垯姣忔湇鍔℃瘡杩炴帴 + if (connections == 0){ + service_share_connect = true; + connections = 1; + } + + ExchangeClient[] clients = new ExchangeClient[connections]; + for (int i = 0; i < clients.length; i++) { + if (service_share_connect){ + clients[i] = getSharedClient(url); + } else { + clients[i] = initClient(url); + } + } + return clients; + } + + /** + *鑾峰彇鍏变韩杩炴帴 + */ + private ExchangeClient getSharedClient(URL url){ + String key = url.getAddress(); + ReferenceCountExchangeClient client = referenceClientMap.get(key); + if ( client != null ){ + if ( !client.isClosed()){ + client.incrementAndGetCount(); + return client; + } else { +// logger.warn(new IllegalStateException("client is closed,but stay in clientmap .client :"+ client)); + referenceClientMap.remove(key); + } + } + ExchangeClient exchagneclient = initClient(url); + + client = new ReferenceCountExchangeClient(exchagneclient, ghostClientMap); + referenceClientMap.put(key, client); + ghostClientMap.remove(key); + return client; } - /** - * 鍒涘缓鏂拌繛鎺. - */ - private ExchangeClient initClient(URL url) { - + /** + * 鍒涘缓鏂拌繛鎺. + */ + private ExchangeClient initClient(URL url) { + // client type setting. String str = url.getParameter(Constants.CLIENT_KEY, url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_CLIENT)); String version = url.getParameter(Constants.DUBBO_VERSION_KEY); boolean compatible = (version != null && version.startsWith("1.0.")); url = url.addParameter(Constants.CODEC_KEY, Version.isCompatibleVersion() && compatible ? COMPATIBLE_CODEC_NAME : DubboCodec.NAME); - //榛樿寮鍚痟eartbeat - url = url.addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT)); + //榛樿寮鍚痟eartbeat + url = url.addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT)); // BIO瀛樺湪涓ラ噸鎬ц兘闂锛屾殏鏃朵笉鍏佽浣跨敤 if (str != null && str.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) { throw new RpcException("Unsupported client type: " + str + "," + " supported client type is " + StringUtils.join(ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions(), " ")); } - - ExchangeClient client ; + + ExchangeClient client ; try { //璁剧疆杩炴帴搴旇鏄痩azy鐨 if (url.getParameter(Constants.LAZY_CONNECT_KEY, false)){ client = new LazyConnectExchangeClient(url ,requestHandler); } else { client = Exchangers.connect(url ,requestHandler); - } - } catch (RemotingException e) { - throw new RpcException("Fail to create remoting client for service(" + url - + "): " + e.getMessage(), e); - } - return client; + } + } catch (RemotingException e) { + throw new RpcException("Fail to create remoting client for service(" + url + + "): " + e.getMessage(), e); + } + return client; } public void destroy() { @@ -397,34 +398,34 @@ public void destroy() { logger.warn(t.getMessage(), t); } } - } - - for (String key : new ArrayList(referenceClientMap.keySet())) { - ExchangeClient client = referenceClientMap.remove(key); - if (client != null) { - try { - if (logger.isInfoEnabled()) { - logger.info("Close dubbo connect: " + client.getLocalAddress() + "-->" + client.getRemoteAddress()); - } - client.close(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } - } - - for (String key : new ArrayList(ghostClientMap.keySet())) { - ExchangeClient client = ghostClientMap.remove(key); - if (client != null) { - try { - if (logger.isInfoEnabled()) { - logger.info("Close dubbo connect: " + client.getLocalAddress() + "-->" + client.getRemoteAddress()); - } - client.close(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } + } + + for (String key : new ArrayList(referenceClientMap.keySet())) { + ExchangeClient client = referenceClientMap.remove(key); + if (client != null) { + try { + if (logger.isInfoEnabled()) { + logger.info("Close dubbo connect: " + client.getLocalAddress() + "-->" + client.getRemoteAddress()); + } + client.close(); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); + } + } + } + + for (String key : new ArrayList(ghostClientMap.keySet())) { + ExchangeClient client = ghostClientMap.remove(key); + if (client != null) { + try { + if (logger.isInfoEnabled()) { + logger.info("Close dubbo connect: " + client.getLocalAddress() + "-->" + client.getRemoteAddress()); + } + client.close(); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); + } + } } stubServiceMethodsMap.clear(); } From fdbf715757638d7d1a73855eb133700d13ba9ed9 Mon Sep 17 00:00:00 2001 From: oldrat Date: Tue, 14 Aug 2012 10:50:47 +0800 Subject: [PATCH 017/200] =?UTF-8?q?DUBBO-562=20Dubbo=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E7=9A=84=E7=B3=BB=E7=BB=9FProperty=E4=BD=9C=E4=B8=BA=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E6=97=B6=E6=89=93=E5=8D=B0=E5=87=BA=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E6=8F=90=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/dubbo/config/AbstractConfig.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java index 96870a322400..c03d01c1b7b6 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java @@ -146,12 +146,17 @@ protected static void appendProperties(AbstractConfig config) { if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 1 && isPrimitive(method.getParameterTypes()[0])) { String property = StringUtils.camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-"); + String value = null; if (config.getId() != null && config.getId().length() > 0) { - value = System.getProperty(prefix + config.getId() + "." + property); + String pn = prefix + config.getId() + "." + property; + value = System.getProperty(pn); + logger.info("Use System Property " + pn + "to config dubbo"); } if (value == null || value.length() == 0) { - value = System.getProperty(prefix + property); + String pn = prefix + property; + value = System.getProperty(pn); + logger.info("Use System Property " + pn + "to config dubbo"); } if (value == null || value.length() == 0) { Method getter; From b2be1f6ed283cff60e10073040422a5fd662a25c Mon Sep 17 00:00:00 2001 From: oldrat Date: Tue, 14 Aug 2012 11:50:35 +0800 Subject: [PATCH 018/200] =?UTF-8?q?DUBBO-563=20Config=E7=B1=BB=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E5=8F=98=E9=87=8F=E6=B7=BB=E5=8A=A0volatile=E4=BF=AE?= =?UTF-8?q?=E9=A5=B0=E7=AC=A6=EF=BC=8C=E9=81=BF=E5=85=8D=E5=8F=AF=E8=A7=81?= =?UTF-8?q?=E6=80=A7=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/config/ReferenceConfig.java | 8 +- .../alibaba/dubbo/config/ServiceConfig.java | 352 +++++++++--------- 2 files changed, 186 insertions(+), 174 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java index 7f06848dcb4a..7aa387c473ed 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java @@ -86,13 +86,13 @@ public class ReferenceConfig extends AbstractReferenceConfig { private String protocol; // 鎺ュ彛浠g悊绫诲紩鐢 - private transient T ref; + private transient volatile T ref; - private transient Invoker invoker; + private transient volatile Invoker invoker; - private transient boolean initialized; + private transient volatile boolean initialized; - private transient boolean destroyed; + private transient volatile boolean destroyed; private final List urls = new ArrayList(); diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java index 2194c44c253a..71c883fd9468 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java @@ -83,11 +83,11 @@ public class ServiceConfig extends AbstractServiceConfig { private final List> exporters = new ArrayList>(); - private transient boolean exported; + private transient volatile boolean exported; - private transient boolean unexported; + private transient volatile boolean unexported; - private transient boolean generic; + private transient volatile boolean generic; public ServiceConfig() { } @@ -278,205 +278,217 @@ public synchronized void unexport() { private void doExportUrls() { List registryURLs = loadRegistries(true); for (ProtocolConfig protocolConfig : protocols) { - String name = protocolConfig.getName(); - if (name == null || name.length() == 0) { - name = "dubbo"; - } - String host = protocolConfig.getHost(); - if (provider != null && (host == null || host.length() == 0)) { - host = provider.getHost(); + doExportUrlsFor1Protocol(protocolConfig, registryURLs); + } + } + + private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List registryURLs) { + String name = protocolConfig.getName(); + if (name == null || name.length() == 0) { + name = "dubbo"; + } + + String host = protocolConfig.getHost(); + if (provider != null && (host == null || host.length() == 0)) { + host = provider.getHost(); + } + boolean anyhost = false; + if (NetUtils.isInvalidLocalHost(host)) { + anyhost = true; + try { + host = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + logger.warn(e.getMessage(), e); } - boolean anyhost = false; if (NetUtils.isInvalidLocalHost(host)) { - anyhost = true; - try { - host = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException e) { - logger.warn(e.getMessage(), e); - } - if (NetUtils.isInvalidLocalHost(host)) { - if (registryURLs != null && registryURLs.size() > 0) { - for (URL registryURL : registryURLs) { + if (registryURLs != null && registryURLs.size() > 0) { + for (URL registryURL : registryURLs) { + try { + Socket socket = new Socket(); try { - Socket socket = new Socket(); + SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort()); + socket.connect(addr, 1000); + host = socket.getLocalAddress().getHostAddress(); + break; + } finally { try { - SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort()); - socket.connect(addr, 1000); - host = socket.getLocalAddress().getHostAddress(); - break; - } finally { - try { - socket.close(); - } catch (Throwable e) {} - } - } catch (Exception e) { - logger.warn(e.getMessage(), e); + socket.close(); + } catch (Throwable e) {} } + } catch (Exception e) { + logger.warn(e.getMessage(), e); } } - if (NetUtils.isInvalidLocalHost(host)) { - host = NetUtils.getLocalHost(); - } } - } - Integer port = protocolConfig.getPort(); - if (provider != null && (port == null || port == 0)) { - port = provider.getPort(); - } - int defaultPort = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(name).getDefaultPort(); - if (port == null || port == 0) { - port = defaultPort; - } - if (port == null || port <= 0) { - port = getRandomPort(name); - if (port == null || port < 0) { - port = NetUtils.getAvailablePort(defaultPort); - putRandomPort(name, port); + if (NetUtils.isInvalidLocalHost(host)) { + host = NetUtils.getLocalHost(); } - logger.warn("Use random available port(" + port + ") for protocol " + name); } - Map map = new HashMap(); - if (anyhost) { - map.put(Constants.ANYHOST_KEY, "true"); - } - map.put(Constants.SIDE_KEY, Constants.PROVIDER_SIDE); - map.put(Constants.DUBBO_VERSION_KEY, Version.getVersion()); - map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis())); - if (ConfigUtils.getPid() > 0) { - map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid())); + } + + Integer port = protocolConfig.getPort(); + if (provider != null && (port == null || port == 0)) { + port = provider.getPort(); + } + final int defaultPort = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(name).getDefaultPort(); + if (port == null || port == 0) { + port = defaultPort; + } + if (port == null || port <= 0) { + port = getRandomPort(name); + if (port == null || port < 0) { + port = NetUtils.getAvailablePort(defaultPort); + putRandomPort(name, port); } - appendParameters(map, application); - appendParameters(map, module); - appendParameters(map, provider, Constants.DEFAULT_KEY); - appendParameters(map, protocolConfig); - appendParameters(map, this); - if (methods != null && methods.size() > 0) { - for (MethodConfig method : methods) { - appendParameters(map, method, method.getName()); - String retryKey = method.getName() + ".retry"; - if (map.containsKey(retryKey)) { - String retryValue = map.remove(retryKey); - if ("false".equals(retryValue)) { - map.put(method.getName() + ".retries", "0"); - } + logger.warn("Use random available port(" + port + ") for protocol " + name); + } + + Map map = new HashMap(); + if (anyhost) { + map.put(Constants.ANYHOST_KEY, "true"); + } + map.put(Constants.SIDE_KEY, Constants.PROVIDER_SIDE); + map.put(Constants.DUBBO_VERSION_KEY, Version.getVersion()); + map.put(Constants.TIMESTAMP_KEY, String.valueOf(System.currentTimeMillis())); + if (ConfigUtils.getPid() > 0) { + map.put(Constants.PID_KEY, String.valueOf(ConfigUtils.getPid())); + } + appendParameters(map, application); + appendParameters(map, module); + appendParameters(map, provider, Constants.DEFAULT_KEY); + appendParameters(map, protocolConfig); + appendParameters(map, this); + if (methods != null && methods.size() > 0) { + for (MethodConfig method : methods) { + appendParameters(map, method, method.getName()); + String retryKey = method.getName() + ".retry"; + if (map.containsKey(retryKey)) { + String retryValue = map.remove(retryKey); + if ("false".equals(retryValue)) { + map.put(method.getName() + ".retries", "0"); } - List arguments = method.getArguments(); - if (arguments != null && arguments.size() > 0) { - for (ArgumentConfig argument : arguments) { - //绫诲瀷鑷姩杞崲. - if(argument.getType() != null && argument.getType().length() >0){ - Method[] methods = interfaceClass.getMethods(); - //閬嶅巻鎵鏈夋柟娉 - if(methods != null && methods.length > 0){ - for (int i = 0; i < methods.length; i++) { - String methodName = methods[i].getName(); - //鍖归厤鏂规硶鍚嶇О锛岃幏鍙栨柟娉曠鍚. - if(methodName.equals(method.getName())){ - Class[] argtypes = methods[i].getParameterTypes(); - //涓涓柟娉曚腑鍗曚釜callback - if (argument.getIndex() != -1 ){ - if (argtypes[argument.getIndex()].getName().equals(argument.getType())){ - appendParameters(map, argument, method.getName() + "." + argument.getIndex()); - }else { - throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :"+argument.getIndex() + ", type:" + argument.getType()); - } - } else { - //涓涓柟娉曚腑澶氫釜callback - for (int j = 0 ;j argclazz = argtypes[j]; - if (argclazz.getName().equals(argument.getType())){ - appendParameters(map, argument, method.getName() + "." + j); - if (argument.getIndex() != -1 && argument.getIndex() != j){ - throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :"+argument.getIndex() + ", type:" + argument.getType()); - } + } + List arguments = method.getArguments(); + if (arguments != null && arguments.size() > 0) { + for (ArgumentConfig argument : arguments) { + //绫诲瀷鑷姩杞崲. + if(argument.getType() != null && argument.getType().length() >0){ + Method[] methods = interfaceClass.getMethods(); + //閬嶅巻鎵鏈夋柟娉 + if(methods != null && methods.length > 0){ + for (int i = 0; i < methods.length; i++) { + String methodName = methods[i].getName(); + //鍖归厤鏂规硶鍚嶇О锛岃幏鍙栨柟娉曠鍚. + if(methodName.equals(method.getName())){ + Class[] argtypes = methods[i].getParameterTypes(); + //涓涓柟娉曚腑鍗曚釜callback + if (argument.getIndex() != -1 ){ + if (argtypes[argument.getIndex()].getName().equals(argument.getType())){ + appendParameters(map, argument, method.getName() + "." + argument.getIndex()); + }else { + throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :"+argument.getIndex() + ", type:" + argument.getType()); + } + } else { + //涓涓柟娉曚腑澶氫釜callback + for (int j = 0 ;j argclazz = argtypes[j]; + if (argclazz.getName().equals(argument.getType())){ + appendParameters(map, argument, method.getName() + "." + j); + if (argument.getIndex() != -1 && argument.getIndex() != j){ + throw new IllegalArgumentException("argument config error : the index attribute and type attirbute not match :index :"+argument.getIndex() + ", type:" + argument.getType()); } } } } } } - }else if(argument.getIndex() != -1){ - appendParameters(map, argument, method.getName() + "." + argument.getIndex()); - }else { - throw new IllegalArgumentException("argument config must set index or type attribute.eg: or "); } - + }else if(argument.getIndex() != -1){ + appendParameters(map, argument, method.getName() + "." + argument.getIndex()); + }else { + throw new IllegalArgumentException("argument config must set index or type attribute.eg: or "); } + } } + } // end of methods for + } + + if (generic) { + map.put("generic", String.valueOf(true)); + map.put("methods", Constants.ANY_VALUE); + } else { + String revision = Version.getVersion(interfaceClass, version); + if (revision != null && revision.length() > 0) { + map.put("revision", revision); } - if (generic) { - map.put("generic", String.valueOf(true)); - map.put("methods", Constants.ANY_VALUE); + map.put("methods", StringUtils.join(new HashSet(Arrays.asList(Wrapper.getWrapper(interfaceClass).getDeclaredMethodNames())), ",")); + } + if (! ConfigUtils.isEmpty(token)) { + if (ConfigUtils.isDefault(token)) { + map.put("token", UUID.randomUUID().toString()); } else { - String revision = Version.getVersion(interfaceClass, version); - if (revision != null && revision.length() > 0) { - map.put("revision", revision); - } - map.put("methods", StringUtils.join(new HashSet(Arrays.asList(Wrapper.getWrapper(interfaceClass).getDeclaredMethodNames())), ",")); + map.put("token", token); } - if (! ConfigUtils.isEmpty(token)) { - if (ConfigUtils.isDefault(token)) { - map.put("token", UUID.randomUUID().toString()); - } else { - map.put("token", token); - } - } - if ("injvm".equals(protocolConfig.getName())) { - protocolConfig.setRegister(false); - map.put("notify", "false"); - } - // 瀵煎嚭鏈嶅姟 - String contextPath = protocolConfig.getContextpath(); - if ((contextPath == null || contextPath.length() == 0) && provider != null) { - contextPath = provider.getContextpath(); - } - URL url = new URL(name, host, port, (contextPath == null || contextPath.length() == 0 ? "" : contextPath + "/") + path, map); - - if (ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class) + } + if ("injvm".equals(protocolConfig.getName())) { + protocolConfig.setRegister(false); + map.put("notify", "false"); + } + // 瀵煎嚭鏈嶅姟 + String contextPath = protocolConfig.getContextpath(); + if ((contextPath == null || contextPath.length() == 0) && provider != null) { + contextPath = provider.getContextpath(); + } + URL url = new URL(name, host, port, (contextPath == null || contextPath.length() == 0 ? "" : contextPath + "/") + path, map); + + if (ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class) .hasExtension(url.getProtocol())) { - url = ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class) + url = ExtensionLoader.getExtensionLoader(ConfiguratorFactory.class) .getExtension(url.getProtocol()).getConfigurator(url).configure(url); + } + + String scope = url.getParameter(Constants.SCOPE_KEY); + //閰嶇疆涓簄one涓嶆毚闇 + if (! Constants.SCOPE_NONE.toString().equalsIgnoreCase(scope)) { + + //閰嶇疆涓嶆槸remote鐨勬儏鍐典笅鍋氭湰鍦版毚闇 (閰嶇疆涓簉emote锛屽垯琛ㄧず鍙毚闇茶繙绋嬫湇鍔) + if (!Constants.SCOPE_REMOTE.toString().equalsIgnoreCase(scope)) { + exportLocal(url); } - - String scope = url.getParameter(Constants.SCOPE_KEY); - //閰嶇疆涓簄one涓嶆毚闇 - if (! Constants.SCOPE_NONE.toString().equalsIgnoreCase(scope)) { - //閰嶇疆涓嶆槸remote鐨勬儏鍐典笅鍋氭湰鍦版毚闇 (閰嶇疆涓簉emote锛屽垯琛ㄧず鍙毚闇茶繙绋嬫湇鍔) - if (!Constants.SCOPE_REMOTE.toString().equalsIgnoreCase(scope)) { - exportLocal(url); - } - //濡傛灉閰嶇疆涓嶆槸local鍒欐毚闇蹭负杩滅▼鏈嶅姟.(閰嶇疆涓簂ocal锛屽垯琛ㄧず鍙毚闇茶繙绋嬫湇鍔) - if (! Constants.SCOPE_LOCAL.toString().equalsIgnoreCase(scope) ){ - if (logger.isInfoEnabled()) { - logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url); - } - if (registryURLs != null && registryURLs.size() > 0 - && url.getParameter("register", true)) { - for (URL registryURL : registryURLs) { - url = url.addParameterIfAbsent("dynamic", registryURL.getParameter("dynamic")); - URL monitorUrl = loadMonitor(registryURL); - if (monitorUrl != null) { - url = url.addParameterAndEncoded(Constants.MONITOR_KEY, monitorUrl.toFullString()); - } - if (logger.isInfoEnabled()) { - logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url + " to registry " + registryURL); - } - Invoker invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString())); - Exporter exporter = protocol.export(invoker); - exporters.add(exporter); - } - } else { - Invoker invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, url); - Exporter exporter = protocol.export(invoker); - exporters.add(exporter); - } - } + //濡傛灉閰嶇疆涓嶆槸local鍒欐毚闇蹭负杩滅▼鏈嶅姟.(閰嶇疆涓簂ocal锛屽垯琛ㄧず鍙毚闇茶繙绋嬫湇鍔) + if (! Constants.SCOPE_LOCAL.toString().equalsIgnoreCase(scope) ){ + if (logger.isInfoEnabled()) { + logger.info("Export dubbo service " + interfaceClass.getName() + " to url " + url); + } + if (registryURLs != null && registryURLs.size() > 0 + && url.getParameter("register", true)) { + for (URL registryURL : registryURLs) { + url = url.addParameterIfAbsent("dynamic", registryURL.getParameter("dynamic")); + URL monitorUrl = loadMonitor(registryURL); + if (monitorUrl != null) { + url = url.addParameterAndEncoded(Constants.MONITOR_KEY, monitorUrl.toFullString()); + } + if (logger.isInfoEnabled()) { + logger.info("Register dubbo service " + interfaceClass.getName() + " url " + url + " to registry " + registryURL); + } + Invoker invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString())); + + Exporter exporter = protocol.export(invoker); + exporters.add(exporter); + } + } else { + Invoker invoker = proxyFactory.getInvoker(ref, (Class) interfaceClass, url); + + Exporter exporter = protocol.export(invoker); + exporters.add(exporter); + } } - this.urls.add(url); } + this.urls.add(url); } + @SuppressWarnings({ "unchecked", "rawtypes" }) private void exportLocal(URL url) { if (!Constants.LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) { From 1a91825f664b16005a725cc05c3b748c05d4df7f Mon Sep 17 00:00:00 2001 From: oldrat Date: Tue, 14 Aug 2012 11:53:09 +0800 Subject: [PATCH 019/200] update version to 2.5.1-SNAPSHOT --- dubbo-admin/pom.xml | 2 +- dubbo-cluster/pom.xml | 2 +- dubbo-common/pom.xml | 2 +- dubbo-config/dubbo-config-api/pom.xml | 2 +- dubbo-config/dubbo-config-spring/pom.xml | 2 +- dubbo-config/pom.xml | 2 +- dubbo-container/dubbo-container-api/pom.xml | 2 +- dubbo-container/dubbo-container-jetty/pom.xml | 2 +- dubbo-container/dubbo-container-log4j/pom.xml | 2 +- dubbo-container/dubbo-container-logback/pom.xml | 2 +- dubbo-container/dubbo-container-spring/pom.xml | 2 +- dubbo-container/pom.xml | 2 +- dubbo-demo/dubbo-demo-api/pom.xml | 2 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 2 +- dubbo-demo/dubbo-demo-provider/pom.xml | 2 +- dubbo-demo/pom.xml | 2 +- dubbo-filter/dubbo-filter-cache/pom.xml | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 2 +- dubbo-filter/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +- dubbo-monitor/pom.xml | 2 +- dubbo-registry/dubbo-registry-api/pom.xml | 2 +- dubbo-registry/dubbo-registry-default/pom.xml | 2 +- dubbo-registry/dubbo-registry-multicast/pom.xml | 2 +- dubbo-registry/dubbo-registry-redis/pom.xml | 2 +- dubbo-registry/dubbo-registry-zookeeper/pom.xml | 2 +- dubbo-registry/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-p2p/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-zookeeper/pom.xml | 2 +- dubbo-remoting/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-default/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 2 +- dubbo-rpc/pom.xml | 2 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 2 +- dubbo-simple/dubbo-registry-simple/pom.xml | 2 +- dubbo-simple/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark/pom.xml | 2 +- dubbo-test/dubbo-test-compatibility/pom.xml | 2 +- dubbo-test/dubbo-test-examples/pom.xml | 2 +- dubbo-test/dubbo-test-integration/pom.xml | 2 +- dubbo-test/pom.xml | 2 +- dubbo/pom.xml | 2 +- pom.xml | 2 +- 57 files changed, 57 insertions(+), 57 deletions(-) diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index 14c8422775b9..1e1d456130cb 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-admin war diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index 6cc7f1c8b681..760fe79b6527 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-cluster jar diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index 3a295b5b9f3e..0c53ed4282ec 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-common jar diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 964598452677..fd028cdbab82 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-config-api jar diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 2482253c177c..f70091593951 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-config-spring jar diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index ae20dd015dd3..8591181b21ec 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index d27becd676b3..242ea63aae70 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-container-api jar diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index c982b0c5aa0e..a6da58edd8ea 100644 --- a/dubbo-container/dubbo-container-jetty/pom.xml +++ b/dubbo-container/dubbo-container-jetty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index c504b006a2fd..81e22e5a7a8e 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index 1392de0bea59..67ee9c5aea90 100644 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ b/dubbo-container/dubbo-container-logback/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index 069dae8ed32f..a724d9301dd8 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-container-spring jar diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index 7a2ce45f46fc..bc0dbfe8b76d 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-container pom diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index 60ecb9228349..181677dda32f 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-demo-api jar diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml index eaa29042d1ea..cbf7994e5746 100644 --- a/dubbo-demo/dubbo-demo-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-demo-consumer jar diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml index 3e08241c1455..eec9382c28f1 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-demo-provider jar diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index a7d3612e7dc6..1a6c466a1e04 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-demo pom diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 16b0a932b913..269ef15c1524 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index c4247a114025..96d85242d319 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index f229be701586..10eff8097f72 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-filter pom diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index c5754290e07d..ac4eb116f4f2 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index 7efa9a7c2b89..65a30681c9ea 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index 5d288a7f8949..689f1a608d23 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 1b5578126517..42dd87710e9c 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index 8d05c8a5ee89..5a6a5c2ccc40 100644 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ b/dubbo-registry/dubbo-registry-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-registry-default jar diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index 14b61b7c3407..7cb38680d281 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index e925f19f517e..3b71cc519831 100644 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ b/dubbo-registry/dubbo-registry-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-registry-redis jar diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index bec7c3e78e24..b57cedbf7367 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-registry-zookeeper jar diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index 5427149b5305..0b5dfe0d59a9 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-registry pom diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index 0a8ab7ec8f47..30823ac83b50 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-remoting-api jar diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml index f3475aa2f606..e615c69e235d 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml +++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-remoting-grizzly jar diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index 4338449bbd5f..83b74355929a 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-remoting-http jar diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml index a7dfa9da99d7..9298d59fd4f7 100644 --- a/dubbo-remoting/dubbo-remoting-mina/pom.xml +++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-remoting-mina jar diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index ad966b182581..eb9a6fb1f3fe 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-remoting-netty jar diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml index 5b18f1d7038d..2feadb7c390d 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml +++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-remoting-p2p jar diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index 606cc8aab211..e1d74996b919 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-remoting-zookeeper jar diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 0400b0d33186..ca8a09eea4d7 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-remoting pom diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index a5854cc9ebd1..147ef085fbb6 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-rpc-api jar diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index 016bb7166912..474ebc6b80da 100644 --- a/dubbo-rpc/dubbo-rpc-default/pom.xml +++ b/dubbo-rpc/dubbo-rpc-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-rpc-default jar diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index f293a9591c59..5288b30f1b7a 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-rpc-hessian jar diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index c9c8ec21d83c..5fd11498680e 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-rpc-http jar diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index 48b9e792d58c..83fc38caca7a 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml +++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-rpc-injvm jar diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml index 22dcd2ef2235..fd1fca7075e9 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml +++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-rpc-memcached jar diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml index 0998d30e7714..55b91a9ba4b3 100644 --- a/dubbo-rpc/dubbo-rpc-redis/pom.xml +++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-rpc-redis jar diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml index 75c6b01efae7..28ea93a87688 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-rpc-rmi jar diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml index 3a736ab88094..704b70eaef61 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ b/dubbo-rpc/dubbo-rpc-thrift/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-rpc-thrift jar diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml index 1e236982d353..752b03224acc 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml +++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-rpc-webservice jar diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 9461dc0717a6..3a0b7b966a80 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-rpc pom diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml index e30bc2fe7c20..6e4bf8afdd31 100644 --- a/dubbo-simple/dubbo-monitor-simple/pom.xml +++ b/dubbo-simple/dubbo-monitor-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-monitor-simple jar diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml index 26e0933deaf5..36fb115b6b51 100644 --- a/dubbo-simple/dubbo-registry-simple/pom.xml +++ b/dubbo-simple/dubbo-registry-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-registry-simple jar diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml index 30dd493403bd..fc216d21f79a 100644 --- a/dubbo-simple/pom.xml +++ b/dubbo-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-simple pom diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml index 1e439dc31e44..3d2f0be891aa 100644 --- a/dubbo-test/dubbo-test-benchmark/pom.xml +++ b/dubbo-test/dubbo-test-benchmark/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-test-benchmark jar diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml index b9de78e7ce3e..65222dc32cb1 100644 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ b/dubbo-test/dubbo-test-compatibility/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-test-compatibility jar diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index 2ca45d060188..dc717aa8f348 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-test-examples jar diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml index 0068da31a88f..9f5c5d6c8422 100644 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ b/dubbo-test/dubbo-test-integration/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-test-integration jar diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml index 6a236ff407b9..aa73320922dd 100644 --- a/dubbo-test/pom.xml +++ b/dubbo-test/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo-test pom diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 6f4b4921ae89..188430bfe914 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT dubbo jar diff --git a/pom.xml b/pom.xml index ef0b933c91f1..c33f1370b498 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ 2.0 dubbo-parent - 2.5.0-SNAPSHOT + 2.5.1-SNAPSHOT pom ${project.artifactId} The parent project of dubbo From e43363ed850ca552ca0dbb46113816701b0ccb32 Mon Sep 17 00:00:00 2001 From: oldrat Date: Tue, 14 Aug 2012 17:39:18 +0800 Subject: [PATCH 020/200] =?UTF-8?q?bug=20fix=20DUBBO-566=20redis=E5=8D=8F?= =?UTF-8?q?=E8=AE=AE=E6=B2=A1=E6=9C=89=E9=87=8A=E6=94=BE=E8=B5=84=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rpc/protocol/redis/RedisProtocol.java | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/dubbo-rpc/dubbo-rpc-redis/src/main/java/com/alibaba/dubbo/rpc/protocol/redis/RedisProtocol.java b/dubbo-rpc/dubbo-rpc-redis/src/main/java/com/alibaba/dubbo/rpc/protocol/redis/RedisProtocol.java index c51d56576efb..bcb9e2f25a03 100644 --- a/dubbo-rpc/dubbo-rpc-redis/src/main/java/com/alibaba/dubbo/rpc/protocol/redis/RedisProtocol.java +++ b/dubbo-rpc/dubbo-rpc-redis/src/main/java/com/alibaba/dubbo/rpc/protocol/redis/RedisProtocol.java @@ -24,6 +24,7 @@ import org.apache.commons.pool.impl.GenericObjectPool; +import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; @@ -93,12 +94,15 @@ public Invoker refer(final Class type, final URL url) throws RpcExcept final String delete = url.getParameter("delete", Map.class.equals(type) ? "remove" : "delete"); return new AbstractInvoker(type, url) { protected Result doInvoke(Invocation invocation) throws Throwable { + Jedis resource = null; try { + resource = jedisPool.getResource(); + if (get.equals(invocation.getMethodName())) { if (invocation.getArguments().length != 1) { throw new IllegalArgumentException("The redis get method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); } - byte[] value = jedisPool.getResource().get(String.valueOf(invocation.getArguments()[0]).getBytes()); + byte[] value = resource.get(String.valueOf(invocation.getArguments()[0]).getBytes()); if (value == null) { return new RpcResult(); } @@ -112,21 +116,22 @@ protected Result doInvoke(Invocation invocation) throws Throwable { ByteArrayOutputStream output = new ByteArrayOutputStream(); ObjectOutput value = getSerialization(url).serialize(url, output); value.writeObject(invocation.getArguments()[1]); - jedisPool.getResource().set(key, output.toByteArray()); + resource.set(key, output.toByteArray()); if (expiry > 1000) { - jedisPool.getResource().expire(key, expiry / 1000); + resource.expire(key, expiry / 1000); } return new RpcResult(); } else if (delete.equals(invocation.getMethodName())) { if (invocation.getArguments().length != 1) { throw new IllegalArgumentException("The redis delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); } - jedisPool.getResource().del(String.valueOf(invocation.getArguments()[0]).getBytes()); + resource.del(String.valueOf(invocation.getArguments()[0]).getBytes()); return new RpcResult(); } else { throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in redis service."); } - } catch (Throwable t) { + } + catch (Throwable t) { RpcException re = new RpcException("Failed to invoke memecached service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t); if (t instanceof TimeoutException || t instanceof SocketTimeoutException) { re.setCode(RpcException.TIMEOUT_EXCEPTION); @@ -137,7 +142,18 @@ protected Result doInvoke(Invocation invocation) throws Throwable { } throw re; } + finally { + if(resource != null) { + try { + jedisPool.returnResource(resource); + } + catch (Throwable t) { + logger.warn("returnResource error: " + t.getMessage(), t); + } + } + } } + public void destroy() { super.destroy(); try { From 1ba66ceeaa54593c66622b6bb62869c1cb2e9d35 Mon Sep 17 00:00:00 2001 From: kimi Date: Tue, 14 Aug 2012 20:51:00 +0800 Subject: [PATCH 021/200] =?UTF-8?q?DUBBO-565=20client/server=20=E7=BA=BF?= =?UTF-8?q?=E7=A8=8B=E6=B1=A0=E4=B8=AD=E7=BA=BF=E7=A8=8B=E7=9A=84=E5=90=8D?= =?UTF-8?q?=E5=AD=97=E4=B8=AD=E5=B8=A6ip=E5=9C=B0=E5=9D=80=E4=BF=A1?= =?UTF-8?q?=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/common/utils/ExecutorUtil.java | 57 ++++---- .../remoting/transport/AbstractClient.java | 4 +- .../remoting/transport/mina/MinaServer.java | 81 +++++------ .../remoting/transport/netty/NettyServer.java | 3 +- .../transport/netty/ThreadNameTest.java | 134 ++++++++++++++++++ 5 files changed, 212 insertions(+), 67 deletions(-) create mode 100644 dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ThreadNameTest.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ExecutorUtil.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ExecutorUtil.java index 0de8305a5995..8c2075d1eb97 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ExecutorUtil.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ExecutorUtil.java @@ -1,18 +1,18 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.common.utils; import java.util.concurrent.Executor; @@ -21,6 +21,8 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; @@ -93,20 +95,27 @@ private static void newThreadToCloseExecutor(final ExecutorService es) { if (!isShutdown(es)) { shutdownExecutor.execute(new Runnable() { public void run() { - try { + try { for (int i=0;i<1000;i++){ - es.shutdownNow(); - if (es.awaitTermination(10, TimeUnit.MILLISECONDS)){ - break; - } + es.shutdownNow(); + if (es.awaitTermination(10, TimeUnit.MILLISECONDS)){ + break; + } } - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } catch (Throwable e) { - logger.warn(e.getMessage(), e); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } catch (Throwable e) { + logger.warn(e.getMessage(), e); } } }); } } + + public static URL setThreadName(URL url, String defaultPrefix) { + String name = url.getParameter(Constants.THREAD_NAME_KEY, defaultPrefix); + name = new StringBuilder(32).append(name).append("-").append(url.getAddress()).toString(); + url = url.removeParameter(Constants.THREAD_NAME_KEY).addParameter(Constants.THREAD_NAME_KEY, name); + return url; + } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java index 9d530f6807dd..79f695067364 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java @@ -126,8 +126,8 @@ public AbstractClient(URL url, ChannelHandler handler) throws RemotingException } protected static ChannelHandler wrapChannelHandler(URL url, ChannelHandler handler){ - url = url.addParameterIfAbsent(Constants.THREAD_NAME_KEY, CLIENT_THREAD_POOL_NAME) - .addParameterIfAbsent(Constants.THREADPOOL_KEY, Constants.DEFAULT_CLIENT_THREADPOOL); + url = ExecutorUtil.setThreadName(url, CLIENT_THREAD_POOL_NAME); + url = url.addParameterIfAbsent(Constants.THREADPOOL_KEY, Constants.DEFAULT_CLIENT_THREADPOOL); return ChannelHandlers.wrap(handler, url); } diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java index 6ea1ac21cacb..8bcd0f82d3e6 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java @@ -1,42 +1,43 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.mina; -import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Executors; - -import org.apache.mina.common.IoSession; -import org.apache.mina.common.ThreadModel; -import org.apache.mina.filter.codec.ProtocolCodecFilter; -import org.apache.mina.transport.socket.nio.SocketAcceptor; -import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.transport.AbstractServer; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelHandlers; +import java.net.InetSocketAddress; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.Executors; + +import org.apache.mina.common.IoSession; +import org.apache.mina.common.ThreadModel; +import org.apache.mina.filter.codec.ProtocolCodecFilter; +import org.apache.mina.transport.socket.nio.SocketAcceptor; +import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.ExecutorUtil; +import com.alibaba.dubbo.common.utils.NamedThreadFactory; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.transport.AbstractServer; +import com.alibaba.dubbo.remoting.transport.dispather.ChannelHandlers; /** * MinaServer @@ -45,14 +46,14 @@ * @author william.liangf * @author ding.lid */ -public class MinaServer extends AbstractServer { - +public class MinaServer extends AbstractServer { + private static final Logger logger = LoggerFactory.getLogger(MinaServer.class); private SocketAcceptor acceptor; public MinaServer(URL url, ChannelHandler handler) throws RemotingException{ - super(url, ChannelHandlers.wrap(handler, url.addParameterIfAbsent(Constants.THREAD_NAME_KEY, SERVER_THREAD_POOL_NAME))); + super(url, ChannelHandlers.wrap(handler, ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME))); } @Override diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java index ab3567b3fe96..30956b10eabb 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java @@ -33,6 +33,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.ExecutorUtil; import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.remoting.Channel; @@ -59,7 +60,7 @@ public class NettyServer extends AbstractServer implements Server { private org.jboss.netty.channel.Channel channel; public NettyServer(URL url, ChannelHandler handler) throws RemotingException{ - super(url, ChannelHandlers.wrap(handler, url.addParameterIfAbsent(Constants.THREAD_NAME_KEY, SERVER_THREAD_POOL_NAME))); + super(url, ChannelHandlers.wrap(handler, ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME))); } @Override diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ThreadNameTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ThreadNameTest.java new file mode 100644 index 000000000000..377fbb450152 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/netty/ThreadNameTest.java @@ -0,0 +1,134 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.transport.netty; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.RemotingException; + +/** + * @author kimi + */ +public class ThreadNameTest { + + private NettyServer server; + private NettyClient client; + + private URL serverURL; + private URL clientURL; + + private ThreadNameVerifyHandler serverHandler; + private ThreadNameVerifyHandler clientHandler; + + @Before + public void before() throws Exception { + int port = 55555; + serverURL = URL.valueOf("netty://localhost").setPort(port); + clientURL = URL.valueOf("netty://localhost").setPort(port); + + serverHandler = new ThreadNameVerifyHandler(String.valueOf(port), false); + clientHandler = new ThreadNameVerifyHandler(String.valueOf(port), true); + + server = new NettyServer(serverURL, serverHandler); + client = new NettyClient(clientURL, clientHandler); + } + + @After + public void after() throws Exception { + if (client != null) { + client.close(); + client = null; + } + + if (server != null) { + server.close(); + server = null; + } + } + + @Test + public void testThreadName() throws Exception { + client.send("hello"); + Thread.sleep(1000L * 5L); + if (!serverHandler.isSuccess() || !clientHandler.isSuccess()) { + Assert.fail(); + } + } + + class ThreadNameVerifyHandler implements ChannelHandler { + + private String message; + private boolean success; + private boolean client; + + public boolean isSuccess() { + return success; + } + + ThreadNameVerifyHandler(String msg, boolean client) { + message = msg; + this.client = client; + } + + private void checkThreadName() { + if (!success) { + success = Thread.currentThread().getName().contains(message); + } + } + + private void output(String method) { + System.out.println(Thread.currentThread().getName() + + " " + (client ? "client " + method : "server " + method)); + } + + @Override + public void connected(Channel channel) throws RemotingException { + output("connected"); + checkThreadName(); + } + + @Override + public void disconnected(Channel channel) throws RemotingException { + output("disconnected"); + checkThreadName(); + } + + @Override + public void sent(Channel channel, Object message) throws RemotingException { + output("sent"); + checkThreadName(); + } + + @Override + public void received(Channel channel, Object message) throws RemotingException { + output("received"); + checkThreadName(); + } + + @Override + public void caught(Channel channel, Throwable exception) throws RemotingException { + output("caught"); + checkThreadName(); + } + } + +} \ No newline at end of file From 0cdf517bdc4aa39f610dd28b76fe0678a10383f3 Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Wed, 15 Aug 2012 18:56:49 +0800 Subject: [PATCH 022/200] =?UTF-8?q?DUBBO-568=20=E9=85=8D=E7=BD=AE=E9=A1=B9?= =?UTF-8?q?dispather=E5=8D=95=E8=AF=8D=E6=8B=BC=E5=86=99=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/config/ProtocolConfig.java | 28 +++++++++++++++---- .../alibaba/dubbo/config/ProviderConfig.java | 4 +-- .../src/main/resources/META-INF/dubbo.xsd | 14 ++++++++-- .../{Dispather.java => Dispatcher.java} | 2 +- .../transport/dispather/ChannelHandlers.java | 4 +-- .../transport/dispather/all/AllDispather.java | 4 +-- .../ConnectionOrderedDispather.java | 4 +-- .../dispather/direct/DirectDispather.java | 4 +-- .../execution/ExecutionDispather.java | 4 +-- .../message/MessageOnlyDispather.java | 4 +-- ... => com.alibaba.dubbo.remoting.Dispatcher} | 0 .../dispather/FakeChannelHandlers.java | 4 +-- dubbo/pom.xml | 2 +- 13 files changed, 53 insertions(+), 25 deletions(-) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/{Dispather.java => Dispatcher.java} (97%) rename dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/{com.alibaba.dubbo.remoting.Dispather => com.alibaba.dubbo.remoting.Dispatcher} (100%) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java index abbf7ad66432..cb24f4b462cb 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java @@ -23,7 +23,7 @@ import com.alibaba.dubbo.common.threadpool.ThreadPool; import com.alibaba.dubbo.config.support.Parameter; import com.alibaba.dubbo.registry.support.AbstractRegistryFactory; -import com.alibaba.dubbo.remoting.Dispather; +import com.alibaba.dubbo.remoting.Dispatcher; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.Transporter; import com.alibaba.dubbo.remoting.exchange.Exchanger; @@ -95,7 +95,7 @@ public class ProtocolConfig extends AbstractConfig { private String exchanger; // 淇℃伅绾跨▼妯″瀷娲惧彂鏂瑰紡 - private String dispather; + private String dispatcher; // 瀵圭О缃戠粶缁勭綉鏂瑰紡 private String networker; @@ -367,13 +367,31 @@ public void setExchanger(String exchanger) { this.exchanger = exchanger; } + /** + * 鍗曡瘝鎷煎啓閿欒锛岃浣跨敤getDispatcher() + * @deprecated {@link #getDispatcher()} + */ + @Deprecated public String getDispather() { - return dispather; + return getDispatcher(); } + /** + * 鍗曡瘝鎷煎啓閿欒锛岃浣跨敤setDispatcher() + * @deprecated {@link #setDispatcher(String)} + */ + @Deprecated public void setDispather(String dispather) { - checkExtension(Dispather.class, "dispather", exchanger); - this.dispather = dispather; + setDispatcher(dispather); + } + + public String getDispatcher() { + return dispatcher; + } + + public void setDispatcher(String dispatcher) { + checkExtension(Dispatcher.class, "dispacther", dispatcher); + this.dispatcher = dispatcher; } public String getNetworker() { diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java index 8251fda87753..915544243e93 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java @@ -20,7 +20,7 @@ import com.alibaba.dubbo.common.status.StatusChecker; import com.alibaba.dubbo.common.threadpool.ThreadPool; import com.alibaba.dubbo.config.support.Parameter; -import com.alibaba.dubbo.remoting.Dispather; +import com.alibaba.dubbo.remoting.Dispatcher; import com.alibaba.dubbo.remoting.Transporter; import com.alibaba.dubbo.remoting.exchange.Exchanger; import com.alibaba.dubbo.remoting.telnet.TelnetHandler; @@ -348,7 +348,7 @@ public String getDispather() { } public void setDispather(String dispather) { - checkExtension(Dispather.class, "dispather", exchanger); + checkExtension(Dispatcher.class, "dispather", exchanger); this.dispather = dispather; } diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index cccbb79b899b..633046bd5d52 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -825,7 +825,12 @@ - + + + + + + @@ -945,7 +950,12 @@ - + + + + + + diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java similarity index 97% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispather.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java index 03e05e885975..c7c1bb156d06 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java @@ -27,7 +27,7 @@ * @author chao.liuc */ @SPI(AllDispather.NAME) -public interface Dispather { +public interface Dispatcher { /** * dispath. diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/ChannelHandlers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/ChannelHandlers.java index 3c4b76e1fe8b..2458d0910887 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/ChannelHandlers.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/ChannelHandlers.java @@ -19,7 +19,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispather; +import com.alibaba.dubbo.remoting.Dispatcher; import com.alibaba.dubbo.remoting.exchange.support.header.HeartbeatHandler; import com.alibaba.dubbo.remoting.transport.MultiMessageHandler; @@ -36,7 +36,7 @@ public static ChannelHandler wrap(ChannelHandler handler, URL url){ protected ChannelHandlers() {} protected ChannelHandler wrapInternal(ChannelHandler handler, URL url) { - return new MultiMessageHandler(new HeartbeatHandler(ExtensionLoader.getExtensionLoader(Dispather.class) + return new MultiMessageHandler(new HeartbeatHandler(ExtensionLoader.getExtensionLoader(Dispatcher.class) .getAdaptiveExtension().dispath(handler, url))); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/all/AllDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/all/AllDispather.java index a5f77edbb47d..b3b3d1387b30 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/all/AllDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/all/AllDispather.java @@ -17,14 +17,14 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispather; +import com.alibaba.dubbo.remoting.Dispatcher; /** * 榛樿鐨勭嚎绋嬫睜閰嶇疆 * * @author chao.liuc */ -public class AllDispather implements Dispather { +public class AllDispather implements Dispatcher { public static final String NAME = "all"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/connection/ConnectionOrderedDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/connection/ConnectionOrderedDispather.java index 882429988dc7..766126ebbaec 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/connection/ConnectionOrderedDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/connection/ConnectionOrderedDispather.java @@ -17,14 +17,14 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispather; +import com.alibaba.dubbo.remoting.Dispatcher; /** * connect disconnect 淇濊瘉椤哄簭. * * @author chao.liuc */ -public class ConnectionOrderedDispather implements Dispather { +public class ConnectionOrderedDispather implements Dispatcher { public static final String NAME = "connection"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/direct/DirectDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/direct/DirectDispather.java index 5edbfb7a3415..54231e6acdaa 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/direct/DirectDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/direct/DirectDispather.java @@ -17,14 +17,14 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispather; +import com.alibaba.dubbo.remoting.Dispatcher; /** * 涓嶆淳鍙戠嚎绋嬫睜銆 * * @author chao.liuc */ -public class DirectDispather implements Dispather { +public class DirectDispather implements Dispatcher { public static final String NAME = "direct"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/execution/ExecutionDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/execution/ExecutionDispather.java index 64f0901aeead..0d80a78bd20e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/execution/ExecutionDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/execution/ExecutionDispather.java @@ -17,14 +17,14 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispather; +import com.alibaba.dubbo.remoting.Dispatcher; /** * 闄ゅ彂閫佸叏閮ㄤ娇鐢ㄧ嚎绋嬫睜澶勭悊 * * @author chao.liuc */ -public class ExecutionDispather implements Dispather { +public class ExecutionDispather implements Dispatcher { public static final String NAME = "execution"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/message/MessageOnlyDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/message/MessageOnlyDispather.java index 574e8ea1ff31..d41e3dd25d50 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/message/MessageOnlyDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/message/MessageOnlyDispather.java @@ -17,14 +17,14 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispather; +import com.alibaba.dubbo.remoting.Dispatcher; /** * 鍙湁message receive浣跨敤绾跨▼姹. * * @author chao.liuc */ -public class MessageOnlyDispather implements Dispather { +public class MessageOnlyDispather implements Dispatcher { public static final String NAME = "message"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispather b/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher similarity index 100% rename from dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispather rename to dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispather/FakeChannelHandlers.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispather/FakeChannelHandlers.java index bab013e67f97..6fc14f3977b3 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispather/FakeChannelHandlers.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispather/FakeChannelHandlers.java @@ -19,7 +19,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispather; +import com.alibaba.dubbo.remoting.Dispatcher; /** * @author kimi @@ -32,7 +32,7 @@ public FakeChannelHandlers() { @Override protected ChannelHandler wrapInternal(ChannelHandler handler, URL url) { - return ExtensionLoader.getExtensionLoader(Dispather.class) + return ExtensionLoader.getExtensionLoader(Dispatcher.class) .getAdaptiveExtension().dispath(handler, url); } diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 188430bfe914..b4bc0ff0428d 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -368,7 +368,7 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispather + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher From 788f373183523f1ef6bcf53127accef20d42f1cd Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Wed, 15 Aug 2012 19:09:40 +0800 Subject: [PATCH 023/200] =?UTF-8?q?DUBBO-568=20=E9=85=8D=E7=BD=AE=E9=A1=B9?= =?UTF-8?q?dispather=E5=8D=95=E8=AF=8D=E6=8B=BC=E5=86=99=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/com/alibaba/dubbo/common/Constants.java | 2 +- .../src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java | 2 +- .../java/com/alibaba/dubbo/remoting/PerformanceServerTest.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java index 82af4beb9461..718287ee0e2e 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -324,7 +324,7 @@ public class Constants { public static final String HESSIAN_VERSION_KEY = "hessian.version"; - public static final String DISPATHER_KEY = "dispather"; + public static final String DISPATCHER_KEY = "dispatcher"; public static final String CHANNEL_HANDLER_KEY = "channel.handler"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java index c7c1bb156d06..d8da98ef99c1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java @@ -36,7 +36,7 @@ public interface Dispatcher { * @param url * @return channel handler */ - @Adaptive({Constants.DISPATHER_KEY, Constants.CHANNEL_HANDLER_KEY}) + @Adaptive({Constants.DISPATCHER_KEY, "dispather", "channel.handler"}) // 鍚庝袱涓弬鏁颁负鍏煎鏃ч厤缃 ChannelHandler dispath(ChannelHandler handler, URL url); } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java index 3d117a7844b1..4a17bac97326 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java @@ -88,7 +88,7 @@ private static ExchangeServer statServer() throws Exception{ final int threads = PerformanceUtils.getIntProperty(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); final int iothreads = PerformanceUtils.getIntProperty(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS); final int buffer = PerformanceUtils.getIntProperty(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); - final String channelHandler = PerformanceUtils.getProperty(Constants.CHANNEL_HANDLER_KEY, ExecutionDispather.NAME); + final String channelHandler = PerformanceUtils.getProperty(Constants.DISPATCHER_KEY, ExecutionDispather.NAME); // 鍚姩鏈嶅姟鍣 From 220aa6d289a23f97b955242bc7b34e9f977689fc Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Wed, 15 Aug 2012 19:12:52 +0800 Subject: [PATCH 024/200] =?UTF-8?q?DUBBO-568=20-=20=E9=85=8D=E7=BD=AE?= =?UTF-8?q?=E9=A1=B9dispather=E5=8D=95=E8=AF=8D=E6=8B=BC=E5=86=99=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/dubbo/remoting/Dispatcher.java | 6 +++--- .../dubbo/remoting/transport/AbstractClient.java | 2 +- .../dubbo/remoting/transport/AbstractServer.java | 2 +- .../ChannelEventRunnable.java | 2 +- .../{dispather => dispatcher}/ChannelHandlers.java | 4 ++-- .../WrappedChannelHandler.java | 2 +- .../all/AllChannelHandler.java | 8 ++++---- .../{dispather => dispatcher}/all/AllDispather.java | 4 ++-- .../connection/ConnectionOrderedChannelHandler.java | 8 ++++---- .../connection/ConnectionOrderedDispather.java | 4 ++-- .../direct/DirectDispather.java | 4 ++-- .../execution/ExecutionChannelHandler.java | 8 ++++---- .../execution/ExecutionDispather.java | 4 ++-- .../message/MessageOnlyChannelHandler.java | 8 ++++---- .../message/MessageOnlyDispather.java | 4 ++-- .../internal/com.alibaba.dubbo.remoting.Dispatcher | 10 +++++----- .../alibaba/dubbo/remoting/PerformanceServerTest.java | 2 +- .../remoting/handler/ConnectChannelHandlerTest.java | 2 +- .../remoting/handler/WrappedChannelHandlerTest.java | 2 +- .../dubbo/remoting/transport/mina/MinaServer.java | 2 +- .../dubbo/remoting/transport/netty/NettyServer.java | 2 +- .../transport/dispather/FakeChannelHandlers.java | 3 ++- 22 files changed, 47 insertions(+), 46 deletions(-) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/ChannelEventRunnable.java (95%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/ChannelHandlers.java (95%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/WrappedChannelHandler.java (98%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/all/AllChannelHandler.java (90%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/all/AllDispather.java (86%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/connection/ConnectionOrderedChannelHandler.java (93%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/connection/ConnectionOrderedDispather.java (86%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/direct/DirectDispather.java (86%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/execution/ExecutionChannelHandler.java (84%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/execution/ExecutionDispather.java (86%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/message/MessageOnlyChannelHandler.java (83%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/message/MessageOnlyDispather.java (86%) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java index d8da98ef99c1..92228f3e0f77 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java @@ -19,7 +19,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.Adaptive; import com.alibaba.dubbo.common.extension.SPI; -import com.alibaba.dubbo.remoting.transport.dispather.all.AllDispather; +import com.alibaba.dubbo.remoting.transport.dispatcher.all.AllDispather; /** * ChannelHandlerWrapper (SPI, Singleton, ThreadSafe) @@ -30,13 +30,13 @@ public interface Dispatcher { /** - * dispath. + * dispatch the message to threadpool. * * @param handler * @param url * @return channel handler */ @Adaptive({Constants.DISPATCHER_KEY, "dispather", "channel.handler"}) // 鍚庝袱涓弬鏁颁负鍏煎鏃ч厤缃 - ChannelHandler dispath(ChannelHandler handler, URL url); + ChannelHandler dispatch(ChannelHandler handler, URL url); } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java index 79f695067364..8bbd54662d9f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java @@ -40,7 +40,7 @@ import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.Client; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelHandlers; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers; /** * AbstractClient diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java index 8fa514f67773..7ab2871c2ed3 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractServer.java @@ -30,7 +30,7 @@ import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.Server; -import com.alibaba.dubbo.remoting.transport.dispather.WrappedChannelHandler; +import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; /** * AbstractServer diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/ChannelEventRunnable.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java similarity index 95% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/ChannelEventRunnable.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java index 79344433df69..f0976d34f63e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/ChannelEventRunnable.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelEventRunnable.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather; +package com.alibaba.dubbo.remoting.transport.dispatcher; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/ChannelHandlers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelHandlers.java similarity index 95% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/ChannelHandlers.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelHandlers.java index 2458d0910887..5590d7b543b2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/ChannelHandlers.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/ChannelHandlers.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather; +package com.alibaba.dubbo.remoting.transport.dispatcher; import com.alibaba.dubbo.common.URL; @@ -37,7 +37,7 @@ protected ChannelHandlers() {} protected ChannelHandler wrapInternal(ChannelHandler handler, URL url) { return new MultiMessageHandler(new HeartbeatHandler(ExtensionLoader.getExtensionLoader(Dispatcher.class) - .getAdaptiveExtension().dispath(handler, url))); + .getAdaptiveExtension().dispatch(handler, url))); } private static ChannelHandlers INSTANCE = new ChannelHandlers(); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/WrappedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java similarity index 98% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/WrappedChannelHandler.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java index ccaba8c6a2ab..4ba418f9c501 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/WrappedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/WrappedChannelHandler.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather; +package com.alibaba.dubbo.remoting.transport.dispatcher; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/all/AllChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java similarity index 90% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/all/AllChannelHandler.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java index 6103e951cc87..1268cdb14188 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/all/AllChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllChannelHandler.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather.all; +package com.alibaba.dubbo.remoting.transport.dispatcher.all; import java.util.concurrent.ExecutorService; @@ -22,9 +22,9 @@ import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.ExecutionException; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelEventRunnable; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelEventRunnable.ChannelState; -import com.alibaba.dubbo.remoting.transport.dispather.WrappedChannelHandler; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; +import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; public class AllChannelHandler extends WrappedChannelHandler { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/all/AllDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispather.java similarity index 86% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/all/AllDispather.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispather.java index b3b3d1387b30..c6be973d0c20 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/all/AllDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispather.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather.all; +package com.alibaba.dubbo.remoting.transport.dispatcher.all; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; @@ -28,7 +28,7 @@ public class AllDispather implements Dispatcher { public static final String NAME = "all"; - public ChannelHandler dispath(ChannelHandler handler, URL url) { + public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new AllChannelHandler(handler, url); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/connection/ConnectionOrderedChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java similarity index 93% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/connection/ConnectionOrderedChannelHandler.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java index 5b72097635e9..4dff6d5a3d1f 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/connection/ConnectionOrderedChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedChannelHandler.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather.connection; +package com.alibaba.dubbo.remoting.transport.dispatcher.connection; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; @@ -28,9 +28,9 @@ import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.ExecutionException; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelEventRunnable; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelEventRunnable.ChannelState; -import com.alibaba.dubbo.remoting.transport.dispather.WrappedChannelHandler; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; +import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; public class ConnectionOrderedChannelHandler extends WrappedChannelHandler { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/connection/ConnectionOrderedDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispather.java similarity index 86% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/connection/ConnectionOrderedDispather.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispather.java index 766126ebbaec..2b8b55ad57e5 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/connection/ConnectionOrderedDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispather.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather.connection; +package com.alibaba.dubbo.remoting.transport.dispatcher.connection; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; @@ -28,7 +28,7 @@ public class ConnectionOrderedDispather implements Dispatcher { public static final String NAME = "connection"; - public ChannelHandler dispath(ChannelHandler handler, URL url) { + public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new ConnectionOrderedChannelHandler(handler, url); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/direct/DirectDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispather.java similarity index 86% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/direct/DirectDispather.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispather.java index 54231e6acdaa..bb141a4de445 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/direct/DirectDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispather.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather.direct; +package com.alibaba.dubbo.remoting.transport.dispatcher.direct; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; @@ -28,7 +28,7 @@ public class DirectDispather implements Dispatcher { public static final String NAME = "direct"; - public ChannelHandler dispath(ChannelHandler handler, URL url) { + public ChannelHandler dispatch(ChannelHandler handler, URL url) { return handler; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/execution/ExecutionChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionChannelHandler.java similarity index 84% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/execution/ExecutionChannelHandler.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionChannelHandler.java index 48334c386d7d..ffe113a87acc 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/execution/ExecutionChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionChannelHandler.java @@ -13,15 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather.execution; +package com.alibaba.dubbo.remoting.transport.dispatcher.execution; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelEventRunnable; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelEventRunnable.ChannelState; -import com.alibaba.dubbo.remoting.transport.dispather.WrappedChannelHandler; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; +import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; public class ExecutionChannelHandler extends WrappedChannelHandler { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/execution/ExecutionDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispather.java similarity index 86% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/execution/ExecutionDispather.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispather.java index 0d80a78bd20e..36e86c91f7b9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/execution/ExecutionDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispather.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather.execution; +package com.alibaba.dubbo.remoting.transport.dispatcher.execution; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; @@ -28,7 +28,7 @@ public class ExecutionDispather implements Dispatcher { public static final String NAME = "execution"; - public ChannelHandler dispath(ChannelHandler handler, URL url) { + public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new ExecutionChannelHandler(handler, url); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/message/MessageOnlyChannelHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java similarity index 83% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/message/MessageOnlyChannelHandler.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java index 7af07a2fb4ed..19a112970f2a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/message/MessageOnlyChannelHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyChannelHandler.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather.message; +package com.alibaba.dubbo.remoting.transport.dispatcher.message; import java.util.concurrent.ExecutorService; @@ -22,9 +22,9 @@ import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.ExecutionException; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelEventRunnable; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelEventRunnable.ChannelState; -import com.alibaba.dubbo.remoting.transport.dispather.WrappedChannelHandler; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable; +import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelEventRunnable.ChannelState; public class MessageOnlyChannelHandler extends WrappedChannelHandler { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/message/MessageOnlyDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispather.java similarity index 86% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/message/MessageOnlyDispather.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispather.java index d41e3dd25d50..b00db8995a33 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispather/message/MessageOnlyDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispather.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather.message; +package com.alibaba.dubbo.remoting.transport.dispatcher.message; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.ChannelHandler; @@ -28,7 +28,7 @@ public class MessageOnlyDispather implements Dispatcher { public static final String NAME = "message"; - public ChannelHandler dispath(ChannelHandler handler, URL url) { + public ChannelHandler dispatch(ChannelHandler handler, URL url) { return new MessageOnlyChannelHandler(handler, url); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher b/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher index 3eeb5d95020e..f4e576922898 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher +++ b/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher @@ -1,5 +1,5 @@ -all=com.alibaba.dubbo.remoting.transport.dispather.all.AllDispather -direct=com.alibaba.dubbo.remoting.transport.dispather.direct.DirectDispather -message=com.alibaba.dubbo.remoting.transport.dispather.message.MessageOnlyDispather -execution=com.alibaba.dubbo.remoting.transport.dispather.execution.ExecutionDispather -connection=com.alibaba.dubbo.remoting.transport.dispather.connection.ConnectionOrderedDispather \ No newline at end of file +all=com.alibaba.dubbo.remoting.transport.dispatcher.all.AllDispather +direct=com.alibaba.dubbo.remoting.transport.dispatcher.direct.DirectDispather +message=com.alibaba.dubbo.remoting.transport.dispatcher.message.MessageOnlyDispather +execution=com.alibaba.dubbo.remoting.transport.dispatcher.execution.ExecutionDispather +connection=com.alibaba.dubbo.remoting.transport.dispatcher.connection.ConnectionOrderedDispather \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java index 4a17bac97326..0654f813ed5b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java @@ -29,7 +29,7 @@ import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.Exchangers; import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import com.alibaba.dubbo.remoting.transport.dispather.execution.ExecutionDispather; +import com.alibaba.dubbo.remoting.transport.dispatcher.execution.ExecutionDispather; /** * PerformanceServer diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java index fae3dc832f45..3155ecb50d9b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/ConnectChannelHandlerTest.java @@ -28,7 +28,7 @@ import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; -import com.alibaba.dubbo.remoting.transport.dispather.connection.ConnectionOrderedChannelHandler; +import com.alibaba.dubbo.remoting.transport.dispatcher.connection.ConnectionOrderedChannelHandler; diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/WrappedChannelHandlerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/WrappedChannelHandlerTest.java index dc981a49094c..b086bf353773 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/WrappedChannelHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/handler/WrappedChannelHandlerTest.java @@ -28,7 +28,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.transport.dispather.WrappedChannelHandler; +import com.alibaba.dubbo.remoting.transport.dispatcher.WrappedChannelHandler; public class WrappedChannelHandlerTest { WrappedChannelHandler handler ; diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java index 8bcd0f82d3e6..b0191c6d50a0 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaServer.java @@ -37,7 +37,7 @@ import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.transport.AbstractServer; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelHandlers; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers; /** * MinaServer diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java index 30956b10eabb..af006355f9d8 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java @@ -41,7 +41,7 @@ import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.Server; import com.alibaba.dubbo.remoting.transport.AbstractServer; -import com.alibaba.dubbo.remoting.transport.dispather.ChannelHandlers; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers; /** * NettyServer diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispather/FakeChannelHandlers.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispather/FakeChannelHandlers.java index 6fc14f3977b3..dc91e033e147 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispather/FakeChannelHandlers.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispather/FakeChannelHandlers.java @@ -20,6 +20,7 @@ import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.Dispatcher; +import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers; /** * @author kimi @@ -33,7 +34,7 @@ public FakeChannelHandlers() { @Override protected ChannelHandler wrapInternal(ChannelHandler handler, URL url) { return ExtensionLoader.getExtensionLoader(Dispatcher.class) - .getAdaptiveExtension().dispath(handler, url); + .getAdaptiveExtension().dispatch(handler, url); } public static void setTestingChannelHandlers() { From 4793ef2d9b9f6cf40cac5164b33f84fb7ac2d0d4 Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 16 Aug 2012 11:44:48 +0800 Subject: [PATCH 025/200] =?UTF-8?q?DUBBO-558=20=E5=BA=94=E7=94=A8=E4=B8=AD?= =?UTF-8?q?DubboClientHandler-thread=E5=A4=AA=E5=A4=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rpc/cluster/support/ClusterUtils.java | 15 +++- .../rpc/cluster/support/ClusterUtilsTest.java | 81 +++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) create mode 100644 dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtilsTest.java diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtils.java index 646329edf86c..76b6ff6b74e9 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtils.java @@ -38,10 +38,23 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { //绾跨▼姹犻厤缃笉浣跨敤鎻愪緵鑰呯殑 map.remove(Constants.THREAD_NAME_KEY); + map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.THREAD_NAME_KEY); + map.remove(Constants.CORE_THREADS_KEY); + map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.CORE_THREADS_KEY); + map.remove(Constants.THREADS_KEY); + map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.THREADS_KEY); + map.remove(Constants.QUEUES_KEY); + map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.QUEUES_KEY); + map.remove(Constants.ALIVE_KEY); + map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.ALIVE_KEY); + + map.remove(Constants.THREADPOOL_KEY); + map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.THREADPOOL_KEY); + } if (localMap != null && localMap.size() > 0) { @@ -79,7 +92,7 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { localMap.put(Constants.INVOKER_LISTENER_KEY, remoteListener + "," + localListener); } } - return remoteUrl.addParameters(map); + return remoteUrl.removeParameters(remoteUrl.getParameters().keySet()).addParameters(map); } private ClusterUtils() {} diff --git a/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtilsTest.java b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtilsTest.java new file mode 100644 index 000000000000..87d046c1865e --- /dev/null +++ b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtilsTest.java @@ -0,0 +1,81 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.cluster.support; + +import org.junit.Assert; +import org.junit.Test; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; + +/** + * @author kimi + */ +public class ClusterUtilsTest { + + @Test + public void testMergeUrl() throws Exception { + URL providerURL = URL.valueOf("dubbo://localhost:55555"); + providerURL = providerURL.setPath("path") + .setUsername("username") + .setPassword("password"); + + providerURL = providerURL.addParameter(Constants.GROUP_KEY, "dubbo") + .addParameter(Constants.VERSION_KEY, "1.2.3") + .addParameter(Constants.DUBBO_VERSION_KEY, "2.3.7") + .addParameter(Constants.THREADPOOL_KEY, "fixed") + .addParameter(Constants.THREADS_KEY, Integer.MAX_VALUE) + .addParameter(Constants.THREAD_NAME_KEY, "test") + .addParameter(Constants.CORE_THREADS_KEY, Integer.MAX_VALUE) + .addParameter(Constants.QUEUES_KEY, Integer.MAX_VALUE) + .addParameter(Constants.ALIVE_KEY, Integer.MAX_VALUE) + .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADS_KEY, Integer.MAX_VALUE) + .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADPOOL_KEY, "fixed") + .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.CORE_THREADS_KEY, Integer.MAX_VALUE) + .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.QUEUES_KEY, Integer.MAX_VALUE) + .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.ALIVE_KEY, Integer.MAX_VALUE) + .addParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREAD_NAME_KEY, "test"); + + URL consumerURL = URL.valueOf("dubbo://localhost:55555"); + consumerURL = consumerURL.addParameter(Constants.PID_KEY, "1234"); + + URL url = ClusterUtils.mergeUrl(providerURL, consumerURL.getParameters()); + + Assert.assertFalse(url.hasParameter(Constants.THREADS_KEY)); + Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADS_KEY)); + + Assert.assertFalse(url.hasParameter(Constants.THREADPOOL_KEY)); + Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADPOOL_KEY)); + + Assert.assertFalse(url.hasParameter(Constants.CORE_THREADS_KEY)); + Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.CORE_THREADS_KEY)); + + Assert.assertFalse(url.hasParameter(Constants.QUEUES_KEY)); + Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.QUEUES_KEY)); + + Assert.assertFalse(url.hasParameter(Constants.ALIVE_KEY)); + Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.ALIVE_KEY)); + + Assert.assertFalse(url.hasParameter(Constants.THREAD_NAME_KEY)); + Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREAD_NAME_KEY)); + + Assert.assertEquals(url.getPath(), "path"); + Assert.assertEquals(url.getUsername(), "username"); + Assert.assertEquals(url.getPassword(), "password"); + Assert.assertEquals(url.getParameter(Constants.PID_KEY), "1234"); + } + +} From ee4710d5be58e0938f1082e7b9f4e0a5f185ce28 Mon Sep 17 00:00:00 2001 From: oldrat Date: Thu, 16 Aug 2012 12:26:44 +0800 Subject: [PATCH 026/200] =?UTF-8?q?DUBBO-558=20=E5=BA=94=E7=94=A8=E4=B8=AD?= =?UTF-8?q?DubboClientHandler-thread=E5=A4=AA=E5=A4=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/rpc/cluster/support/ClusterUtils.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtils.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtils.java index 76b6ff6b74e9..9d31824b0979 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtils.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtils.java @@ -40,6 +40,9 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { map.remove(Constants.THREAD_NAME_KEY); map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.THREAD_NAME_KEY); + map.remove(Constants.THREADPOOL_KEY); + map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.THREADPOOL_KEY); + map.remove(Constants.CORE_THREADS_KEY); map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.CORE_THREADS_KEY); @@ -51,10 +54,6 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { map.remove(Constants.ALIVE_KEY); map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.ALIVE_KEY); - - map.remove(Constants.THREADPOOL_KEY); - map.remove(Constants.DEFAULT_KEY_PREFIX + Constants.THREADPOOL_KEY); - } if (localMap != null && localMap.size() > 0) { @@ -92,7 +91,8 @@ public static URL mergeUrl(URL remoteUrl, Map localMap) { localMap.put(Constants.INVOKER_LISTENER_KEY, remoteListener + "," + localListener); } } - return remoteUrl.removeParameters(remoteUrl.getParameters().keySet()).addParameters(map); + + return remoteUrl.clearParameters().addParameters(map); } private ClusterUtils() {} From 12c5c855b2e6d5dde3c77d07a44cb04f5ba22e4d Mon Sep 17 00:00:00 2001 From: oldrat Date: Thu, 16 Aug 2012 14:09:43 +0800 Subject: [PATCH 027/200] =?UTF-8?q?DUBBO-558=20=E5=BA=94=E7=94=A8=E4=B8=AD?= =?UTF-8?q?DubboClientHandler-thread=E5=A4=AA=E5=A4=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/rpc/cluster/support/ClusterUtilsTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtilsTest.java b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtilsTest.java index 87d046c1865e..4c7e51a1f939 100644 --- a/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtilsTest.java +++ b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/support/ClusterUtilsTest.java @@ -51,13 +51,13 @@ public void testMergeUrl() throws Exception { URL consumerURL = URL.valueOf("dubbo://localhost:55555"); consumerURL = consumerURL.addParameter(Constants.PID_KEY, "1234"); + consumerURL = consumerURL.addParameter(Constants.THREADPOOL_KEY, "foo"); URL url = ClusterUtils.mergeUrl(providerURL, consumerURL.getParameters()); Assert.assertFalse(url.hasParameter(Constants.THREADS_KEY)); Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADS_KEY)); - Assert.assertFalse(url.hasParameter(Constants.THREADPOOL_KEY)); Assert.assertFalse(url.hasParameter(Constants.DEFAULT_KEY_PREFIX + Constants.THREADPOOL_KEY)); Assert.assertFalse(url.hasParameter(Constants.CORE_THREADS_KEY)); @@ -76,6 +76,7 @@ public void testMergeUrl() throws Exception { Assert.assertEquals(url.getUsername(), "username"); Assert.assertEquals(url.getPassword(), "password"); Assert.assertEquals(url.getParameter(Constants.PID_KEY), "1234"); + Assert.assertEquals(url.getParameter(Constants.THREADPOOL_KEY), "foo"); } } From 2a1fb35598b089da66b257c350b0f0f2749182ed Mon Sep 17 00:00:00 2001 From: kimi Date: Fri, 17 Aug 2012 12:29:40 +0800 Subject: [PATCH 028/200] =?UTF-8?q?DUBBO-560=20=E6=9C=8D=E5=8A=A1=E6=8F=90?= =?UTF-8?q?=E4=BE=9B=E6=96=B9=E5=85=B3=E9=97=AD=E6=97=B6=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E6=8F=90=E4=BE=9B=E6=96=B9=E5=8F=AF=E8=83=BD=E4=BC=9A=E4=B8=B4?= =?UTF-8?q?=E6=97=B6=E5=87=BA=E7=8E=B0=E6=9C=8D=E5=8A=A1=E6=89=BE=E4=B8=8D?= =?UTF-8?q?=E5=88=B0=E7=9A=84=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java index 46ae68ceda9f..f413af6fca50 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocol.java @@ -385,7 +385,6 @@ private ExchangeClient initClient(URL url) { } public void destroy() { - super.destroy(); for (String key : new ArrayList(serverMap.keySet())) { ExchangeServer server = serverMap.remove(key); if (server != null) { @@ -428,5 +427,6 @@ public void destroy() { } } stubServiceMethodsMap.clear(); + super.destroy(); } } \ No newline at end of file From 693c2d09e0f5dc65a6420fb673567a47c3b24855 Mon Sep 17 00:00:00 2001 From: kimi Date: Mon, 20 Aug 2012 10:54:07 +0800 Subject: [PATCH 029/200] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95=EF=BC=8C=E6=B5=8B=E8=AF=95=20PojoUtils=20?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E8=83=BD=E6=AD=A3=E7=A1=AE=E5=A4=84=E7=90=86?= =?UTF-8?q?=20list=20->=20pojo=20->=20list=20->=20pojo=20=E8=BF=99?= =?UTF-8?q?=E7=A7=8D=E7=B1=BB=E5=9E=8B=E7=9A=84=E5=AF=B9=E8=B1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/common/utils/PojoUtilsTest.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/utils/PojoUtilsTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/utils/PojoUtilsTest.java index bd0f88cf4999..7e4d04502fc0 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/utils/PojoUtilsTest.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/utils/PojoUtilsTest.java @@ -636,6 +636,45 @@ public void testPojoList() throws Exception { Assert.assertEquals(parent.getAge(), realizeParent.getAge()); } + @Test + public void testListPojoListPojo() throws Exception { + InnerPojo parentList = new InnerPojo(); + Parent parent = new Parent(); + parent.setName("zhangsan"); + parent.setAge(Integer.MAX_VALUE); + parentList.setList(Arrays.asList(parent)); + + ListResult> list = new ListResult>(); + list.setResult(Arrays.asList(parentList)); + + Object generializeObject = PojoUtils.generalize(list); + Object realizeObject = PojoUtils.realize(generializeObject, ListResult.class); + + Assert.assertTrue(realizeObject instanceof ListResult); + ListResult realizeList = (ListResult)realizeObject; + List realizeInnerList = realizeList.getResult(); + Assert.assertEquals(1, realizeInnerList.size()); + Assert.assertTrue(realizeInnerList.get(0) instanceof InnerPojo); + InnerPojo realizeParentList = (InnerPojo)realizeInnerList.get(0); + Assert.assertEquals(1, realizeParentList.getList().size()); + Assert.assertTrue(realizeParentList.getList().get(0) instanceof Parent); + Parent realizeParent = (Parent)realizeParentList.getList().get(0); + Assert.assertEquals(parent.getName(), realizeParent.getName()); + Assert.assertEquals(parent.getAge(), realizeParent.getAge()); + } + + public static class InnerPojo { + private List list; + + public List getList() { + return list; + } + + public void setList(List list) { + this.list = list; + } + } + public static class ListResult { List result; From 8711f9581ab835e75fa89d369e02b815f71487cf Mon Sep 17 00:00:00 2001 From: oldrat Date: Thu, 16 Aug 2012 15:43:23 +0800 Subject: [PATCH 030/200] =?UTF-8?q?DUBBO-558=20=E5=BA=94=E7=94=A8=E4=B8=AD?= =?UTF-8?q?DubboClientHandler-thread=E5=A4=AA=E5=A4=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/dubbo/common/utils/ExecutorUtil.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ExecutorUtil.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ExecutorUtil.java index 8c2075d1eb97..d4f336abfb1e 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ExecutorUtil.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ExecutorUtil.java @@ -112,10 +112,14 @@ public void run() { } } - public static URL setThreadName(URL url, String defaultPrefix) { - String name = url.getParameter(Constants.THREAD_NAME_KEY, defaultPrefix); + /** + * append thread name with url address + * @return new url with updated thread name + */ + public static URL setThreadName(URL url, String defaultName) { + String name = url.getParameter(Constants.THREAD_NAME_KEY, defaultName); name = new StringBuilder(32).append(name).append("-").append(url.getAddress()).toString(); - url = url.removeParameter(Constants.THREAD_NAME_KEY).addParameter(Constants.THREAD_NAME_KEY, name); + url = url.addParameter(Constants.THREAD_NAME_KEY, name); return url; } } \ No newline at end of file From 429c0e86f505e2fbc64d7be017d3ce22950ba41c Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Tue, 21 Aug 2012 09:43:30 +0800 Subject: [PATCH 031/200] curator 1.1.16 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c33f1370b498..2f9b519a3255 100644 --- a/pom.xml +++ b/pom.xml @@ -97,7 +97,7 @@ 0.8 3.3.3 0.1 - 1.1.10 + 1.1.16 2.0.0 1.3.6 2.6.1 From d103c22661480307535c8f8db78519d9e3293fbf Mon Sep 17 00:00:00 2001 From: oldrat Date: Tue, 21 Aug 2012 12:30:28 +0800 Subject: [PATCH 032/200] =?UTF-8?q?DUBBO-568=20=E9=85=8D=E7=BD=AE=E9=A1=B9?= =?UTF-8?q?dispather=E5=8D=95=E8=AF=8D=E6=8B=BC=E5=86=99=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/remoting/Dispatcher.java | 4 +- .../telnet/support/TelnetHandlerAdapter.java | 2 - .../{AllDispather.java => AllDispatcher.java} | 38 +++++++++---------- ....java => ConnectionOrderedDispatcher.java} | 38 +++++++++---------- ...ctDispather.java => DirectDispatcher.java} | 38 +++++++++---------- ...ispather.java => ExecutionDispatcher.java} | 38 +++++++++---------- ...pather.java => MessageOnlyDispatcher.java} | 38 +++++++++---------- .../com.alibaba.dubbo.remoting.Dispatcher | 10 ++--- .../dubbo/remoting/PerformanceServerTest.java | 34 ++++++++--------- .../support/header/HeartbeatHandlerTest.java | 2 +- .../FakeChannelHandlers.java | 3 +- 11 files changed, 121 insertions(+), 124 deletions(-) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/{AllDispather.java => AllDispatcher.java} (93%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/{ConnectionOrderedDispather.java => ConnectionOrderedDispatcher.java} (92%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/{DirectDispather.java => DirectDispatcher.java} (93%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/{ExecutionDispather.java => ExecutionDispatcher.java} (93%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/{MessageOnlyDispather.java => MessageOnlyDispatcher.java} (93%) rename dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/{dispather => dispatcher}/FakeChannelHandlers.java (92%) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java index 92228f3e0f77..2699fcb0e121 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Dispatcher.java @@ -19,14 +19,14 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.Adaptive; import com.alibaba.dubbo.common.extension.SPI; -import com.alibaba.dubbo.remoting.transport.dispatcher.all.AllDispather; +import com.alibaba.dubbo.remoting.transport.dispatcher.all.AllDispatcher; /** * ChannelHandlerWrapper (SPI, Singleton, ThreadSafe) * * @author chao.liuc */ -@SPI(AllDispather.NAME) +@SPI(AllDispatcher.NAME) public interface Dispatcher { /** diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java index 87be74c8e1c3..74b10bb5a6f0 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/support/TelnetHandlerAdapter.java @@ -23,8 +23,6 @@ import com.alibaba.dubbo.remoting.transport.ChannelHandlerAdapter; /** - * TelnetHandlerDispather - * * @author william.liangf */ public class TelnetHandlerAdapter extends ChannelHandlerAdapter implements TelnetHandler { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java similarity index 93% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispather.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java index c6be973d0c20..30d5ec6d6755 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/all/AllDispatcher.java @@ -1,30 +1,30 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.dispatcher.all; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispatcher; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.Dispatcher; /** * 榛樿鐨勭嚎绋嬫睜閰嶇疆 * * @author chao.liuc */ -public class AllDispather implements Dispatcher { +public class AllDispatcher implements Dispatcher { public static final String NAME = "all"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java similarity index 92% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispather.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java index 2b8b55ad57e5..ee9fe27e4a17 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/connection/ConnectionOrderedDispatcher.java @@ -1,30 +1,30 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.dispatcher.connection; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispatcher; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.Dispatcher; /** * connect disconnect 淇濊瘉椤哄簭. * * @author chao.liuc */ -public class ConnectionOrderedDispather implements Dispatcher { +public class ConnectionOrderedDispatcher implements Dispatcher { public static final String NAME = "connection"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java similarity index 93% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispather.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java index bb141a4de445..5eab7be3a823 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/direct/DirectDispatcher.java @@ -1,30 +1,30 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.dispatcher.direct; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispatcher; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.Dispatcher; /** * 涓嶆淳鍙戠嚎绋嬫睜銆 * * @author chao.liuc */ -public class DirectDispather implements Dispatcher { +public class DirectDispatcher implements Dispatcher { public static final String NAME = "direct"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java similarity index 93% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispather.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java index 36e86c91f7b9..d72f9d6983ac 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/execution/ExecutionDispatcher.java @@ -1,30 +1,30 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.dispatcher.execution; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispatcher; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.Dispatcher; /** * 闄ゅ彂閫佸叏閮ㄤ娇鐢ㄧ嚎绋嬫睜澶勭悊 * * @author chao.liuc */ -public class ExecutionDispather implements Dispatcher { +public class ExecutionDispatcher implements Dispatcher { public static final String NAME = "execution"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispather.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java similarity index 93% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispather.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java index b00db8995a33..4326aaec270b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispather.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/dispatcher/message/MessageOnlyDispatcher.java @@ -1,30 +1,30 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.dispatcher.message; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Dispatcher; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.Dispatcher; /** * 鍙湁message receive浣跨敤绾跨▼姹. * * @author chao.liuc */ -public class MessageOnlyDispather implements Dispatcher { +public class MessageOnlyDispatcher implements Dispatcher { public static final String NAME = "message"; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher b/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher index f4e576922898..806cb8b7cd35 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher +++ b/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher @@ -1,5 +1,5 @@ -all=com.alibaba.dubbo.remoting.transport.dispatcher.all.AllDispather -direct=com.alibaba.dubbo.remoting.transport.dispatcher.direct.DirectDispather -message=com.alibaba.dubbo.remoting.transport.dispatcher.message.MessageOnlyDispather -execution=com.alibaba.dubbo.remoting.transport.dispatcher.execution.ExecutionDispather -connection=com.alibaba.dubbo.remoting.transport.dispatcher.connection.ConnectionOrderedDispather \ No newline at end of file +all=com.alibaba.dubbo.remoting.transport.dispatcher.all.AllDispatcher +direct=com.alibaba.dubbo.remoting.transport.dispatcher.direct.DirectDispatcher +message=com.alibaba.dubbo.remoting.transport.dispatcher.message.MessageOnlyDispatcher +execution=com.alibaba.dubbo.remoting.transport.dispatcher.execution.ExecutionDispatcher +connection=com.alibaba.dubbo.remoting.transport.dispatcher.connection.ConnectionOrderedDispatcher \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java index 0654f813ed5b..ee0461c782a1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java @@ -1,18 +1,18 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting; import java.util.ArrayList; @@ -29,7 +29,7 @@ import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.Exchangers; import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import com.alibaba.dubbo.remoting.transport.dispatcher.execution.ExecutionDispather; +import com.alibaba.dubbo.remoting.transport.dispatcher.execution.ExecutionDispather; /** * PerformanceServer @@ -88,7 +88,7 @@ private static ExchangeServer statServer() throws Exception{ final int threads = PerformanceUtils.getIntProperty(Constants.THREADS_KEY, Constants.DEFAULT_THREADS); final int iothreads = PerformanceUtils.getIntProperty(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS); final int buffer = PerformanceUtils.getIntProperty(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); - final String channelHandler = PerformanceUtils.getProperty(Constants.DISPATCHER_KEY, ExecutionDispather.NAME); + final String channelHandler = PerformanceUtils.getProperty(Constants.DISPATCHER_KEY, ExecutionDispatcher.NAME); // 鍚姩鏈嶅姟鍣 diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java index e58d226e5349..d269b72e5930 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/exchange/support/header/HeartbeatHandlerTest.java @@ -30,7 +30,7 @@ import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.Exchangers; -import com.alibaba.dubbo.remoting.transport.dispather.FakeChannelHandlers; +import com.alibaba.dubbo.remoting.transport.dispatcher.FakeChannelHandlers; import junit.framework.Assert; diff --git a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispather/FakeChannelHandlers.java b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java similarity index 92% rename from dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispather/FakeChannelHandlers.java rename to dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java index dc91e033e147..cc68e644c7a3 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispather/FakeChannelHandlers.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/test/java/com/alibaba/dubbo/remoting/transport/dispatcher/FakeChannelHandlers.java @@ -14,13 +14,12 @@ * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.dispather; +package com.alibaba.dubbo.remoting.transport.dispatcher; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.Dispatcher; -import com.alibaba.dubbo.remoting.transport.dispatcher.ChannelHandlers; /** * @author kimi From f1ef1e0461ef2904dc87ad235c553eb970b8de2c Mon Sep 17 00:00:00 2001 From: oldrat Date: Tue, 21 Aug 2012 12:43:46 +0800 Subject: [PATCH 033/200] =?UTF-8?q?DUBBO-568=20=E9=85=8D=E7=BD=AE=E9=A1=B9?= =?UTF-8?q?dispather=E5=8D=95=E8=AF=8D=E6=8B=BC=E5=86=99=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/config/ProtocolConfig.java | 4 +-- .../alibaba/dubbo/config/ProviderConfig.java | 26 ++++++++++++++++--- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java index cb24f4b462cb..1f32d0c2fa8c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java @@ -368,7 +368,7 @@ public void setExchanger(String exchanger) { } /** - * 鍗曡瘝鎷煎啓閿欒锛岃浣跨敤getDispatcher() + * 鍗曡瘝鎷煎啓閿欒锛岃浣跨敤{@link #getDispatcher()} * @deprecated {@link #getDispatcher()} */ @Deprecated @@ -377,7 +377,7 @@ public String getDispather() { } /** - * 鍗曡瘝鎷煎啓閿欒锛岃浣跨敤setDispatcher() + * 鍗曡瘝鎷煎啓閿欒锛岃浣跨敤{@link #setDispatcher(String) * @deprecated {@link #setDispatcher(String)} */ @Deprecated diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java index 915544243e93..e013adde560e 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java @@ -17,6 +17,7 @@ import java.util.Arrays; +import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.status.StatusChecker; import com.alibaba.dubbo.common.threadpool.ThreadPool; import com.alibaba.dubbo.config.support.Parameter; @@ -85,7 +86,7 @@ public class ProviderConfig extends AbstractServiceConfig { private String exchanger; // 淇℃伅绾跨▼妯″瀷娲惧彂鏂瑰紡 - private String dispather; + private String dispatcher; // 瀵圭О缃戠粶缁勭綉鏂瑰紡 private String networker; @@ -343,13 +344,32 @@ public void setExchanger(String exchanger) { this.exchanger = exchanger; } + /** + * 鍗曡瘝鎷煎啓閿欒锛岃浣跨敤{@link #getDispatcher()} + * @deprecated {@link #getDispatcher()} + */ + @Deprecated public String getDispather() { - return dispather; + return getDispatcher(); } + /** + * 鍗曡瘝鎷煎啓閿欒锛岃浣跨敤{@link #setDispatcher(String)} + * @deprecated {@link #setDispatcher(String)} + */ + @Deprecated public void setDispather(String dispather) { + setDispatcher(dispather); + } + + public String getDispatcher() { + return dispatcher; + } + + public void setDispatcher(String dispatcher) { + checkExtension(Dispatcher.class, Constants.DISPATCHER_KEY, exchanger); checkExtension(Dispatcher.class, "dispather", exchanger); - this.dispather = dispather; + this.dispatcher = dispatcher; } public String getNetworker() { From e3a4dfd1bbe5dc9bd47b5ac9b6134b5dbbfe8514 Mon Sep 17 00:00:00 2001 From: oldrat Date: Tue, 21 Aug 2012 13:04:17 +0800 Subject: [PATCH 034/200] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20Parameter=20exclud?= =?UTF-8?q?ed=EF=BC=8C=E9=81=BF=E5=85=8D=E5=86=97=E4=BD=99Key=20=20DUBBO-5?= =?UTF-8?q?68=20=E9=85=8D=E7=BD=AE=E9=A1=B9dispather=E5=8D=95=E8=AF=8D?= =?UTF-8?q?=E6=8B=BC=E5=86=99=E9=94=99=E8=AF=AF=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java | 1 + .../src/main/java/com/alibaba/dubbo/config/ProviderConfig.java | 1 + 2 files changed, 2 insertions(+) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java index 1f32d0c2fa8c..afa206274f63 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java @@ -372,6 +372,7 @@ public void setExchanger(String exchanger) { * @deprecated {@link #getDispatcher()} */ @Deprecated + @Parameter(excluded = true) public String getDispather() { return getDispatcher(); } diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java index e013adde560e..e25abbda2a1f 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProviderConfig.java @@ -349,6 +349,7 @@ public void setExchanger(String exchanger) { * @deprecated {@link #getDispatcher()} */ @Deprecated + @Parameter(excluded = true) public String getDispather() { return getDispatcher(); } From 90aebf0f972e1db5f32e5c23f049f2849e00eae7 Mon Sep 17 00:00:00 2001 From: oldrat Date: Tue, 21 Aug 2012 13:31:48 +0800 Subject: [PATCH 035/200] =?UTF-8?q?DUBBO-568=20=E9=85=8D=E7=BD=AE=E9=A1=B9?= =?UTF-8?q?dispather=E5=8D=95=E8=AF=8D=E6=8B=BC=E5=86=99=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/dubbo/remoting/PerformanceServerTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java index ee0461c782a1..b829cd1ce643 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/PerformanceServerTest.java @@ -29,7 +29,7 @@ import com.alibaba.dubbo.remoting.exchange.ExchangeServer; import com.alibaba.dubbo.remoting.exchange.Exchangers; import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import com.alibaba.dubbo.remoting.transport.dispatcher.execution.ExecutionDispather; +import com.alibaba.dubbo.remoting.transport.dispatcher.execution.ExecutionDispatcher; /** * PerformanceServer From 14ec569de9ecf1a837b124c349aa80bdb83c900d Mon Sep 17 00:00:00 2001 From: oldrat Date: Tue, 21 Aug 2012 13:43:09 +0800 Subject: [PATCH 036/200] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=A9=BA=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/com/alibaba/dubbo/config/AbstractConfig.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java index c03d01c1b7b6..3e70bc2362b0 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java @@ -151,12 +151,12 @@ protected static void appendProperties(AbstractConfig config) { if (config.getId() != null && config.getId().length() > 0) { String pn = prefix + config.getId() + "." + property; value = System.getProperty(pn); - logger.info("Use System Property " + pn + "to config dubbo"); + logger.info("Use System Property " + pn + " to config dubbo"); } if (value == null || value.length() == 0) { String pn = prefix + property; value = System.getProperty(pn); - logger.info("Use System Property " + pn + "to config dubbo"); + logger.info("Use System Property " + pn + " to config dubbo"); } if (value == null || value.length() == 0) { Method getter; From 873e8e01bf2ccaed607ed580de99658d7aace443 Mon Sep 17 00:00:00 2001 From: oldrat Date: Wed, 22 Aug 2012 11:14:54 +0800 Subject: [PATCH 037/200] =?UTF-8?q?DUBBO-571=20Provider=E7=9A=84URL?= =?UTF-8?q?=E7=9A=84methods=20key=E5=80=BC=E4=B8=AD=E6=B2=A1=E6=9C=89?= =?UTF-8?q?=E7=BB=A7=E6=89=BF=E6=8E=A5=E5=8F=A3=E7=9A=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/common/bytecode/WrapperTest.java | 193 ++++++++++-------- .../alibaba/dubbo/config/ServiceConfig.java | 10 +- .../dubbo/config/spring/ConfigTest.java | 18 ++ .../config/spring/api/DemoServiceSon.java | 25 +++ .../spring/impl/DemoServiceSonImpl.java | 45 ++++ .../demo-provider-no-methods-interface.xml | 34 +++ 6 files changed, 244 insertions(+), 81 deletions(-) create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/api/DemoServiceSon.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/impl/DemoServiceSonImpl.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/resources/com/alibaba/dubbo/config/spring/demo-provider-no-methods-interface.xml diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/bytecode/WrapperTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/bytecode/WrapperTest.java index 86714cf2dd6e..be62ecb5e4e2 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/bytecode/WrapperTest.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/bytecode/WrapperTest.java @@ -13,32 +13,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.common.bytecode; - -import com.alibaba.dubbo.common.bytecode.Wrapper; - -import junit.framework.TestCase; - -public class WrapperTest extends TestCase -{ - public void testMain() throws Exception - { - Wrapper w = Wrapper.getWrapper(I1.class); - String[] ns = w.getDeclaredMethodNames(); - assertEquals(ns.length, 5); - ns = w.getMethodNames(); - assertEquals(ns.length, 6); - - Object obj = new Impl1(); - assertEquals(w.getPropertyValue(obj, "name"), "you name"); - - w.setPropertyValue(obj, "name", "changed"); - assertEquals(w.getPropertyValue(obj, "name"), "changed"); +package com.alibaba.dubbo.common.bytecode; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class WrapperTest +{ + @Test + public void testMain() throws Exception + { + Wrapper w = Wrapper.getWrapper(I1.class); + String[] ns = w.getDeclaredMethodNames(); + assertEquals(ns.length, 5); + ns = w.getMethodNames(); + assertEquals(ns.length, 6); + + Object obj = new Impl1(); + assertEquals(w.getPropertyValue(obj, "name"), "you name"); + + w.setPropertyValue(obj, "name", "changed"); + assertEquals(w.getPropertyValue(obj, "name"), "changed"); w.invokeMethod(obj, "hello", new Class[] {String.class}, new Object[]{ "qianlei" }); } // bug: DUBBO-132 + @Test public void test_unwantedArgument() throws Exception { Wrapper w = Wrapper.getWrapper(I1.class); Object obj = new Impl1(); @@ -51,70 +52,90 @@ public void test_unwantedArgument() throws Exception { } //bug: DUBBO-425 + @Test public void test_makeEmptyClass() throws Exception { Wrapper.getWrapper(EmptyServiceImpl.class); } - - - public static class Impl0 - { - public float a,b,c; - } - - public static interface I0 - { - String getName(); - } - - public static interface I1 extends I0 - { - void setName(String name); - - void hello(String name); - - int showInt(int v); - - void setFloat(float f); - + + /** + * see http://code.alibabatech.com/jira/browse/DUBBO-571 + */ + @Test + public void test_getDeclaredMethodNames_ContainExtendsParentMethods() throws Exception { + assertArrayEquals(new String[]{"hello", }, Wrapper.getWrapper(Parent1.class).getMethodNames()); + + assertArrayEquals(new String[]{}, Wrapper.getWrapper(Son.class).getDeclaredMethodNames()); + } + + /** + * see http://code.alibabatech.com/jira/browse/DUBBO-571 + */ + @Test + public void test_getMethodNames_ContainExtendsParentMethods() throws Exception { + assertArrayEquals(new String[]{"hello", "world"}, Wrapper.getWrapper(Son.class).getMethodNames()); + } + + public static class Impl0 + { + public float a,b,c; + } + + public static interface I0 + { + String getName(); + } + + public static interface I1 extends I0 + { + void setName(String name); + + void hello(String name); + + int showInt(int v); + + void setFloat(float f); + float getFloat(); - } - - public static class Impl1 implements I1 - { - private String name = "you name"; - - private float fv = 0; - - public String getName() - { - return name; - } - - public void setName(String name) - { - this.name = name; - } - - public void hello(String name) - { - System.out.println("hello " + name); - } - - public int showInt(int v) - { - return v; - } - - public float getFloat() - { - return fv; - } - - public void setFloat(float f) - { - fv = f; - } } + + public static class Impl1 implements I1 + { + private String name = "you name"; + + private float fv = 0; + + public String getName() + { + return name; + } + + public void setName(String name) + { + this.name = name; + } + + public void hello(String name) + { + System.out.println("hello " + name); + } + + public int showInt(int v) + { + return v; + } + + public float getFloat() + { + return fv; + } + + public void setFloat(float f) + { + fv = f; + } + } + + public static interface EmptyService { @@ -123,4 +144,16 @@ public static interface EmptyService public static class EmptyServiceImpl implements EmptyService { } + + public static interface Parent1 { + void hello(); + } + + public static interface Parent2 { + void world(); + } + + public static interface Son extends Parent1, Parent2 { + + } } \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java index 71c883fd9468..77486f4c8cf3 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java @@ -422,7 +422,15 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r if (revision != null && revision.length() > 0) { map.put("revision", revision); } - map.put("methods", StringUtils.join(new HashSet(Arrays.asList(Wrapper.getWrapper(interfaceClass).getDeclaredMethodNames())), ",")); + + String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames(); + if(methods.length == 0) { + logger.warn("NO method found in service interface " + interfaceClass.getName()); + map.put("methods", Constants.ANY_VALUE); + } + else { + map.put("methods", StringUtils.join(new HashSet(Arrays.asList(methods)), ",")); + } } if (! ConfigUtils.isEmpty(token)) { if (ConfigUtils.isDefault(token)) { diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java index 3ec164f7ca0f..18110a15a173 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java @@ -26,6 +26,7 @@ import java.util.List; import org.junit.Test; +import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -370,6 +371,23 @@ public void testInitReference() throws Exception { providerContext.close(); } } + + // DUBBO-571 Provider鐨刄RL鐨刴ethods key鍊间腑娌℃湁缁ф壙鎺ュ彛鐨勬柟娉 + @Test + public void test_noMethodInterface_methodsKeyHasValue() throws Exception { + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/demo-provider-no-methods-interface.xml"); + ctx.start(); + try { + ServiceBean bean = (ServiceBean) ctx.getBean("service"); + List urls = bean.getExportedUrls(); + assertEquals(1, urls.size()); + URL url = urls.get(0); + assertEquals("sayName,getBox", url.getParameter("methods")); + } finally { + ctx.stop(); + ctx.close(); + } + } // DUBBO-147 閫氳繃RpcContext鍙互鑾峰緱鎵鏈夊皾璇曡繃鐨処nvoker @Test diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/api/DemoServiceSon.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/api/DemoServiceSon.java new file mode 100644 index 000000000000..ede66ebc8bac --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/api/DemoServiceSon.java @@ -0,0 +1,25 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.api; + +/** + * DemoService + * + * @author ding.lid + */ +public interface DemoServiceSon extends DemoService { + // no methods +} \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/impl/DemoServiceSonImpl.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/impl/DemoServiceSonImpl.java new file mode 100644 index 000000000000..1a0292207218 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/impl/DemoServiceSonImpl.java @@ -0,0 +1,45 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.config.spring.impl; + +import com.alibaba.dubbo.config.spring.api.Box; +import com.alibaba.dubbo.config.spring.api.DemoService; +import com.alibaba.dubbo.config.spring.api.DemoServiceSon; + +/** + * @author ding.lid + */ +public class DemoServiceSonImpl implements DemoServiceSon { + + private String prefix = "say:"; + + public String sayName(String name) { + return prefix + name; + } + + public Box getBox() { + return null; + } + + public String getPrefix() { + return prefix; + } + + public void setPrefix(String prefix) { + this.prefix = prefix; + } + +} \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/src/test/resources/com/alibaba/dubbo/config/spring/demo-provider-no-methods-interface.xml b/dubbo-config/dubbo-config-spring/src/test/resources/com/alibaba/dubbo/config/spring/demo-provider-no-methods-interface.xml new file mode 100644 index 000000000000..260d21f4e760 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/resources/com/alibaba/dubbo/config/spring/demo-provider-no-methods-interface.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + \ No newline at end of file From 85310c7d674e0f0f0951c9a605e6dda37d7c262e Mon Sep 17 00:00:00 2001 From: oldrat Date: Wed, 22 Aug 2012 13:43:05 +0800 Subject: [PATCH 038/200] =?UTF-8?q?=E4=B8=8D=E8=87=AA=E5=8A=A8=E4=B8=8A?= =?UTF-8?q?=E4=BC=A0xsd=20file=E3=80=82=E5=9B=A0=E4=B8=BA=E4=BD=8E?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E5=8F=AF=E4=BB=A5=E5=9C=A8=E9=AB=98=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E4=B9=8B=E5=90=8E=E5=8F=91=E5=B8=83=E3=80=82=E6=AF=94?= =?UTF-8?q?=E5=A6=82=20bug=20fix=E7=89=88=E6=9C=AC2.4.5=20=E5=9C=A82.5.0?= =?UTF-8?q?=E4=B9=8B=E5=90=8E=E5=8F=91=E5=B8=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dubbo-config/dubbo-config-spring/pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index f70091593951..02c933a1f381 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -86,6 +86,10 @@ + + \ No newline at end of file From ce33f45036e461869f773992ac017c11df6b99a6 Mon Sep 17 00:00:00 2001 From: kimi Date: Wed, 22 Aug 2012 13:45:23 +0800 Subject: [PATCH 039/200] release 2.5.1 --- dubbo-admin/pom.xml | 2 +- dubbo-cluster/pom.xml | 2 +- dubbo-common/pom.xml | 2 +- dubbo-config/dubbo-config-api/pom.xml | 2 +- dubbo-config/dubbo-config-spring/pom.xml | 2 +- dubbo-config/pom.xml | 2 +- dubbo-container/dubbo-container-api/pom.xml | 2 +- dubbo-container/dubbo-container-jetty/pom.xml | 2 +- dubbo-container/dubbo-container-log4j/pom.xml | 2 +- dubbo-container/dubbo-container-logback/pom.xml | 2 +- dubbo-container/dubbo-container-spring/pom.xml | 2 +- dubbo-container/pom.xml | 2 +- dubbo-demo/dubbo-demo-api/pom.xml | 2 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 2 +- dubbo-demo/dubbo-demo-provider/pom.xml | 2 +- dubbo-demo/pom.xml | 2 +- dubbo-filter/dubbo-filter-cache/pom.xml | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 2 +- dubbo-filter/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +- dubbo-monitor/pom.xml | 2 +- dubbo-registry/dubbo-registry-api/pom.xml | 2 +- dubbo-registry/dubbo-registry-default/pom.xml | 2 +- dubbo-registry/dubbo-registry-multicast/pom.xml | 2 +- dubbo-registry/dubbo-registry-redis/pom.xml | 2 +- dubbo-registry/dubbo-registry-zookeeper/pom.xml | 2 +- dubbo-registry/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-p2p/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-zookeeper/pom.xml | 2 +- dubbo-remoting/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-default/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 2 +- dubbo-rpc/pom.xml | 2 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 2 +- dubbo-simple/dubbo-registry-simple/pom.xml | 2 +- dubbo-simple/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark/pom.xml | 2 +- dubbo-test/dubbo-test-compatibility/pom.xml | 2 +- dubbo-test/dubbo-test-examples/pom.xml | 2 +- dubbo-test/dubbo-test-integration/pom.xml | 2 +- dubbo-test/pom.xml | 2 +- dubbo/pom.xml | 2 +- pom.xml | 2 +- 57 files changed, 57 insertions(+), 57 deletions(-) diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index 1e1d456130cb..4559f72f60a3 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-admin war diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index 760fe79b6527..f489d09d27de 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-cluster jar diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index 0c53ed4282ec..1c78ea4a01fd 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-common jar diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index fd028cdbab82..bda835e27413 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.5.1-SNAPSHOT + 2.5.1 dubbo-config-api jar diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 02c933a1f381..b9580fe65214 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.5.1-SNAPSHOT + 2.5.1 dubbo-config-spring jar diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index 8591181b21ec..d31616e4cf18 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index 242ea63aae70..010f37eee3f0 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.1-SNAPSHOT + 2.5.1 dubbo-container-api jar diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index a6da58edd8ea..b346f41fc78b 100644 --- a/dubbo-container/dubbo-container-jetty/pom.xml +++ b/dubbo-container/dubbo-container-jetty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.1-SNAPSHOT + 2.5.1 dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index 81e22e5a7a8e..f018da23a6d7 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.1-SNAPSHOT + 2.5.1 dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index 67ee9c5aea90..f170fd879285 100644 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ b/dubbo-container/dubbo-container-logback/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.1-SNAPSHOT + 2.5.1 dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index a724d9301dd8..4d415ed181b1 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.1-SNAPSHOT + 2.5.1 dubbo-container-spring jar diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index bc0dbfe8b76d..0f8e7170beaa 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-container pom diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index 181677dda32f..266e2e575a67 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.1-SNAPSHOT + 2.5.1 dubbo-demo-api jar diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml index cbf7994e5746..110af9d3bdbb 100644 --- a/dubbo-demo/dubbo-demo-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.1-SNAPSHOT + 2.5.1 dubbo-demo-consumer jar diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml index eec9382c28f1..ef29ae001189 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.1-SNAPSHOT + 2.5.1 dubbo-demo-provider jar diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index 1a6c466a1e04..9817cfaa1efb 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-demo pom diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 269ef15c1524..ed34c401727a 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.1-SNAPSHOT + 2.5.1 dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index 96d85242d319..6192f2d492ed 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.1-SNAPSHOT + 2.5.1 dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index 10eff8097f72..ca14f1b159e7 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-filter pom diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index ac4eb116f4f2..3c0bc08ab5b9 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.1-SNAPSHOT + 2.5.1 dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index 65a30681c9ea..1091c1e57c3b 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.1-SNAPSHOT + 2.5.1 dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index 689f1a608d23..eed4790a169f 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 42dd87710e9c..2f5231a96e3c 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.1-SNAPSHOT + 2.5.1 dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index 5a6a5c2ccc40..0b6305e93ea3 100644 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ b/dubbo-registry/dubbo-registry-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.1-SNAPSHOT + 2.5.1 dubbo-registry-default jar diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index 7cb38680d281..b2716d338483 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.1-SNAPSHOT + 2.5.1 dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index 3b71cc519831..885893cc6589 100644 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ b/dubbo-registry/dubbo-registry-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.1-SNAPSHOT + 2.5.1 dubbo-registry-redis jar diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index b57cedbf7367..4c32c817b261 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.1-SNAPSHOT + 2.5.1 dubbo-registry-zookeeper jar diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index 0b5dfe0d59a9..974be0c460ac 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-registry pom diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index 30823ac83b50..29425f54d65a 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1-SNAPSHOT + 2.5.1 dubbo-remoting-api jar diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml index e615c69e235d..f2506c2a05eb 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml +++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1-SNAPSHOT + 2.5.1 dubbo-remoting-grizzly jar diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index 83b74355929a..cf26b1a0819d 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1-SNAPSHOT + 2.5.1 dubbo-remoting-http jar diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml index 9298d59fd4f7..2f8e55d35295 100644 --- a/dubbo-remoting/dubbo-remoting-mina/pom.xml +++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1-SNAPSHOT + 2.5.1 dubbo-remoting-mina jar diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index eb9a6fb1f3fe..101a0d61e58b 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1-SNAPSHOT + 2.5.1 dubbo-remoting-netty jar diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml index 2feadb7c390d..d0ad0309d090 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml +++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1-SNAPSHOT + 2.5.1 dubbo-remoting-p2p jar diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index e1d74996b919..2714f36c4ae0 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1-SNAPSHOT + 2.5.1 dubbo-remoting-zookeeper jar diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index ca8a09eea4d7..5e9ad9b350a8 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-remoting pom diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index 147ef085fbb6..95680a6842a4 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1-SNAPSHOT + 2.5.1 dubbo-rpc-api jar diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index 474ebc6b80da..a282287a36e8 100644 --- a/dubbo-rpc/dubbo-rpc-default/pom.xml +++ b/dubbo-rpc/dubbo-rpc-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1-SNAPSHOT + 2.5.1 dubbo-rpc-default jar diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index 5288b30f1b7a..98479c79ebe6 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1-SNAPSHOT + 2.5.1 dubbo-rpc-hessian jar diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index 5fd11498680e..bee9cba00140 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1-SNAPSHOT + 2.5.1 dubbo-rpc-http jar diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index 83fc38caca7a..09fa9f1be667 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml +++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1-SNAPSHOT + 2.5.1 dubbo-rpc-injvm jar diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml index fd1fca7075e9..f4bfac07612f 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml +++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1-SNAPSHOT + 2.5.1 dubbo-rpc-memcached jar diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml index 55b91a9ba4b3..73426aedeedb 100644 --- a/dubbo-rpc/dubbo-rpc-redis/pom.xml +++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1-SNAPSHOT + 2.5.1 dubbo-rpc-redis jar diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml index 28ea93a87688..b7517bbb67ce 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1-SNAPSHOT + 2.5.1 dubbo-rpc-rmi jar diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml index 704b70eaef61..8b6d7113afad 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ b/dubbo-rpc/dubbo-rpc-thrift/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1-SNAPSHOT + 2.5.1 dubbo-rpc-thrift jar diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml index 752b03224acc..3f0c83bbf8fd 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml +++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1-SNAPSHOT + 2.5.1 dubbo-rpc-webservice jar diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 3a0b7b966a80..cf29794034d7 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-rpc pom diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml index 6e4bf8afdd31..1331a8ac2dea 100644 --- a/dubbo-simple/dubbo-monitor-simple/pom.xml +++ b/dubbo-simple/dubbo-monitor-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.5.1-SNAPSHOT + 2.5.1 dubbo-monitor-simple jar diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml index 36fb115b6b51..5e0b7eff4023 100644 --- a/dubbo-simple/dubbo-registry-simple/pom.xml +++ b/dubbo-simple/dubbo-registry-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.5.1-SNAPSHOT + 2.5.1 dubbo-registry-simple jar diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml index fc216d21f79a..3659830ca601 100644 --- a/dubbo-simple/pom.xml +++ b/dubbo-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-simple pom diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml index 3d2f0be891aa..237d03ba8733 100644 --- a/dubbo-test/dubbo-test-benchmark/pom.xml +++ b/dubbo-test/dubbo-test-benchmark/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.1-SNAPSHOT + 2.5.1 dubbo-test-benchmark jar diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml index 65222dc32cb1..3d13334af766 100644 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ b/dubbo-test/dubbo-test-compatibility/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.1-SNAPSHOT + 2.5.1 dubbo-test-compatibility jar diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index dc717aa8f348..b8f11b1674a6 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.1-SNAPSHOT + 2.5.1 dubbo-test-examples jar diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml index 9f5c5d6c8422..7a50fb964fd2 100644 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ b/dubbo-test/dubbo-test-integration/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.1-SNAPSHOT + 2.5.1 dubbo-test-integration jar diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml index aa73320922dd..550725e911da 100644 --- a/dubbo-test/pom.xml +++ b/dubbo-test/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo-test pom diff --git a/dubbo/pom.xml b/dubbo/pom.xml index b4bc0ff0428d..569e40dcbcba 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 dubbo jar diff --git a/pom.xml b/pom.xml index 2f9b519a3255..0ae2e99fd190 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ 2.0 dubbo-parent - 2.5.1-SNAPSHOT + 2.5.1 pom ${project.artifactId} The parent project of dubbo From a55c10d7c5a819c80f4252299ea49dd20feeeb47 Mon Sep 17 00:00:00 2001 From: oldrat Date: Thu, 23 Aug 2012 00:02:24 +0800 Subject: [PATCH 040/200] =?UTF-8?q?DUBBO-573=20Version.getVersion=E5=87=BA?= =?UTF-8?q?NPE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/dubbo/common/Version.java | 37 +++++++++++-------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java index 62442a94c2e3..716426932e2b 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java @@ -16,6 +16,7 @@ package com.alibaba.dubbo.common; import java.net.URL; +import java.security.CodeSource; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; @@ -75,26 +76,32 @@ public static String getVersion(Class cls, String defaultVersion) { } if (version == null || version.length() == 0) { // 濡傛灉瑙勮寖涓病鏈夌増鏈彿锛屽熀浜巎ar鍖呭悕鑾峰彇鐗堟湰鍙 - String file = cls.getProtectionDomain().getCodeSource().getLocation().getFile(); - if (file != null && file.length() > 0 && file.endsWith(".jar")) { - file = file.substring(0, file.length() - 4); - int i = file.lastIndexOf('/'); - if (i >= 0) { - file = file.substring(i + 1); - } - i = file.indexOf("-"); - if (i >= 0) { - file = file.substring(i + 1); - } - while (file.length() > 0 && ! Character.isDigit(file.charAt(0))) { + CodeSource codeSource = cls.getProtectionDomain().getCodeSource(); + if(codeSource == null) { + logger.info("No codeSource for class " + cls.getName() + " when getVersion, use default version " + defaultVersion); + } + else { + String file = codeSource.getLocation().getFile(); + if (file != null && file.length() > 0 && file.endsWith(".jar")) { + file = file.substring(0, file.length() - 4); + int i = file.lastIndexOf('/'); + if (i >= 0) { + file = file.substring(i + 1); + } i = file.indexOf("-"); if (i >= 0) { file = file.substring(i + 1); - } else { - break; } + while (file.length() > 0 && ! Character.isDigit(file.charAt(0))) { + i = file.indexOf("-"); + if (i >= 0) { + file = file.substring(i + 1); + } else { + break; + } + } + version = file; } - version = file; } } // 杩斿洖鐗堟湰鍙凤紝濡傛灉涓虹┖杩斿洖缂虹渷鐗堟湰鍙 From ae19c902ba30a468ff4dbc75b0fa38e146831602 Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 23 Aug 2012 10:54:27 +0800 Subject: [PATCH 041/200] update version to 2.5.2-SNAPSHOT --- dubbo-admin/pom.xml | 2 +- dubbo-cluster/pom.xml | 2 +- dubbo-common/pom.xml | 2 +- dubbo-config/dubbo-config-api/pom.xml | 2 +- dubbo-config/dubbo-config-spring/pom.xml | 2 +- dubbo-config/pom.xml | 2 +- dubbo-container/dubbo-container-api/pom.xml | 2 +- dubbo-container/dubbo-container-jetty/pom.xml | 2 +- dubbo-container/dubbo-container-log4j/pom.xml | 2 +- dubbo-container/dubbo-container-logback/pom.xml | 2 +- dubbo-container/dubbo-container-spring/pom.xml | 2 +- dubbo-container/pom.xml | 2 +- dubbo-demo/dubbo-demo-api/pom.xml | 2 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 2 +- dubbo-demo/dubbo-demo-provider/pom.xml | 2 +- dubbo-demo/pom.xml | 2 +- dubbo-filter/dubbo-filter-cache/pom.xml | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 2 +- dubbo-filter/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +- dubbo-monitor/pom.xml | 2 +- dubbo-registry/dubbo-registry-api/pom.xml | 2 +- dubbo-registry/dubbo-registry-default/pom.xml | 2 +- dubbo-registry/dubbo-registry-multicast/pom.xml | 2 +- dubbo-registry/dubbo-registry-redis/pom.xml | 2 +- dubbo-registry/dubbo-registry-zookeeper/pom.xml | 2 +- dubbo-registry/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-p2p/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-zookeeper/pom.xml | 2 +- dubbo-remoting/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-default/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 2 +- dubbo-rpc/pom.xml | 2 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 2 +- dubbo-simple/dubbo-registry-simple/pom.xml | 2 +- dubbo-simple/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark/pom.xml | 2 +- dubbo-test/dubbo-test-compatibility/pom.xml | 2 +- dubbo-test/dubbo-test-examples/pom.xml | 2 +- dubbo-test/dubbo-test-integration/pom.xml | 2 +- dubbo-test/pom.xml | 2 +- dubbo/pom.xml | 2 +- pom.xml | 2 +- 57 files changed, 57 insertions(+), 57 deletions(-) diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index 4559f72f60a3..65427c5286e6 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-admin war diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index f489d09d27de..470653b47018 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-cluster jar diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index 1c78ea4a01fd..a0fd8cb71cf5 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-common jar diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index bda835e27413..700125466365 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.5.1 + 2.5.2-SNAPSHOT dubbo-config-api jar diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index b9580fe65214..800faf21611e 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.5.1 + 2.5.2-SNAPSHOT dubbo-config-spring jar diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index d31616e4cf18..37ff9e674ada 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index 010f37eee3f0..b330d5932ddc 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.1 + 2.5.2-SNAPSHOT dubbo-container-api jar diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index b346f41fc78b..31ec7bf7e871 100644 --- a/dubbo-container/dubbo-container-jetty/pom.xml +++ b/dubbo-container/dubbo-container-jetty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.1 + 2.5.2-SNAPSHOT dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index f018da23a6d7..dfb95377b5e1 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.1 + 2.5.2-SNAPSHOT dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index f170fd879285..0542a36e8756 100644 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ b/dubbo-container/dubbo-container-logback/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.1 + 2.5.2-SNAPSHOT dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index 4d415ed181b1..7cd1f0ac568c 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.1 + 2.5.2-SNAPSHOT dubbo-container-spring jar diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index 0f8e7170beaa..bce54e53ed94 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-container pom diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index 266e2e575a67..188cdd7e9615 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.1 + 2.5.2-SNAPSHOT dubbo-demo-api jar diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml index 110af9d3bdbb..df5086d43205 100644 --- a/dubbo-demo/dubbo-demo-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.1 + 2.5.2-SNAPSHOT dubbo-demo-consumer jar diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml index ef29ae001189..eaa4e2ebf729 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.1 + 2.5.2-SNAPSHOT dubbo-demo-provider jar diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index 9817cfaa1efb..6a392eebda00 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-demo pom diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index ed34c401727a..80aa42f36348 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.1 + 2.5.2-SNAPSHOT dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index 6192f2d492ed..23f0b647ceb9 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.1 + 2.5.2-SNAPSHOT dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index ca14f1b159e7..865f6d825a38 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-filter pom diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index 3c0bc08ab5b9..9d94daabf508 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.1 + 2.5.2-SNAPSHOT dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index 1091c1e57c3b..3986a24c9273 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.1 + 2.5.2-SNAPSHOT dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index eed4790a169f..5c1566e83a93 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 2f5231a96e3c..ef5bced28db5 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.1 + 2.5.2-SNAPSHOT dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index 0b6305e93ea3..00d3248bee36 100644 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ b/dubbo-registry/dubbo-registry-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.1 + 2.5.2-SNAPSHOT dubbo-registry-default jar diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index b2716d338483..1b5de58e6259 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.1 + 2.5.2-SNAPSHOT dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index 885893cc6589..01a474c41ab8 100644 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ b/dubbo-registry/dubbo-registry-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.1 + 2.5.2-SNAPSHOT dubbo-registry-redis jar diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index 4c32c817b261..02f5dee90e8b 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.1 + 2.5.2-SNAPSHOT dubbo-registry-zookeeper jar diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index 974be0c460ac..1a2e3abfe5c6 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-registry pom diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index 29425f54d65a..d3a2c690a397 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1 + 2.5.2-SNAPSHOT dubbo-remoting-api jar diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml index f2506c2a05eb..f050cbfc94b3 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml +++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1 + 2.5.2-SNAPSHOT dubbo-remoting-grizzly jar diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index cf26b1a0819d..ebd369322707 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1 + 2.5.2-SNAPSHOT dubbo-remoting-http jar diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml index 2f8e55d35295..e5f5f24ae7e2 100644 --- a/dubbo-remoting/dubbo-remoting-mina/pom.xml +++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1 + 2.5.2-SNAPSHOT dubbo-remoting-mina jar diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index 101a0d61e58b..b0d78e0e5cb2 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1 + 2.5.2-SNAPSHOT dubbo-remoting-netty jar diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml index d0ad0309d090..f9d38a7a4d39 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml +++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1 + 2.5.2-SNAPSHOT dubbo-remoting-p2p jar diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index 2714f36c4ae0..27f59dfa5622 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.1 + 2.5.2-SNAPSHOT dubbo-remoting-zookeeper jar diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 5e9ad9b350a8..85ac02f08d7d 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-remoting pom diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index 95680a6842a4..c6d87b449dee 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1 + 2.5.2-SNAPSHOT dubbo-rpc-api jar diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index a282287a36e8..a51e8c4e83fe 100644 --- a/dubbo-rpc/dubbo-rpc-default/pom.xml +++ b/dubbo-rpc/dubbo-rpc-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1 + 2.5.2-SNAPSHOT dubbo-rpc-default jar diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index 98479c79ebe6..1fdc5b3409af 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1 + 2.5.2-SNAPSHOT dubbo-rpc-hessian jar diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index bee9cba00140..c0a0d714d187 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1 + 2.5.2-SNAPSHOT dubbo-rpc-http jar diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index 09fa9f1be667..a25021bad66f 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml +++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1 + 2.5.2-SNAPSHOT dubbo-rpc-injvm jar diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml index f4bfac07612f..fcbea65efec6 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml +++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1 + 2.5.2-SNAPSHOT dubbo-rpc-memcached jar diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml index 73426aedeedb..07b38ef4f848 100644 --- a/dubbo-rpc/dubbo-rpc-redis/pom.xml +++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1 + 2.5.2-SNAPSHOT dubbo-rpc-redis jar diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml index b7517bbb67ce..5c2df6dd7ca2 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1 + 2.5.2-SNAPSHOT dubbo-rpc-rmi jar diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml index 8b6d7113afad..687406fe6a14 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ b/dubbo-rpc/dubbo-rpc-thrift/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1 + 2.5.2-SNAPSHOT dubbo-rpc-thrift jar diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml index 3f0c83bbf8fd..147375c4304b 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml +++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.1 + 2.5.2-SNAPSHOT dubbo-rpc-webservice jar diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index cf29794034d7..5f1421a823ca 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-rpc pom diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml index 1331a8ac2dea..ec4130c8ca9a 100644 --- a/dubbo-simple/dubbo-monitor-simple/pom.xml +++ b/dubbo-simple/dubbo-monitor-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.5.1 + 2.5.2-SNAPSHOT dubbo-monitor-simple jar diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml index 5e0b7eff4023..7c70d56ee906 100644 --- a/dubbo-simple/dubbo-registry-simple/pom.xml +++ b/dubbo-simple/dubbo-registry-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.5.1 + 2.5.2-SNAPSHOT dubbo-registry-simple jar diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml index 3659830ca601..709e01a15add 100644 --- a/dubbo-simple/pom.xml +++ b/dubbo-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-simple pom diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml index 237d03ba8733..5dd16c20547a 100644 --- a/dubbo-test/dubbo-test-benchmark/pom.xml +++ b/dubbo-test/dubbo-test-benchmark/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.1 + 2.5.2-SNAPSHOT dubbo-test-benchmark jar diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml index 3d13334af766..75315e9aa22e 100644 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ b/dubbo-test/dubbo-test-compatibility/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.1 + 2.5.2-SNAPSHOT dubbo-test-compatibility jar diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index b8f11b1674a6..bdf23a6e0ec8 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.1 + 2.5.2-SNAPSHOT dubbo-test-examples jar diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml index 7a50fb964fd2..b822a6c757dc 100644 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ b/dubbo-test/dubbo-test-integration/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.1 + 2.5.2-SNAPSHOT dubbo-test-integration jar diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml index 550725e911da..12a66b4a528e 100644 --- a/dubbo-test/pom.xml +++ b/dubbo-test/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo-test pom diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 569e40dcbcba..b11cea48e01e 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT dubbo jar diff --git a/pom.xml b/pom.xml index 0ae2e99fd190..f1c211e9f9c6 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ 2.0 dubbo-parent - 2.5.1 + 2.5.2-SNAPSHOT pom ${project.artifactId} The parent project of dubbo From 925bc13ddeb3d4a75b2170b2a4987da694095c9d Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 23 Aug 2012 10:59:08 +0800 Subject: [PATCH 042/200] add properties for generate idea copyright --- pom.xml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pom.xml b/pom.xml index f1c211e9f9c6..0a413651096a 100644 --- a/pom.xml +++ b/pom.xml @@ -127,6 +127,10 @@ false true ${file_encoding} + + + Copyright 1999-2012 Alibaba Group. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + oss From c43682609625f6702e70a2512a770bc623dfd89b Mon Sep 17 00:00:00 2001 From: kimi Date: Mon, 27 Aug 2012 11:05:58 +0800 Subject: [PATCH 043/200] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=88=A4=E6=96=ADbea?= =?UTF-8?q?n=E5=B1=9E=E6=80=A7=E7=9A=84read/write=E6=96=B9=E6=B3=95?= =?UTF-8?q?=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/dubbo/common/utils/ReflectUtils.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ReflectUtils.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ReflectUtils.java index 93fc00826fe1..8fad47576b83 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ReflectUtils.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ReflectUtils.java @@ -945,7 +945,8 @@ public static boolean isBeanPropertyReadMethod(Method method) { && method.getReturnType() != void.class && method.getDeclaringClass() != Object.class && method.getParameterTypes().length == 0 - && (method.getName().startsWith("get") || method.getName().startsWith("is")); + && ((method.getName().startsWith("get") && method.getName().length() > 3) + || (method.getName().startsWith("is") && method.getName().length() > 2)); } public static String getPropertyNameFromBeanReadMethod(Method method) { @@ -968,7 +969,8 @@ public static boolean isBeanPropertyWriteMethod(Method method) { && ! Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass() != Object.class && method.getParameterTypes().length == 1 - && method.getName().startsWith("set"); + && method.getName().startsWith("set") + && method.getName().length() > 3; } public static String getPropertyNameFromBeanWriteMethod(Method method) { From 0acac3f4015823f5ea6236cdf43b73c424f6a5a4 Mon Sep 17 00:00:00 2001 From: oldrat Date: Thu, 30 Aug 2012 14:37:53 +0800 Subject: [PATCH 044/200] =?UTF-8?q?=E6=97=A5=E5=BF=97=E4=BF=AE=E6=94=B9=20?= =?UTF-8?q?DUBBO-573?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/com/alibaba/dubbo/common/Version.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java index 716426932e2b..80ee7a652496 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Version.java @@ -108,7 +108,7 @@ public static String getVersion(Class cls, String defaultVersion) { return version == null || version.length() == 0 ? defaultVersion : version; } catch (Throwable e) { // 闃插尽鎬у閿 // 蹇界暐寮傚父锛岃繑鍥炵己鐪佺増鏈彿 - logger.error(e.getMessage(), e); + logger.error("return default version, ignore exception " + e.getMessage(), e); return defaultVersion; } } From 2060ed880e0d1f380fbf89d39f7c48f153ff71db Mon Sep 17 00:00:00 2001 From: oldrat Date: Thu, 30 Aug 2012 14:47:52 +0800 Subject: [PATCH 045/200] =?UTF-8?q?DUBBO-576=20Dubbo=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E7=9A=84=E7=B3=BB=E7=BB=9FProperty=EF=BC=8C=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E4=BA=86=E7=9A=84=E9=85=8D=E7=BD=AE=E6=89=8D=E6=89=93=E5=8D=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/dubbo/config/AbstractConfig.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java index 3e70bc2362b0..3eee351cb502 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/AbstractConfig.java @@ -35,7 +35,7 @@ import com.alibaba.dubbo.config.support.Parameter; /** - * AbstractConfig + * 閰嶇疆瑙f瀽鐨勫伐鍏锋柟娉曘佸叕鍏辨柟娉 * * @author william.liangf * @export @@ -151,12 +151,16 @@ protected static void appendProperties(AbstractConfig config) { if (config.getId() != null && config.getId().length() > 0) { String pn = prefix + config.getId() + "." + property; value = System.getProperty(pn); - logger.info("Use System Property " + pn + " to config dubbo"); + if(! StringUtils.isBlank(value)) { + logger.info("Use System Property " + pn + " to config dubbo"); + } } if (value == null || value.length() == 0) { String pn = prefix + property; value = System.getProperty(pn); - logger.info("Use System Property " + pn + " to config dubbo"); + if(! StringUtils.isBlank(value)) { + logger.info("Use System Property " + pn + " to config dubbo"); + } } if (value == null || value.length() == 0) { Method getter; From 2096288912e29e0225865943afdfb97a14da1c00 Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 30 Aug 2012 15:55:22 +0800 Subject: [PATCH 046/200] =?UTF-8?q?DUBBO-582=20decode=E6=97=B6=E5=8D=B3?= =?UTF-8?q?=E4=BD=BFpayload=E8=B6=85=E5=87=BA=E9=99=90=E5=88=B6=E4=B9=9F?= =?UTF-8?q?=E8=A6=81=E6=8A=8A=E5=BD=93=E5=89=8Dmessage=E8=AF=BB=E5=AE=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../exchange/codec/ExchangeCodec.java | 2 +- .../remoting/codec/ExchangeCodecTest.java | 42 ++++++++++++++----- 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java index 32646f3dc302..83184770c407 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -113,7 +113,6 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] he // get data length. int len = Bytes.bytes2int(header, 12); - checkPayload(channel, len); int tt = len + HEADER_LENGTH; if( readable < tt ) { @@ -125,6 +124,7 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] he is = StreamUtils.limitedInputStream(is, len); try { + checkPayload(channel, len); return decodeBody(channel, is, header); } finally { if (is.available() > 0) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java index b9b5ae453028..7bfa386f3ecc 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java @@ -148,17 +148,7 @@ public void test_Decode_Error_Response_Object() throws IOException{ Response obj = (Response)decode(request); Assert.assertEquals(90, obj.getStatus()); } - @Test - public void test_Decode_Check_Payload() throws IOException{ - byte[] header = new byte[] { MAGIC_HIGH , MAGIC_LOW , 1 ,1 ,1 ,1 ,1 , 1 ,1 ,1 ,1 ,1 , 1 ,1 , 1,1 }; - byte[] request = assemblyDataProtocol(header) ; - try{ - testDecode_assertEquals(request, TelnetCodec.NEED_MORE_INPUT); - fail(); - }catch (IOException expected) { - Assert.assertTrue(expected.getMessage().startsWith("Data length too large: "+Bytes.bytes2int(new byte[]{1,1,1,1}))); - } - } + @Test public void test_Decode_Header_Need_Readmore() throws IOException{ byte[] header = new byte[] { MAGIC_HIGH , MAGIC_LOW , 0 ,0 ,0 ,0 ,0 , 0 ,0 ,0 ,0 }; @@ -419,4 +409,34 @@ public void testMessageLengthGreaterThanMessageActualLength() throws Exception { decodedRequest = (Request)codec.decode(channel, inputStream); Assert.assertTrue(date.equals(decodedRequest.getData())); } + + @Test + public void testMessageLengthExceedPayloadLimit() throws Exception { + Request request = new Request(1L); + request.setData("hello"); + UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(512); + Channel channel = getCliendSideChannel(url); + codec.encode(channel, bos, request); + byte[] requestMessage = bos.toByteArray(); + byte[] message = new byte[requestMessage.length * 2]; + System.arraycopy(requestMessage, 0, message, 0, requestMessage.length); + System.arraycopy(requestMessage, 0, message, requestMessage.length, requestMessage.length); + + channel = getServerSideChannel( + url.addParameter(Constants.PAYLOAD_KEY, requestMessage.length - 16 /* header length */ - 2)); + UnsafeByteArrayInputStream bis = new UnsafeByteArrayInputStream(message); + try { + codec.decode(channel, bis); + Assert.fail(); + } catch (IOException e) { + Assert.assertTrue(e.getMessage().startsWith("Data length too large: "+ (requestMessage.length - 16 /* header length*/))); + } + + channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD)); + Object object = codec.decode(channel, bis); + Assert.assertTrue(object instanceof Request); + Request decodeRequest = (Request) object; + Assert.assertEquals(request.getId(), decodeRequest.getId()); + Assert.assertEquals(request.getData(), decodeRequest.getData()); + } } \ No newline at end of file From 772ce39e2c418e9f7ced1ad44d7015c0feeeec49 Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 30 Aug 2012 16:14:36 +0800 Subject: [PATCH 047/200] =?UTF-8?q?DUBBO-581=20codec=20encode=E5=90=8E?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E6=95=B0=E6=8D=AE=E6=98=AF=E5=90=A6=E8=B6=85?= =?UTF-8?q?=E8=BF=87payload=E7=9A=84=E9=99=90=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../exchange/codec/ExchangeCodec.java | 2 ++ .../remoting/codec/ExchangeCodecTest.java | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java index 83184770c407..4635b2e0c551 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -239,6 +239,7 @@ protected void encodeRequest(Channel channel, OutputStream os, Request req) thro bos.flush(); bos.close(); byte[] data = bos.toByteArray(); + checkPayload(channel, data.length); Bytes.int2bytes(data.length, header, 12); // write @@ -278,6 +279,7 @@ protected void encodeResponse(Channel channel, OutputStream os, Response res) th bos.close(); byte[] data = bos.toByteArray(); + checkPayload(channel, data.length); Bytes.int2bytes(data.length, header, 12); // write os.write(header); // write header. diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java index 7bfa386f3ecc..54c2be5cfa4a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java @@ -439,4 +439,27 @@ public void testMessageLengthExceedPayloadLimit() throws Exception { Assert.assertEquals(request.getId(), decodeRequest.getId()); Assert.assertEquals(request.getData(), decodeRequest.getData()); } + + @Test + public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { + Request request = new Request(1L); + request.setData("hello"); + UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(512); + AbstractMockChannel channel = getCliendSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); + try { + codec.encode(channel, bos, request); + Assert.fail(); + } catch (IOException e) { + Assert.assertTrue(e.getMessage().startsWith("Data length too large: " + 6)); + } + + Response response = new Response(1L); + response.setResult("hello"); + bos = new UnsafeByteArrayOutputStream(512); + channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); + codec.encode(channel, bos, response); + Assert.assertTrue(channel.getReceivedMessage() instanceof Response); + Response receiveMessage = (Response) channel.getReceivedMessage(); + Assert.assertEquals(Response.BAD_RESPONSE, receiveMessage.getStatus()); + } } \ No newline at end of file From 5ca8687cf4d64e14ac8d870c04998aa903773134 Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 30 Aug 2012 16:14:36 +0800 Subject: [PATCH 048/200] =?UTF-8?q?DUBBO-581=20codec=20encode=E5=90=8E?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E6=95=B0=E6=8D=AE=E6=98=AF=E5=90=A6=E8=B6=85?= =?UTF-8?q?=E8=BF=87payload=E7=9A=84=E9=99=90=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../exchange/codec/ExchangeCodec.java | 2 ++ .../remoting/codec/ExchangeCodecTest.java | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java index 83184770c407..4635b2e0c551 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -239,6 +239,7 @@ protected void encodeRequest(Channel channel, OutputStream os, Request req) thro bos.flush(); bos.close(); byte[] data = bos.toByteArray(); + checkPayload(channel, data.length); Bytes.int2bytes(data.length, header, 12); // write @@ -278,6 +279,7 @@ protected void encodeResponse(Channel channel, OutputStream os, Response res) th bos.close(); byte[] data = bos.toByteArray(); + checkPayload(channel, data.length); Bytes.int2bytes(data.length, header, 12); // write os.write(header); // write header. diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java index 7bfa386f3ecc..54c2be5cfa4a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java @@ -439,4 +439,27 @@ public void testMessageLengthExceedPayloadLimit() throws Exception { Assert.assertEquals(request.getId(), decodeRequest.getId()); Assert.assertEquals(request.getData(), decodeRequest.getData()); } + + @Test + public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { + Request request = new Request(1L); + request.setData("hello"); + UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(512); + AbstractMockChannel channel = getCliendSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); + try { + codec.encode(channel, bos, request); + Assert.fail(); + } catch (IOException e) { + Assert.assertTrue(e.getMessage().startsWith("Data length too large: " + 6)); + } + + Response response = new Response(1L); + response.setResult("hello"); + bos = new UnsafeByteArrayOutputStream(512); + channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); + codec.encode(channel, bos, response); + Assert.assertTrue(channel.getReceivedMessage() instanceof Response); + Response receiveMessage = (Response) channel.getReceivedMessage(); + Assert.assertEquals(Response.BAD_RESPONSE, receiveMessage.getStatus()); + } } \ No newline at end of file From 63907bc7cca5608d082dace082a1c80bb5fa55ed Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 30 Aug 2012 17:21:23 +0800 Subject: [PATCH 049/200] =?UTF-8?q?DUBBO-581=20codec=20encode=E5=90=8E?= =?UTF-8?q?=E6=A3=80=E6=9F=A5=E6=95=B0=E6=8D=AE=E6=98=AF=E5=90=A6=E8=B6=85?= =?UTF-8?q?=E8=BF=87payload=E7=9A=84=E9=99=90=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java | 1 + 1 file changed, 1 insertion(+) diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java index 54c2be5cfa4a..eed084120c3b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java @@ -461,5 +461,6 @@ public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { Assert.assertTrue(channel.getReceivedMessage() instanceof Response); Response receiveMessage = (Response) channel.getReceivedMessage(); Assert.assertEquals(Response.BAD_RESPONSE, receiveMessage.getStatus()); + Assert.assertTrue(receiveMessage.getErrorMessage().contains("Data length too large: ")); } } \ No newline at end of file From f2e74a9cb8490b6037d24f62195d1cef92f383c1 Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Fri, 31 Aug 2012 10:04:40 +0800 Subject: [PATCH 050/200] =?UTF-8?q?DUBBO-514=20=E9=87=8D=E5=90=AF=E6=97=B6?= =?UTF-8?q?=E5=BA=94=E9=99=8D=E4=BD=8E=E6=96=B0=E5=90=AF=E6=9C=BA=E5=99=A8?= =?UTF-8?q?=E7=9A=84=E6=9D=83=E9=87=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rpc/cluster/loadbalance/AbstractLoadBalance.java | 11 ++++++++++- .../main/java/com/alibaba/dubbo/common/Constants.java | 4 ++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java index f7adbb14eba6..e35167db7e1c 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java @@ -41,7 +41,16 @@ public Invoker select(List> invokers, URL url, Invocation invo protected abstract Invoker doSelect(List> invokers, URL url, Invocation invocation); protected int getWeight(Invoker invoker, Invocation invocation) { - return invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); + int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); + long timestamp = invoker.getUrl().getParameter(Constants.TIMESTAMP_KEY, 0L); + if (timestamp > 0L) { + int uptime = (int) (System.currentTimeMillis() - timestamp); + int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP); + if (uptime > 0 && uptime < warmup) { + weight = uptime / (warmup / weight); + } + } + return weight; } } \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java index 718287ee0e2e..5cdccf1f713a 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -295,6 +295,10 @@ public class Constants { public static final String PID_KEY = "pid"; public static final String TIMESTAMP_KEY = "timestamp"; + + public static final String WARMUP_KEY = "warmup"; + + public static final int DEFAULT_WARMUP = 10 * 60 * 1000; public static final String CHECK_KEY = "check"; From 4ac044f13eaa9709d956bd5023ce779b7bf3cf24 Mon Sep 17 00:00:00 2001 From: kimi Date: Fri, 31 Aug 2012 10:13:48 +0800 Subject: [PATCH 051/200] =?UTF-8?q?=E5=9B=9E=E6=BB=9A=20DUBBO-582?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../exchange/codec/ExchangeCodec.java | 2 +- .../remoting/codec/ExchangeCodecTest.java | 41 +++++-------------- 2 files changed, 12 insertions(+), 31 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java index 4635b2e0c551..6d3a8e5fe76a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -113,6 +113,7 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] he // get data length. int len = Bytes.bytes2int(header, 12); + checkPayload(channel, len); int tt = len + HEADER_LENGTH; if( readable < tt ) { @@ -124,7 +125,6 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] he is = StreamUtils.limitedInputStream(is, len); try { - checkPayload(channel, len); return decodeBody(channel, is, header); } finally { if (is.available() > 0) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java index eed084120c3b..77023b006b38 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java @@ -149,6 +149,17 @@ public void test_Decode_Error_Response_Object() throws IOException{ Assert.assertEquals(90, obj.getStatus()); } + @Test + public void test_Decode_Check_Payload() throws IOException { + byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + byte[] request = assemblyDataProtocol(header); + try { + testDecode_assertEquals(request, TelnetCodec.NEED_MORE_INPUT); + fail(); + } catch (IOException expected) { + Assert.assertTrue(expected.getMessage().startsWith("Data length too large: " + Bytes.bytes2int(new byte[]{1, 1, 1, 1}))); + } + } @Test public void test_Decode_Header_Need_Readmore() throws IOException{ byte[] header = new byte[] { MAGIC_HIGH , MAGIC_LOW , 0 ,0 ,0 ,0 ,0 , 0 ,0 ,0 ,0 }; @@ -410,36 +421,6 @@ public void testMessageLengthGreaterThanMessageActualLength() throws Exception { Assert.assertTrue(date.equals(decodedRequest.getData())); } - @Test - public void testMessageLengthExceedPayloadLimit() throws Exception { - Request request = new Request(1L); - request.setData("hello"); - UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(512); - Channel channel = getCliendSideChannel(url); - codec.encode(channel, bos, request); - byte[] requestMessage = bos.toByteArray(); - byte[] message = new byte[requestMessage.length * 2]; - System.arraycopy(requestMessage, 0, message, 0, requestMessage.length); - System.arraycopy(requestMessage, 0, message, requestMessage.length, requestMessage.length); - - channel = getServerSideChannel( - url.addParameter(Constants.PAYLOAD_KEY, requestMessage.length - 16 /* header length */ - 2)); - UnsafeByteArrayInputStream bis = new UnsafeByteArrayInputStream(message); - try { - codec.decode(channel, bis); - Assert.fail(); - } catch (IOException e) { - Assert.assertTrue(e.getMessage().startsWith("Data length too large: "+ (requestMessage.length - 16 /* header length*/))); - } - - channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD)); - Object object = codec.decode(channel, bis); - Assert.assertTrue(object instanceof Request); - Request decodeRequest = (Request) object; - Assert.assertEquals(request.getId(), decodeRequest.getId()); - Assert.assertEquals(request.getData(), decodeRequest.getData()); - } - @Test public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { Request request = new Request(1L); From 1b7bbae15c4e225a93b2cfee4fb98263fdb4271f Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Fri, 31 Aug 2012 10:56:49 +0800 Subject: [PATCH 052/200] =?UTF-8?q?DUBBO-514=20=E6=94=B9=E4=B8=BA=E6=B5=AE?= =?UTF-8?q?=E7=82=B9=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java index e35167db7e1c..13c15af53f44 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java @@ -47,7 +47,7 @@ protected int getWeight(Invoker invoker, Invocation invocation) { int uptime = (int) (System.currentTimeMillis() - timestamp); int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP); if (uptime > 0 && uptime < warmup) { - weight = uptime / (warmup / weight); + weight = (int) ( (float) uptime / ( (float) warmup / (float) weight ) ); } } return weight; From f9485dee334eb2b4432c0e4acb2035aca1355d6f Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Fri, 31 Aug 2012 11:25:25 +0800 Subject: [PATCH 053/200] =?UTF-8?q?DUBBO-514=20=E5=A2=9E=E5=8A=A0=E5=8D=95?= =?UTF-8?q?=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../loadbalance/AbstractLoadBalance.java | 7 ++++++- .../cluster/loadbalance/LoadBalanceTest.java | 20 ++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java index 13c15af53f44..238a6e2edbcb 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java @@ -47,10 +47,15 @@ protected int getWeight(Invoker invoker, Invocation invocation) { int uptime = (int) (System.currentTimeMillis() - timestamp); int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP); if (uptime > 0 && uptime < warmup) { - weight = (int) ( (float) uptime / ( (float) warmup / (float) weight ) ); + weight = calculateWarmupWeight(uptime, warmup, weight); } } return weight; } + + static int calculateWarmupWeight(int uptime, int warmup, int weight) { + int ww = (int) ( (float) uptime / ( (float) warmup / (float) weight ) ); + return ww < 1 ? 1 : (ww > weight ? weight : ww); + } } \ No newline at end of file diff --git a/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/loadbalance/LoadBalanceTest.java b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/loadbalance/LoadBalanceTest.java index cc09aba64e12..55e2a0417d09 100644 --- a/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/loadbalance/LoadBalanceTest.java +++ b/dubbo-cluster/src/test/java/com/alibaba/dubbo/rpc/cluster/loadbalance/LoadBalanceTest.java @@ -28,6 +28,7 @@ import org.junit.BeforeClass; import org.junit.Test; +import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.rpc.Invocation; @@ -144,7 +145,24 @@ public Map getInvokeCounter(int runs,String loadbalanceName) counter.get(sinvoker).incrementAndGet(); } return counter; + } + + @Test + public void testLoadBalanceWarmup() { + Assert.assertEquals(1, AbstractLoadBalance.calculateWarmupWeight(0, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(1, AbstractLoadBalance.calculateWarmupWeight(13, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(1, AbstractLoadBalance.calculateWarmupWeight(6 * 1000, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(2, AbstractLoadBalance.calculateWarmupWeight(12 * 1000, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(10, AbstractLoadBalance.calculateWarmupWeight(60 * 1000, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(50, AbstractLoadBalance.calculateWarmupWeight(5 * 60 * 1000, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(50, AbstractLoadBalance.calculateWarmupWeight(5 * 60 * 1000 + 23, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(50, AbstractLoadBalance.calculateWarmupWeight(5 * 60 * 1000 + 5999, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(51, AbstractLoadBalance.calculateWarmupWeight(5 * 60 * 1000 + 6000, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(90, AbstractLoadBalance.calculateWarmupWeight(9 * 60 * 1000, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(98, AbstractLoadBalance.calculateWarmupWeight(10 * 60 * 1000 - 12 * 1000, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(99, AbstractLoadBalance.calculateWarmupWeight(10 * 60 * 1000 - 6 * 1000, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(100, AbstractLoadBalance.calculateWarmupWeight(10 * 60 * 1000, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); + Assert.assertEquals(100, AbstractLoadBalance.calculateWarmupWeight(20 * 60 * 1000, Constants.DEFAULT_WARMUP, Constants.DEFAULT_WEIGHT)); } - } \ No newline at end of file From 4a221d92b1154b9daf28a96035d4e6097dd9ad72 Mon Sep 17 00:00:00 2001 From: liangfei0201 Date: Fri, 31 Aug 2012 11:32:04 +0800 Subject: [PATCH 054/200] =?UTF-8?q?DUBBO-514=20=E5=8A=A0=E5=BC=BA=E5=8F=82?= =?UTF-8?q?=E6=95=B0=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../loadbalance/AbstractLoadBalance.java | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java index 238a6e2edbcb..8f53582e2e03 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/loadbalance/AbstractLoadBalance.java @@ -42,14 +42,16 @@ public Invoker select(List> invokers, URL url, Invocation invo protected int getWeight(Invoker invoker, Invocation invocation) { int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT); - long timestamp = invoker.getUrl().getParameter(Constants.TIMESTAMP_KEY, 0L); - if (timestamp > 0L) { - int uptime = (int) (System.currentTimeMillis() - timestamp); - int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP); - if (uptime > 0 && uptime < warmup) { - weight = calculateWarmupWeight(uptime, warmup, weight); - } - } + if (weight > 0) { + long timestamp = invoker.getUrl().getParameter(Constants.TIMESTAMP_KEY, 0L); + if (timestamp > 0L) { + int uptime = (int) (System.currentTimeMillis() - timestamp); + int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP); + if (uptime > 0 && uptime < warmup) { + weight = calculateWarmupWeight(uptime, warmup, weight); + } + } + } return weight; } From dfdde1a6bf906415dda6c46ae860d168efe45401 Mon Sep 17 00:00:00 2001 From: oldrat Date: Wed, 5 Sep 2012 13:43:51 +0800 Subject: [PATCH 055/200] =?UTF-8?q?DUBBO-585=20jedis=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF2.0=E7=89=88=E6=9C=ACBinary=20Compatibility=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0a413651096a..052b8052ead7 100644 --- a/pom.xml +++ b/pom.xml @@ -98,7 +98,7 @@ 3.3.3 0.1 1.1.16 - 2.0.0 + 2.1.0 1.3.6 2.6.1 0.8.0 From 2823abb82c0e4edb8bf5f2d581b27545ccf249dc Mon Sep 17 00:00:00 2001 From: kimi Date: Wed, 5 Sep 2012 13:49:38 +0800 Subject: [PATCH 056/200] =?UTF-8?q?DUBBO-583=20=E9=9B=86=E6=88=90=20hsf=20?= =?UTF-8?q?=E7=9A=84=E8=B7=AF=E7=94=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/rpc/cluster/RuleConverter.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/RuleConverter.java diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/RuleConverter.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/RuleConverter.java new file mode 100644 index 000000000000..ec089690a42b --- /dev/null +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/RuleConverter.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.rpc.cluster; + +import java.util.List; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.SPI; + +/** + * @author kimi + */ +@SPI +public interface RuleConverter { + + List convert(URL subscribeUrl, Object source); + +} From 650fb228f2f91df8172d08263884994fe3dcd2f9 Mon Sep 17 00:00:00 2001 From: oldrat Date: Wed, 5 Sep 2012 14:38:27 +0800 Subject: [PATCH 057/200] =?UTF-8?q?DUBBO-590=20ReferenceConfig=E7=94=9F?= =?UTF-8?q?=E6=88=90=E7=9A=84methods=20key=E5=9C=A8=E6=B2=A1=E6=9C=89?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E6=97=B6=E4=BD=BF=E7=94=A8*=E4=BD=9C?= =?UTF-8?q?=E4=B8=BAvalue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/dubbo/config/ReferenceConfig.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java index 7aa387c473ed..12dcc9472a58 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ReferenceConfig.java @@ -265,7 +265,15 @@ private void init() { if (revision != null && revision.length() > 0) { map.put("revision", revision); } - map.put("methods", StringUtils.join(new HashSet(Arrays.asList(Wrapper.getWrapper(interfaceClass).getDeclaredMethodNames())), ",")); + + String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames(); + if(methods.length == 0) { + logger.warn("NO method found in service interface " + interfaceClass.getName()); + map.put("methods", Constants.ANY_VALUE); + } + else { + map.put("methods", StringUtils.join(new HashSet(Arrays.asList(methods)), ",")); + } } map.put(Constants.INTERFACE_KEY, interfaceName); appendParameters(map, application); @@ -379,6 +387,7 @@ private T createProxy(Map map) { throw new IllegalStateException("No such any registry to reference " + interfaceName + " on the consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", please config to your spring config."); } } + if (urls.size() == 1) { invoker = refprotocol.refer(interfaceClass, urls.get(0)); } else { From 80861908594d9cd8a5ad0e782d591be70f2979a7 Mon Sep 17 00:00:00 2001 From: oldrat Date: Wed, 5 Sep 2012 15:16:25 +0800 Subject: [PATCH 058/200] =?UTF-8?q?DUBBO-580=20ExtensionLoader=E9=80=9A?= =?UTF-8?q?=E8=BF=87=E7=BC=96=E7=A8=8B=E6=96=B9=E5=BC=8F=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?extension=E6=97=B6=E6=B2=A1=E6=9C=89=E5=88=A4=E6=96=AD=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E7=9A=84=E6=98=AF=E5=90=A6=E6=98=AFadaptive=20extensi?= =?UTF-8?q?on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/extension/ExtensionLoader.java | 54 ++++++++--- .../extensionloader/ExtensionLoaderTest.java | 97 ++++++++++++++----- .../extensionloader/ext8_add/AddExt1.java | 31 ++++++ .../extensionloader/ext8_add/AddExt2.java | 31 ++++++ .../extensionloader/ext8_add/AddExt3.java | 31 ++++++ .../extensionloader/ext8_add/AddExt4.java | 31 ++++++ .../impl/AddExt1Impl1.java} | 17 +--- .../ext8_add/impl/AddExt1_ManualAdaptive.java | 32 ++++++ .../impl/AddExt1_ManualAdd1.java} | 17 +--- .../ext8_add/impl/AddExt1_ManualAdd2.java | 28 ++++++ .../ext8_add/impl/AddExt2Impl1.java | 28 ++++++ .../ext8_add/impl/AddExt2_ManualAdaptive.java | 32 ++++++ .../ext8_add/impl/AddExt3_ManualAdaptive.java | 32 ++++++ .../ext8_add/impl/AddExt4_ManualAdaptive.java | 32 ++++++ ...bo.common.extensionloader.ext8_add.AddExt1 | 1 + 15 files changed, 433 insertions(+), 61 deletions(-) create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt1.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt2.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt3.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt4.java rename dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/{ext1/impl/SimpleExtImpl_ManualAdd1.java => ext8_add/impl/AddExt1Impl1.java} (65%) create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1_ManualAdaptive.java rename dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/{ext1/impl/SimpleExtImpl_ManualAdd2.java => ext8_add/impl/AddExt1_ManualAdd1.java} (65%) create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1_ManualAdd2.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt2Impl1.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt2_ManualAdaptive.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt3_ManualAdaptive.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt4_ManualAdaptive.java create mode 100644 dubbo-common/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1 diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java index 453e29165555..89080bf64fca 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java @@ -369,10 +369,6 @@ public String getDefaultExtensionName() { public void addExtension(String name, Class clazz) { getExtensionClasses(); // load classes - if(cachedClasses.get().containsKey(name)) { - throw new IllegalStateException("Extension name " + - name + " already existed(Extension " + type + ")!"); - } if(!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Input type " + clazz + "not implement Extension " + type); @@ -381,8 +377,26 @@ public void addExtension(String name, Class clazz) { throw new IllegalStateException("Input type " + clazz + "can not be interface!"); } - cachedNames.put(clazz, name); - cachedClasses.get().put(name, clazz); + + if(!clazz.isAnnotationPresent(Adaptive.class)) { + if(StringUtils.isBlank(name)) { + throw new IllegalStateException("Extension name is blank (Extension " + type + ")!"); + } + if(cachedClasses.get().containsKey(name)) { + throw new IllegalStateException("Extension name " + + name + " already existed(Extension " + type + ")!"); + } + + cachedNames.put(clazz, name); + cachedClasses.get().put(name, clazz); + } + else { + if(cachedAdaptiveClass != null) { + throw new IllegalStateException("Adaptive Extension already existed(Extension " + type + ")!"); + } + + cachedAdaptiveClass = clazz; + } } /** @@ -397,10 +411,6 @@ public void addExtension(String name, Class clazz) { public void replaceExtension(String name, Class clazz) { getExtensionClasses(); // load classes - if(!cachedClasses.get().containsKey(name)) { - throw new IllegalStateException("Extension name " + - name + " not existed(Extension " + type + ")!"); - } if(!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Input type " + clazz + "not implement Extension " + type); @@ -410,9 +420,27 @@ public void replaceExtension(String name, Class clazz) { clazz + "can not be interface!"); } - cachedNames.put(clazz, name); - cachedClasses.get().put(name, clazz); - cachedInstances.remove(name); + if(!clazz.isAnnotationPresent(Adaptive.class)) { + if(StringUtils.isBlank(name)) { + throw new IllegalStateException("Extension name is blank (Extension " + type + ")!"); + } + if(!cachedClasses.get().containsKey(name)) { + throw new IllegalStateException("Extension name " + + name + " not existed(Extension " + type + ")!"); + } + + cachedNames.put(clazz, name); + cachedClasses.get().put(name, clazz); + cachedInstances.remove(name); + } + else { + if(cachedAdaptiveClass == null) { + throw new IllegalStateException("Adaptive Extension not existed(Extension " + type + ")!"); + } + + cachedAdaptiveClass = clazz; + cachedAdaptiveInstance.set(null); + } } @SuppressWarnings("unchecked") diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoaderTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoaderTest.java index 7e50636e59de..689d97e3f495 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoaderTest.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoaderTest.java @@ -36,10 +36,13 @@ import com.alibaba.dubbo.common.extensionloader.activate.impl.OrderActivateExtImpl2; import com.alibaba.dubbo.common.extensionloader.activate.impl.ValueActivateExtImpl; import com.alibaba.dubbo.common.extensionloader.ext1.impl.SimpleExtImpl1; -import com.alibaba.dubbo.common.extensionloader.ext1.impl.SimpleExtImpl_ManualAdd1; -import com.alibaba.dubbo.common.extensionloader.ext1.impl.SimpleExtImpl_ManualAdd2; import com.alibaba.dubbo.common.extensionloader.ext6_wrap.WrappedExt; import com.alibaba.dubbo.common.extensionloader.ext7.InitErrorExt; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt2; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt3; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt4; +import com.alibaba.dubbo.common.extensionloader.ext8_add.impl.*; import junit.framework.Assert; import org.junit.Test; @@ -219,18 +222,18 @@ public void test_getSupportedExtensions_wrapperIsNotExt() throws Exception { @Test public void test_AddExtension() throws Exception { try { - ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtension("Manual1"); + ExtensionLoader.getExtensionLoader(AddExt1.class).getExtension("Manual1"); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("No such extension com.alibaba.dubbo.common.extensionloader.ext1.SimpleExt by name Manual")); + assertThat(expected.getMessage(), containsString("No such extension com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1 by name Manual")); } - ExtensionLoader.getExtensionLoader(SimpleExt.class).addExtension("Manual1", SimpleExtImpl_ManualAdd1.class); - SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtension("Manual1"); + ExtensionLoader.getExtensionLoader(AddExt1.class).addExtension("Manual1", AddExt1_ManualAdd1.class); + AddExt1 ext = ExtensionLoader.getExtensionLoader(AddExt1.class).getExtension("Manual1"); - assertThat(ext, instanceOf(SimpleExtImpl_ManualAdd1.class)); - assertEquals("Manual1", ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtensionName(SimpleExtImpl_ManualAdd1.class)); + assertThat(ext, instanceOf(AddExt1_ManualAdd1.class)); + assertEquals("Manual1", ExtensionLoader.getExtensionLoader(AddExt1.class).getExtensionName(AddExt1_ManualAdd1.class)); } @Test @@ -238,49 +241,99 @@ public void test_AddExtension_ExceptionWhenExistedExtension() throws Exception { SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtension("impl1"); try { - ExtensionLoader.getExtensionLoader(SimpleExt.class).addExtension("impl1", SimpleExtImpl_ManualAdd1.class); + ExtensionLoader.getExtensionLoader(AddExt1.class).addExtension("impl1", AddExt1_ManualAdd1.class); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Extension name impl1 already existed(Extension interface com.alibaba.dubbo.common.extensionloader.ext1.SimpleExt)!")); + assertThat(expected.getMessage(), containsString("Extension name impl1 already existed(Extension interface com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1)!")); + } + } + + @Test + public void test_AddExtension_Adaptive() throws Exception { + ExtensionLoader loader = ExtensionLoader.getExtensionLoader(AddExt2.class); + loader.addExtension(null, AddExt2_ManualAdaptive.class); + + AddExt2 adaptive = loader.getAdaptiveExtension(); + assertTrue(adaptive instanceof AddExt2_ManualAdaptive); + } + + @Test + public void test_AddExtension_Adaptive_ExceptionWhenExistedAdaptive() throws Exception { + ExtensionLoader loader = ExtensionLoader.getExtensionLoader(AddExt1.class); + + loader.getAdaptiveExtension(); + + try { + loader.addExtension(null, AddExt1_ManualAdaptive.class); + fail(); + } + catch (IllegalStateException expected) { + assertThat(expected.getMessage(), containsString("Adaptive Extension already existed(Extension interface com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1)!")); } } @Test public void test_replaceExtension() throws Exception { try { - ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtension("Manual2"); + ExtensionLoader.getExtensionLoader(AddExt1.class).getExtension("Manual2"); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("No such extension com.alibaba.dubbo.common.extensionloader.ext1.SimpleExt by name Manual")); + assertThat(expected.getMessage(), containsString("No such extension com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1 by name Manual")); } { - SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtension("impl1"); + AddExt1 ext = ExtensionLoader.getExtensionLoader(AddExt1.class).getExtension("impl1"); - assertThat(ext, instanceOf(SimpleExtImpl1.class)); - assertEquals("impl1", ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtensionName(SimpleExtImpl1.class)); + assertThat(ext, instanceOf(AddExt1Impl1.class)); + assertEquals("impl1", ExtensionLoader.getExtensionLoader(AddExt1.class).getExtensionName(AddExt1Impl1.class)); } { - ExtensionLoader.getExtensionLoader(SimpleExt.class).replaceExtension("impl1", SimpleExtImpl_ManualAdd2.class); - SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtension("impl1"); + ExtensionLoader.getExtensionLoader(AddExt1.class).replaceExtension("impl1", AddExt1_ManualAdd2.class); + AddExt1 ext = ExtensionLoader.getExtensionLoader(AddExt1.class).getExtension("impl1"); - assertThat(ext, instanceOf(SimpleExtImpl_ManualAdd2.class)); - assertEquals("impl1", ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtensionName(SimpleExtImpl_ManualAdd2.class)); + assertThat(ext, instanceOf(AddExt1_ManualAdd2.class)); + assertEquals("impl1", ExtensionLoader.getExtensionLoader(AddExt1.class).getExtensionName(AddExt1_ManualAdd2.class)); } } + @Test + public void test_replaceExtension_Adaptive() throws Exception { + ExtensionLoader loader = ExtensionLoader.getExtensionLoader(AddExt3.class); + + AddExt3 adaptive = loader.getAdaptiveExtension(); + assertFalse(adaptive instanceof AddExt3_ManualAdaptive); + + loader.replaceExtension(null, AddExt3_ManualAdaptive.class); + + adaptive = loader.getAdaptiveExtension(); + assertTrue(adaptive instanceof AddExt3_ManualAdaptive); + } + @Test public void test_replaceExtension_ExceptionWhenNotExistedExtension() throws Exception { - SimpleExt ext = ExtensionLoader.getExtensionLoader(SimpleExt.class).getExtension("impl1"); + AddExt1 ext = ExtensionLoader.getExtensionLoader(AddExt1.class).getExtension("impl1"); + + try { + ExtensionLoader.getExtensionLoader(AddExt1.class).replaceExtension("NotExistedExtension", AddExt1_ManualAdd1.class); + fail(); + } + catch (IllegalStateException expected) { + assertThat(expected.getMessage(), containsString("Extension name NotExistedExtension not existed(Extension interface com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1)")); + } + } + + @Test + public void test_replaceExtension_Adaptive_ExceptionWhenNotExistedExtension() throws Exception { + ExtensionLoader loader = ExtensionLoader.getExtensionLoader(AddExt4.class); try { - ExtensionLoader.getExtensionLoader(SimpleExt.class).replaceExtension("NotExistedExtension", SimpleExtImpl_ManualAdd1.class); + loader.replaceExtension(null, AddExt4_ManualAdaptive.class); fail(); } catch (IllegalStateException expected) { - assertThat(expected.getMessage(), containsString("Extension name NotExistedExtension not existed(Extension interface com.alibaba.dubbo.common.extensionloader.ext1.SimpleExt)")); + assertThat(expected.getMessage(), containsString("Adaptive Extension not existed(Extension interface com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt4)")); } } diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt1.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt1.java new file mode 100644 index 000000000000..4d6889d987d0 --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt1.java @@ -0,0 +1,31 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.ext8_add; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.SPI; + +/** + * show add extension pragmatically + * + * @author ding.lid + */ +@SPI("impl1") +public interface AddExt1 { + @Adaptive + String echo(URL url, String s); +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt2.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt2.java new file mode 100644 index 000000000000..e088fd60a96e --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt2.java @@ -0,0 +1,31 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.ext8_add; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.SPI; + +/** + * show add extension pragmatically. use for test addAdaptive successful + * + * @author ding.lid + */ +@SPI("impl1") +public interface AddExt2 { + @Adaptive + String echo(URL url, String s); +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt3.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt3.java new file mode 100644 index 000000000000..d585228d4cfe --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt3.java @@ -0,0 +1,31 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.ext8_add; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.SPI; + +/** + * show add extension pragmatically. use for test replaceAdaptive success + * + * @author ding.lid + */ +@SPI("impl1") +public interface AddExt3 { + @Adaptive + String echo(URL url, String s); +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt4.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt4.java new file mode 100644 index 000000000000..633b58374b57 --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/AddExt4.java @@ -0,0 +1,31 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.ext8_add; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.SPI; + +/** + * show add extension pragmatically. use for test replaceAdaptive fail + * + * @author ding.lid + */ +@SPI("impl1") +public interface AddExt4 { + @Adaptive + String echo(URL url, String s); +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext1/impl/SimpleExtImpl_ManualAdd1.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1Impl1.java similarity index 65% rename from dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext1/impl/SimpleExtImpl_ManualAdd1.java rename to dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1Impl1.java index 28ab01befa00..b1a48fc8c825 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext1/impl/SimpleExtImpl_ManualAdd1.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1Impl1.java @@ -13,25 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.common.extensionloader.ext1.impl; +package com.alibaba.dubbo.common.extensionloader.ext8_add.impl; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extensionloader.ext1.SimpleExt; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1; /** * @author ding.lid */ -public class SimpleExtImpl_ManualAdd1 implements SimpleExt { +public class AddExt1Impl1 implements AddExt1 { public String echo(URL url, String s) { - return "Ext1Impl4-echo"; + return this.getClass().getSimpleName(); } - - public String yell(URL url, String s) { - return "Ext1Impl4-yell"; - } - - public String bang(URL url, int i) { - return "bang4"; - } - } \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1_ManualAdaptive.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1_ManualAdaptive.java new file mode 100644 index 000000000000..7edce0da8d2c --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1_ManualAdaptive.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.ext8_add.impl; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1; + +/** + * @author ding.lid + */ +@Adaptive +public class AddExt1_ManualAdaptive implements AddExt1 { + public String echo(URL url, String s) { + AddExt1 addExt1 = ExtensionLoader.getExtensionLoader(AddExt1.class).getExtension(url.getParameter("add.ext1")); + return addExt1.echo(url, s); + } +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext1/impl/SimpleExtImpl_ManualAdd2.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1_ManualAdd1.java similarity index 65% rename from dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext1/impl/SimpleExtImpl_ManualAdd2.java rename to dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1_ManualAdd1.java index b2685bc75e84..ab7e2671cb18 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext1/impl/SimpleExtImpl_ManualAdd2.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1_ManualAdd1.java @@ -13,25 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.common.extensionloader.ext1.impl; +package com.alibaba.dubbo.common.extensionloader.ext8_add.impl; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extensionloader.ext1.SimpleExt; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1; /** * @author ding.lid */ -public class SimpleExtImpl_ManualAdd2 implements SimpleExt { +public class AddExt1_ManualAdd1 implements AddExt1 { public String echo(URL url, String s) { - return "Ext1Impl4-echo"; + return this.getClass().getSimpleName(); } - - public String yell(URL url, String s) { - return "Ext1Impl4-yell"; - } - - public String bang(URL url, int i) { - return "bang4"; - } - } \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1_ManualAdd2.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1_ManualAdd2.java new file mode 100644 index 000000000000..d7faf3438854 --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt1_ManualAdd2.java @@ -0,0 +1,28 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.ext8_add.impl; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1; + +/** + * @author ding.lid + */ +public class AddExt1_ManualAdd2 implements AddExt1 { + public String echo(URL url, String s) { + return this.getClass().getSimpleName(); + } +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt2Impl1.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt2Impl1.java new file mode 100644 index 000000000000..176e68b3ce5c --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt2Impl1.java @@ -0,0 +1,28 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.ext8_add.impl; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt2; + +/** + * @author ding.lid + */ +public class AddExt2Impl1 implements AddExt2 { + public String echo(URL url, String s) { + return this.getClass().getSimpleName(); + } +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt2_ManualAdaptive.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt2_ManualAdaptive.java new file mode 100644 index 000000000000..ee26bcf3addf --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt2_ManualAdaptive.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.ext8_add.impl; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt2; + +/** + * @author ding.lid + */ +@Adaptive +public class AddExt2_ManualAdaptive implements AddExt2 { + public String echo(URL url, String s) { + AddExt2 addExt1 = ExtensionLoader.getExtensionLoader(AddExt2.class).getExtension(url.getParameter("add.ext2")); + return addExt1.echo(url, s); + } +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt3_ManualAdaptive.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt3_ManualAdaptive.java new file mode 100644 index 000000000000..dd752dd43d80 --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt3_ManualAdaptive.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.ext8_add.impl; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt3; + +/** + * @author ding.lid + */ +@Adaptive +public class AddExt3_ManualAdaptive implements AddExt3 { + public String echo(URL url, String s) { + AddExt3 addExt1 = ExtensionLoader.getExtensionLoader(AddExt3.class).getExtension(url.getParameter("add.ext3")); + return addExt1.echo(url, s); + } +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt4_ManualAdaptive.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt4_ManualAdaptive.java new file mode 100644 index 000000000000..9cf5921d8d5f --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ext8_add/impl/AddExt4_ManualAdaptive.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.ext8_add.impl; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt4; + +/** + * @author ding.lid + */ +@Adaptive +public class AddExt4_ManualAdaptive implements AddExt4 { + public String echo(URL url, String s) { + AddExt4 addExt1 = ExtensionLoader.getExtensionLoader(AddExt4.class).getExtension(url.getParameter("add.ext4")); + return addExt1.echo(url, s); + } +} \ No newline at end of file diff --git a/dubbo-common/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1 b/dubbo-common/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1 new file mode 100644 index 000000000000..02ee0c0f5ca9 --- /dev/null +++ b/dubbo-common/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.extensionloader.ext8_add.AddExt1 @@ -0,0 +1 @@ +impl1=com.alibaba.dubbo.common.extensionloader.ext8_add.impl.AddExt1Impl1 \ No newline at end of file From 3f8e47f43c2656ace28165cde8a4d64013922643 Mon Sep 17 00:00:00 2001 From: oldrat Date: Wed, 5 Sep 2012 16:42:08 +0800 Subject: [PATCH 059/200] =?UTF-8?q?DUBBO-592=20=E6=B7=BB=E5=8A=A0Extension?= =?UTF-8?q?Loader=E4=BD=BF=E7=94=A8Adaptive=E7=B1=BB=E7=9A=84UT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ExtensionLoader_Adaptive_Test.java | 10 ++++++ .../adaptive/HasAdaptiveExt.java | 14 ++++++++ .../adaptive/impl/HasAdaptiveExtImpl1.java | 28 ++++++++++++++++ .../impl/HasAdaptiveExt_ManualAdaptive.java | 32 +++++++++++++++++++ .../compatible/CompatibleExt.java | 1 - ...on.extensionloader.adaptive.HasAdaptiveExt | 2 ++ 6 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/HasAdaptiveExt.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/impl/HasAdaptiveExtImpl1.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/impl/HasAdaptiveExt_ManualAdaptive.java create mode 100644 dubbo-common/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.extensionloader.adaptive.HasAdaptiveExt diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoader_Adaptive_Test.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoader_Adaptive_Test.java index 93913596848f..1d91a73505ab 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoader_Adaptive_Test.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/ExtensionLoader_Adaptive_Test.java @@ -17,6 +17,8 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.extensionloader.adaptive.HasAdaptiveExt; +import com.alibaba.dubbo.common.extensionloader.adaptive.impl.HasAdaptiveExt_ManualAdaptive; import com.alibaba.dubbo.common.extensionloader.ext1.SimpleExt; import com.alibaba.dubbo.common.extensionloader.ext2.Ext2; import com.alibaba.dubbo.common.extensionloader.ext2.UrlHolder; @@ -39,6 +41,14 @@ * @author ding.lid */ public class ExtensionLoader_Adaptive_Test { + + @Test + public void test_useAdaptiveClass() throws Exception { + ExtensionLoader loader = ExtensionLoader.getExtensionLoader(HasAdaptiveExt.class); + HasAdaptiveExt ext = loader.getAdaptiveExtension(); + assertTrue(ext instanceof HasAdaptiveExt_ManualAdaptive); + } + @Test public void test_getAdaptiveExtension_defaultAdaptiveKey() throws Exception { { diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/HasAdaptiveExt.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/HasAdaptiveExt.java new file mode 100644 index 000000000000..442b169c2f56 --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/HasAdaptiveExt.java @@ -0,0 +1,14 @@ +package com.alibaba.dubbo.common.extensionloader.adaptive; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.SPI; + +/** + * @author ding.lid + */ +@SPI +public interface HasAdaptiveExt { + @Adaptive + String echo(URL url, String s); +} diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/impl/HasAdaptiveExtImpl1.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/impl/HasAdaptiveExtImpl1.java new file mode 100644 index 000000000000..7589cd466e95 --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/impl/HasAdaptiveExtImpl1.java @@ -0,0 +1,28 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.adaptive.impl; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extensionloader.adaptive.HasAdaptiveExt; + +/** + * @author ding.lid + */ +public class HasAdaptiveExtImpl1 implements HasAdaptiveExt { + public String echo(URL url, String s) { + return this.getClass().getSimpleName(); + } +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/impl/HasAdaptiveExt_ManualAdaptive.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/impl/HasAdaptiveExt_ManualAdaptive.java new file mode 100644 index 000000000000..9918b3144e11 --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/adaptive/impl/HasAdaptiveExt_ManualAdaptive.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.extensionloader.adaptive.impl; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.extensionloader.adaptive.HasAdaptiveExt; + +/** + * @author ding.lid + */ +@Adaptive +public class HasAdaptiveExt_ManualAdaptive implements HasAdaptiveExt { + public String echo(URL url, String s) { + HasAdaptiveExt addExt1 = ExtensionLoader.getExtensionLoader(HasAdaptiveExt.class).getExtension(url.getParameter("key")); + return addExt1.echo(url, s); + } +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/compatible/CompatibleExt.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/compatible/CompatibleExt.java index 21b3eb183f75..b08340d25753 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/compatible/CompatibleExt.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/extensionloader/compatible/CompatibleExt.java @@ -20,7 +20,6 @@ import com.alibaba.dubbo.common.extension.SPI; /** - * * @author ding.lid */ @SPI("impl1") diff --git a/dubbo-common/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.extensionloader.adaptive.HasAdaptiveExt b/dubbo-common/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.extensionloader.adaptive.HasAdaptiveExt new file mode 100644 index 000000000000..c700dbd7c263 --- /dev/null +++ b/dubbo-common/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.extensionloader.adaptive.HasAdaptiveExt @@ -0,0 +1,2 @@ +adaptive=com.alibaba.dubbo.common.extensionloader.adaptive.impl.HasAdaptiveExt_ManualAdaptive +impl1=com.alibaba.dubbo.common.extensionloader.adaptive.impl.HasAdaptiveExtImpl1 \ No newline at end of file From e17270222f9840f330ce37a98260aff4cf2136c1 Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 6 Sep 2012 17:49:08 +0800 Subject: [PATCH 060/200] =?UTF-8?q?DUBBO-589=20=E5=9C=A8=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?Router=E4=B9=8B=E5=89=8D=E5=85=88=E5=AF=B9Router=E6=8E=92?= =?UTF-8?q?=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cluster/directory/AbstractDirectory.java | 164 +++++++++--------- 1 file changed, 83 insertions(+), 81 deletions(-) diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/directory/AbstractDirectory.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/directory/AbstractDirectory.java index 017af5940ae5..622cc06d03f4 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/directory/AbstractDirectory.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/directory/AbstractDirectory.java @@ -1,66 +1,67 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.cluster.directory; -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.cluster.Directory; -import com.alibaba.dubbo.rpc.cluster.Router; -import com.alibaba.dubbo.rpc.cluster.RouterFactory; -import com.alibaba.dubbo.rpc.cluster.router.MockInvokersSelector; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.rpc.Invocation; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.cluster.Directory; +import com.alibaba.dubbo.rpc.cluster.Router; +import com.alibaba.dubbo.rpc.cluster.RouterFactory; +import com.alibaba.dubbo.rpc.cluster.router.MockInvokersSelector; /** - * 澧炲姞router鐨凞irectory + * 澧炲姞router鐨凞irectory * * @author chao.liuc */ public abstract class AbstractDirectory implements Directory { - - // 鏃ュ織杈撳嚭 - private static final Logger logger = LoggerFactory.getLogger(AbstractDirectory.class); - private final URL url ; + // 鏃ュ織杈撳嚭 + private static final Logger logger = LoggerFactory.getLogger(AbstractDirectory.class); + + private final URL url ; private volatile boolean destroyed = false; - - private volatile URL consumerUrl ; - + + private volatile URL consumerUrl ; + private volatile List routers; public AbstractDirectory(URL url) { this(url, null); - } - - public AbstractDirectory(URL url, List routers) { - this(url, url, routers); + } + + public AbstractDirectory(URL url, List routers) { + this(url, url, routers); } public AbstractDirectory(URL url, URL consumerUrl, List routers) { if (url == null) throw new IllegalArgumentException("url == null"); - this.url = url; + this.url = url; this.consumerUrl = consumerUrl; setRouters(routers); } @@ -69,19 +70,19 @@ public List> list(Invocation invocation) throws RpcException { if (destroyed){ throw new RpcException("Directory already destroyed .url: "+ getUrl()); } - List> invokers = doList(invocation); - List localRouters = this.routers; // local reference - if (localRouters != null && localRouters.size() > 0) { - for (Router router: localRouters){ - try { + List> invokers = doList(invocation); + List localRouters = this.routers; // local reference + if (localRouters != null && localRouters.size() > 0) { + for (Router router: localRouters){ + try { if (router.getUrl() == null || router.getUrl().getParameter(Constants.RUNTIME_KEY, true)) { - invokers = router.route(invokers, getConsumerUrl(), invocation); - } - } catch (Throwable t) { - logger.error("Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), t); + invokers = router.route(invokers, getConsumerUrl(), invocation); + } + } catch (Throwable t) { + logger.error("Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), t); } - } - } + } + } return invokers; } @@ -91,38 +92,39 @@ public URL getUrl() { public List getRouters(){ return routers; - } - - public URL getConsumerUrl() { - return consumerUrl; - } - - public void setConsumerUrl(URL consumerUrl) { - this.consumerUrl = consumerUrl; - } + } + + public URL getConsumerUrl() { + return consumerUrl; + } - protected void setRouters(List routers){ - // copy list - routers = routers == null ? new ArrayList() : new ArrayList(routers); - // append url router - String routerkey = url.getParameter(Constants.ROUTER_KEY); - if (routerkey != null && routerkey.length() > 0) { - RouterFactory routerFactory = ExtensionLoader.getExtensionLoader(RouterFactory.class).getExtension(routerkey); - routers.add(routerFactory.getRouter(url)); - } - // append mock invoker selector - routers.add(new MockInvokersSelector()); + public void setConsumerUrl(URL consumerUrl) { + this.consumerUrl = consumerUrl; + } + + protected void setRouters(List routers){ + // copy list + routers = routers == null ? new ArrayList() : new ArrayList(routers); + // append url router + String routerkey = url.getParameter(Constants.ROUTER_KEY); + if (routerkey != null && routerkey.length() > 0) { + RouterFactory routerFactory = ExtensionLoader.getExtensionLoader(RouterFactory.class).getExtension(routerkey); + routers.add(routerFactory.getRouter(url)); + } + // append mock invoker selector + routers.add(new MockInvokersSelector()); + Collections.sort(routers); this.routers = routers; } - - public boolean isDestroyed() { - return destroyed; - } + + public boolean isDestroyed() { + return destroyed; + } public void destroy(){ destroyed = true; - } - - protected abstract List> doList(Invocation invocation) throws RpcException ; + } + + protected abstract List> doList(Invocation invocation) throws RpcException ; } \ No newline at end of file From b25f1dc780bf8dfc2f10acc231f8230a4938c565 Mon Sep 17 00:00:00 2001 From: kimi Date: Wed, 12 Sep 2012 18:33:01 +0800 Subject: [PATCH 061/200] =?UTF-8?q?=E6=B7=BB=E5=8A=A0log=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/common/utils/LogHelper.java | 179 ++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/LogHelper.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/LogHelper.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/LogHelper.java new file mode 100644 index 000000000000..92a51c977454 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/LogHelper.java @@ -0,0 +1,179 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.common.utils; + +import com.alibaba.dubbo.common.logger.Logger; + +/** + * @author kimi + */ +public class LogHelper { + + public static void trace(Logger logger, String msg) { + if (logger == null) { + return; + } + + if (logger.isTraceEnabled()) { + logger.trace(msg); + } + } + + public static void trace(Logger logger, Throwable throwable) { + if (logger == null) { + return; + } + + if (logger.isTraceEnabled()) { + logger.trace(throwable); + } + } + + public static void trace(Logger logger, String msg, Throwable e) { + if (logger == null) { + return; + } + + if (logger.isTraceEnabled()) { + logger.trace(msg, e); + } + } + + public static void debug(Logger logger, String msg) { + if (logger == null) { + return; + } + + if (logger.isDebugEnabled()) { + logger.debug(msg); + } + } + + public static void debug(Logger logger, Throwable e) { + if (logger == null) { + return; + } + + if (logger.isDebugEnabled()) { + logger.debug(e); + } + } + + public static void debug(Logger logger, String msg, Throwable e) { + if (logger == null) { + return; + } + + if (logger.isDebugEnabled()) { + logger.debug(msg, e); + } + } + + public static void info(Logger logger, String msg) { + if (logger == null) { + return; + } + + if (logger.isInfoEnabled()) { + logger.info(msg); + } + } + + public static void info(Logger logger, Throwable e) { + if (logger == null) { + return; + } + + if (logger.isInfoEnabled()) { + logger.info(e); + } + } + + public static void info(Logger logger, String msg, Throwable e) { + if (logger == null) { + return; + } + + if (logger.isInfoEnabled()) { + logger.info(msg, e); + } + } + + public static void warn(Logger logger, String msg, Throwable e) { + if (logger == null) { + return; + } + + if (logger.isWarnEnabled()) { + logger.warn(msg, e); + } + } + + public static void warn(Logger logger, String msg) { + if (logger == null) { + return; + } + + if (logger.isWarnEnabled()) { + logger.warn(msg); + } + } + + public static void warn(Logger logger, Throwable e) { + if (logger == null) { + return; + } + + if (logger.isWarnEnabled()) { + logger.warn(e); + } + } + + public static void error(Logger logger, Throwable e) { + if (logger == null) { + return; + } + + if (logger.isErrorEnabled()) { + logger.error(e); + } + } + + public static void error(Logger logger, String msg) { + if (logger == null) { + return; + } + + if (logger.isErrorEnabled()) { + logger.error(msg); + } + } + + public static void error(Logger logger, String msg, Throwable e) { + if (logger == null) { + return; + } + + if (logger.isErrorEnabled()) { + logger.error(msg, e); + } + } + + private LogHelper() { + } + +} From 1ad013314719b74018e434cd87b5a9f855c09dc4 Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 13 Sep 2012 14:26:04 +0800 Subject: [PATCH 062/200] =?UTF-8?q?DUBBO-589=20=E5=9C=A8=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?Router=E4=B9=8B=E5=89=8D=E5=85=88=E5=AF=B9Router=E6=8E=92?= =?UTF-8?q?=E5=BA=8F=EF=BC=8C=E4=BF=AE=E5=A4=8D=E5=A4=B1=E8=B4=A5=E7=9A=84?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/registry/dubbo/RegistryDirectoryTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/RegistryDirectoryTest.java index cca1ab8020a2..58f5aed00594 100644 --- a/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ b/dubbo-registry/dubbo-registry-default/src/test/java/com/alibaba/dubbo/registry/dubbo/RegistryDirectoryTest.java @@ -550,12 +550,12 @@ public void testNotifyRouterUrls() { List routers = registryDirectory.getRouters(); //default invocation selector Assert.assertEquals(1+1, routers.size()); - Assert.assertEquals(ScriptRouter.class, routers.get(0).getClass()); + Assert.assertEquals(ScriptRouter.class, routers.get(1).getClass()); registryDirectory.notify(new ArrayList()); routers = registryDirectory.getRouters(); Assert.assertEquals(1 + 1, routers.size()); - Assert.assertEquals(ScriptRouter.class, routers.get(0).getClass()); + Assert.assertEquals(ScriptRouter.class, routers.get(1).getClass()); serviceUrls.clear(); serviceUrls.add(routerurl.addParameter(Constants.ROUTER_KEY, Constants.ROUTER_TYPE_CLEAR)); From 4ecaddfd6bf22168f4c3e37bdc53a6ab24b17629 Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 13 Sep 2012 16:11:45 +0800 Subject: [PATCH 063/200] =?UTF-8?q?DUBBO-596=20decode=E5=A4=9A=E4=B8=AAmes?= =?UTF-8?q?sage=E6=97=B6=E4=BD=BF=E7=94=A8=E6=99=AE=E9=80=9A=E7=9A=84List?= =?UTF-8?q?=E4=BD=9C=E4=B8=BA=E5=A4=9A=E4=B8=AAmessage=E7=9A=84=E5=AE=B9?= =?UTF-8?q?=E5=99=A8=E4=BC=9A=E4=BD=BFclient/server=E4=B8=8D=E8=83=BD?= =?UTF-8?q?=E5=8F=91=E9=80=81/=E6=8E=A5=E5=8F=97List=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E7=9A=84=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/common/utils/MessageCollection.java | 83 +++++++++++++++++++ .../transport/MultiMessageHandler.java | 7 +- .../rpc/protocol/dubbo/DubboCountCodec.java | 7 +- 3 files changed, 89 insertions(+), 8 deletions(-) create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MessageCollection.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MessageCollection.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MessageCollection.java new file mode 100644 index 000000000000..b1db3e89294d --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MessageCollection.java @@ -0,0 +1,83 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.common.utils; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +/** + * @author kimi + */ +public final class MessageCollection implements Iterable { + + public static MessageCollection createFromCollection(Collection collection) { + MessageCollection result = new MessageCollection(); + result.addMessages(collection); + return result; + } + + public static MessageCollection createFromArray(Object... args) { + return createFromCollection(Arrays.asList(args)); + } + + public static MessageCollection create() { + return new MessageCollection(); + } + + private final List messages = new ArrayList(); + + private MessageCollection() {} + + public void addMessage(Object msg) { + messages.add(msg); + } + + public void addMessages(Collection collection) { + messages.addAll(collection); + } + + public Collection getMessages() { + return Collections.unmodifiableCollection(messages); + } + + public int size() { + return messages.size(); + } + + public Object get(int index) { + return messages.get(index); + } + + public boolean isEmpty() { + return messages.isEmpty(); + } + + public Collection removeMessages() { + Collection result = Collections.unmodifiableCollection(messages); + messages.clear(); + return result; + } + + public Iterator iterator() { + return messages.iterator(); + } + +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java index a4fc5e710684..7100fd84f7e2 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java @@ -1,7 +1,6 @@ package com.alibaba.dubbo.remoting.transport; -import java.util.List; - +import com.alibaba.dubbo.common.utils.MessageCollection; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; @@ -18,8 +17,8 @@ public MultiMessageHandler(ChannelHandler handler) { @SuppressWarnings("unchecked") @Override public void received(Channel channel, Object message) throws RemotingException { - if (message instanceof List) { - List list = (List)message; + if (message instanceof MessageCollection) { + MessageCollection list = (MessageCollection)message; for(Object obj : list) { handler.received(channel, obj); } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java index 42e08f352421..1cd8ccbaa0bf 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java @@ -19,11 +19,10 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; +import com.alibaba.dubbo.common.utils.MessageCollection; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.exchange.Request; @@ -45,14 +44,14 @@ public void encode(Channel channel, OutputStream output, Object msg) throws IOEx public Object decode(Channel channel, InputStream input) throws IOException { UnsafeByteArrayInputStream bis = (UnsafeByteArrayInputStream)input; int save = bis.position(); - List result = new ArrayList(); + MessageCollection result = MessageCollection.create(); do { Object obj = codec.decode(channel, bis); if (NEED_MORE_INPUT == obj) { bis.position(save); break; } else { - result.add(obj); + result.addMessage(obj); logMessageLength(obj, bis.position() - save); save = bis.position(); } From 28f39a606bd0f3498bcd2b071504a41c5dcda746 Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 13 Sep 2012 16:28:17 +0800 Subject: [PATCH 064/200] =?UTF-8?q?DUBBO-596=20decode=E5=A4=9A=E4=B8=AAmes?= =?UTF-8?q?sage=E6=97=B6=E4=BD=BF=E7=94=A8=E6=99=AE=E9=80=9A=E7=9A=84List?= =?UTF-8?q?=E4=BD=9C=E4=B8=BA=E5=A4=9A=E4=B8=AAmessage=E7=9A=84=E5=AE=B9?= =?UTF-8?q?=E5=99=A8=E4=BC=9A=E4=BD=BFclient/server=E4=B8=8D=E8=83=BD?= =?UTF-8?q?=E5=8F=91=E9=80=81/=E6=8E=A5=E5=8F=97List=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E7=9A=84=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../utils => remoting/exchange/support}/MessageCollection.java | 2 +- .../alibaba/dubbo/remoting/transport/MultiMessageHandler.java | 2 +- .../com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename dubbo-common/src/main/java/com/alibaba/dubbo/{common/utils => remoting/exchange/support}/MessageCollection.java (97%) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MessageCollection.java b/dubbo-common/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MessageCollection.java similarity index 97% rename from dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MessageCollection.java rename to dubbo-common/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MessageCollection.java index b1db3e89294d..0a9386e25ff4 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/MessageCollection.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MessageCollection.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package com.alibaba.dubbo.common.utils; +package com.alibaba.dubbo.remoting.exchange.support; import java.util.ArrayList; import java.util.Arrays; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java index 7100fd84f7e2..1f50058207da 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java @@ -1,6 +1,6 @@ package com.alibaba.dubbo.remoting.transport; -import com.alibaba.dubbo.common.utils.MessageCollection; +import com.alibaba.dubbo.remoting.exchange.support.MessageCollection; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java index 1cd8ccbaa0bf..8ae38e13dd10 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java @@ -22,7 +22,7 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; -import com.alibaba.dubbo.common.utils.MessageCollection; +import com.alibaba.dubbo.remoting.exchange.support.MessageCollection; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.exchange.Request; From 95f22d0a4f0c00d5e6f0964319cd62b7c5b03a0c Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 13 Sep 2012 16:31:25 +0800 Subject: [PATCH 065/200] =?UTF-8?q?DUBBO-596=20decode=E5=A4=9A=E4=B8=AAmes?= =?UTF-8?q?sage=E6=97=B6=E4=BD=BF=E7=94=A8=E6=99=AE=E9=80=9A=E7=9A=84List?= =?UTF-8?q?=E4=BD=9C=E4=B8=BA=E5=A4=9A=E4=B8=AAmessage=E7=9A=84=E5=AE=B9?= =?UTF-8?q?=E5=99=A8=E4=BC=9A=E4=BD=BFclient/server=E4=B8=8D=E8=83=BD?= =?UTF-8?q?=E5=8F=91=E9=80=81/=E6=8E=A5=E5=8F=97List=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E7=9A=84=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/remoting/exchange/support/MessageCollection.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {dubbo-common => dubbo-remoting/dubbo-remoting-api}/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MessageCollection.java (100%) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MessageCollection.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MessageCollection.java similarity index 100% rename from dubbo-common/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MessageCollection.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MessageCollection.java From 5aaa11bfa032e812de646448bca1c4624059c5ab Mon Sep 17 00:00:00 2001 From: kimi Date: Fri, 14 Sep 2012 14:23:43 +0800 Subject: [PATCH 066/200] =?UTF-8?q?DUBBO-596=20decode=E5=A4=9A=E4=B8=AAmes?= =?UTF-8?q?sage=E6=97=B6=E4=BD=BF=E7=94=A8=E6=99=AE=E9=80=9A=E7=9A=84List?= =?UTF-8?q?=E4=BD=9C=E4=B8=BA=E5=A4=9A=E4=B8=AAmessage=E7=9A=84=E5=AE=B9?= =?UTF-8?q?=E5=99=A8=E4=BC=9A=E4=BD=BFclient/server=E4=B8=8D=E8=83=BD?= =?UTF-8?q?=E5=8F=91=E9=80=81/=E6=8E=A5=E5=8F=97List=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E7=9A=84=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{MessageCollection.java => MultiMessage.java} | 14 +++++++------- .../remoting/transport/MultiMessageHandler.java | 7 ++++--- .../dubbo/rpc/protocol/dubbo/DubboCountCodec.java | 5 +++-- 3 files changed, 14 insertions(+), 12 deletions(-) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/{MessageCollection.java => MultiMessage.java} (82%) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MessageCollection.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MultiMessage.java similarity index 82% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MessageCollection.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MultiMessage.java index 0a9386e25ff4..d35cb8294306 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MessageCollection.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MultiMessage.java @@ -26,25 +26,25 @@ /** * @author kimi */ -public final class MessageCollection implements Iterable { +public final class MultiMessage implements Iterable { - public static MessageCollection createFromCollection(Collection collection) { - MessageCollection result = new MessageCollection(); + public static MultiMessage createFromCollection(Collection collection) { + MultiMessage result = new MultiMessage(); result.addMessages(collection); return result; } - public static MessageCollection createFromArray(Object... args) { + public static MultiMessage createFromArray(Object... args) { return createFromCollection(Arrays.asList(args)); } - public static MessageCollection create() { - return new MessageCollection(); + public static MultiMessage create() { + return new MultiMessage(); } private final List messages = new ArrayList(); - private MessageCollection() {} + private MultiMessage() {} public void addMessage(Object msg) { messages.add(msg); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java index 1f50058207da..5f0df64c6af1 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java @@ -1,9 +1,10 @@ package com.alibaba.dubbo.remoting.transport; -import com.alibaba.dubbo.remoting.exchange.support.MessageCollection; +import com.alibaba.dubbo.remoting.exchange.support.MultiMessage; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exchange.support.MultiMessage; /** * @author kimi @@ -17,8 +18,8 @@ public MultiMessageHandler(ChannelHandler handler) { @SuppressWarnings("unchecked") @Override public void received(Channel channel, Object message) throws RemotingException { - if (message instanceof MessageCollection) { - MessageCollection list = (MessageCollection)message; + if (message instanceof MultiMessage) { + MultiMessage list = (MultiMessage)message; for(Object obj : list) { handler.received(channel, obj); } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java index 8ae38e13dd10..e8ace97b7e52 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java @@ -22,11 +22,12 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; -import com.alibaba.dubbo.remoting.exchange.support.MessageCollection; +import com.alibaba.dubbo.remoting.exchange.support.MultiMessage; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.exchange.support.MultiMessage; import com.alibaba.dubbo.rpc.RpcInvocation; import com.alibaba.dubbo.rpc.RpcResult; @@ -44,7 +45,7 @@ public void encode(Channel channel, OutputStream output, Object msg) throws IOEx public Object decode(Channel channel, InputStream input) throws IOException { UnsafeByteArrayInputStream bis = (UnsafeByteArrayInputStream)input; int save = bis.position(); - MessageCollection result = MessageCollection.create(); + MultiMessage result = MultiMessage.create(); do { Object obj = codec.decode(channel, bis); if (NEED_MORE_INPUT == obj) { From 228338e64dbeca50e8fe13940b5d0e8af89c51e0 Mon Sep 17 00:00:00 2001 From: oldrat Date: Mon, 17 Sep 2012 14:18:47 +0800 Subject: [PATCH 067/200] update javadoc --- .../alibaba/dubbo/remoting/exchange/support/MultiMessage.java | 1 + .../alibaba/dubbo/remoting/transport/MultiMessageHandler.java | 1 + 2 files changed, 2 insertions(+) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MultiMessage.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MultiMessage.java index d35cb8294306..a78ed09fc9af 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MultiMessage.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/support/MultiMessage.java @@ -25,6 +25,7 @@ /** * @author kimi + * @see com.alibaba.dubbo.remoting.transport.MultiMessageHandler */ public final class MultiMessage implements Iterable { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java index 5f0df64c6af1..032f47c19c44 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/MultiMessageHandler.java @@ -8,6 +8,7 @@ /** * @author kimi + * @see MultiMessage */ public class MultiMessageHandler extends AbstractChannelHandlerDelegate { From c48b87e83585b0a90e648a0857ab531756186733 Mon Sep 17 00:00:00 2001 From: kimi Date: Mon, 24 Sep 2012 11:41:38 +0800 Subject: [PATCH 068/200] update version to 2.5.3-SNAPSHOT --- dubbo-admin/pom.xml | 2 +- dubbo-cluster/pom.xml | 2 +- dubbo-common/pom.xml | 2 +- dubbo-config/dubbo-config-api/pom.xml | 2 +- dubbo-config/dubbo-config-spring/pom.xml | 2 +- dubbo-config/pom.xml | 2 +- dubbo-container/dubbo-container-api/pom.xml | 2 +- dubbo-container/dubbo-container-jetty/pom.xml | 2 +- dubbo-container/dubbo-container-log4j/pom.xml | 2 +- dubbo-container/dubbo-container-logback/pom.xml | 2 +- dubbo-container/dubbo-container-spring/pom.xml | 2 +- dubbo-container/pom.xml | 2 +- dubbo-demo/dubbo-demo-api/pom.xml | 2 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 2 +- dubbo-demo/dubbo-demo-provider/pom.xml | 2 +- dubbo-demo/pom.xml | 2 +- dubbo-filter/dubbo-filter-cache/pom.xml | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 2 +- dubbo-filter/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +- dubbo-monitor/pom.xml | 2 +- dubbo-registry/dubbo-registry-api/pom.xml | 2 +- dubbo-registry/dubbo-registry-default/pom.xml | 2 +- dubbo-registry/dubbo-registry-multicast/pom.xml | 2 +- dubbo-registry/dubbo-registry-redis/pom.xml | 2 +- dubbo-registry/dubbo-registry-zookeeper/pom.xml | 2 +- dubbo-registry/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-p2p/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-zookeeper/pom.xml | 2 +- dubbo-remoting/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-default/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 2 +- dubbo-rpc/pom.xml | 2 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 2 +- dubbo-simple/dubbo-registry-simple/pom.xml | 2 +- dubbo-simple/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark/pom.xml | 2 +- dubbo-test/dubbo-test-compatibility/pom.xml | 2 +- dubbo-test/dubbo-test-examples/pom.xml | 2 +- dubbo-test/dubbo-test-integration/pom.xml | 2 +- dubbo-test/pom.xml | 2 +- dubbo/pom.xml | 2 +- pom.xml | 2 +- 57 files changed, 57 insertions(+), 57 deletions(-) diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index 65427c5286e6..d72e33daec26 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-admin war diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index 470653b47018..fcb7c6e700de 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-cluster jar diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index a0fd8cb71cf5..fb381c58c115 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-common jar diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 700125466365..786b29dc81ba 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-config-api jar diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 800faf21611e..c02089df87f0 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-config-spring jar diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index 37ff9e674ada..9e2a66c1cf14 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index b330d5932ddc..ae8b39da87bb 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-container-api jar diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index 31ec7bf7e871..fd5e6b8e7795 100644 --- a/dubbo-container/dubbo-container-jetty/pom.xml +++ b/dubbo-container/dubbo-container-jetty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index dfb95377b5e1..8c6cbd2272a0 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index 0542a36e8756..c873cfb084e3 100644 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ b/dubbo-container/dubbo-container-logback/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index 7cd1f0ac568c..83c13668ca0f 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-container-spring jar diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index bce54e53ed94..0de335044872 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-container pom diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index 188cdd7e9615..e755624a57b7 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-demo-api jar diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml index df5086d43205..37eae52db210 100644 --- a/dubbo-demo/dubbo-demo-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-demo-consumer jar diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml index eaa4e2ebf729..c76d5807c408 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-demo-provider jar diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index 6a392eebda00..db063c2b1b65 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-demo pom diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 80aa42f36348..362f8d582337 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index 23f0b647ceb9..c5add7aaf69a 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index 865f6d825a38..7fb80e708f17 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-filter pom diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index 9d94daabf508..f4359b03b424 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index 3986a24c9273..c3d4c0d4249d 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index 5c1566e83a93..8f07a90dfdfa 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index ef5bced28db5..776758ea8c55 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index 00d3248bee36..1c46630e9ba5 100644 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ b/dubbo-registry/dubbo-registry-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-registry-default jar diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index 1b5de58e6259..9316731eedd0 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index 01a474c41ab8..3ac6c6d31b86 100644 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ b/dubbo-registry/dubbo-registry-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-registry-redis jar diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index 02f5dee90e8b..762bba899ae3 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-registry-zookeeper jar diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index 1a2e3abfe5c6..2692390f29ed 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-registry pom diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index d3a2c690a397..ed94b1f11a25 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-remoting-api jar diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml index f050cbfc94b3..7ebd6db8b4a8 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml +++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-remoting-grizzly jar diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index ebd369322707..a17b281c3413 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-remoting-http jar diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml index e5f5f24ae7e2..50a90f59b4bb 100644 --- a/dubbo-remoting/dubbo-remoting-mina/pom.xml +++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-remoting-mina jar diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index b0d78e0e5cb2..1cafe96cdc56 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-remoting-netty jar diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml index f9d38a7a4d39..be6179a49016 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml +++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-remoting-p2p jar diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index 27f59dfa5622..120055e22be0 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-remoting-zookeeper jar diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 85ac02f08d7d..92abba7b4077 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-remoting pom diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index c6d87b449dee..f15fa164effa 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-rpc-api jar diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index a51e8c4e83fe..c501d447ec81 100644 --- a/dubbo-rpc/dubbo-rpc-default/pom.xml +++ b/dubbo-rpc/dubbo-rpc-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-rpc-default jar diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index 1fdc5b3409af..4fe91df80916 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-rpc-hessian jar diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index c0a0d714d187..239a289fcba6 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-rpc-http jar diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index a25021bad66f..93fdbe7d7279 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml +++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-rpc-injvm jar diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml index fcbea65efec6..0b18b013b3c4 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml +++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-rpc-memcached jar diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml index 07b38ef4f848..51b0ba3ff2ef 100644 --- a/dubbo-rpc/dubbo-rpc-redis/pom.xml +++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-rpc-redis jar diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml index 5c2df6dd7ca2..81d1130b4dca 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-rpc-rmi jar diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml index 687406fe6a14..683574679c20 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ b/dubbo-rpc/dubbo-rpc-thrift/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-rpc-thrift jar diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml index 147375c4304b..a0eccfb84753 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml +++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-rpc-webservice jar diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 5f1421a823ca..50c0b20da5c3 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-rpc pom diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml index ec4130c8ca9a..6b5a45a402e3 100644 --- a/dubbo-simple/dubbo-monitor-simple/pom.xml +++ b/dubbo-simple/dubbo-monitor-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-monitor-simple jar diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml index 7c70d56ee906..f645af1ef958 100644 --- a/dubbo-simple/dubbo-registry-simple/pom.xml +++ b/dubbo-simple/dubbo-registry-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-registry-simple jar diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml index 709e01a15add..3b2dc07636e4 100644 --- a/dubbo-simple/pom.xml +++ b/dubbo-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-simple pom diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml index 5dd16c20547a..775f370a4cfd 100644 --- a/dubbo-test/dubbo-test-benchmark/pom.xml +++ b/dubbo-test/dubbo-test-benchmark/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-test-benchmark jar diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml index 75315e9aa22e..116db9a0c707 100644 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ b/dubbo-test/dubbo-test-compatibility/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-test-compatibility jar diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index bdf23a6e0ec8..913063d5c07b 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-test-examples jar diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml index b822a6c757dc..9aebf178f9f5 100644 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ b/dubbo-test/dubbo-test-integration/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-test-integration jar diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml index 12a66b4a528e..c3899ebf07d9 100644 --- a/dubbo-test/pom.xml +++ b/dubbo-test/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo-test pom diff --git a/dubbo/pom.xml b/dubbo/pom.xml index b11cea48e01e..c7971e04f25c 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT dubbo jar diff --git a/pom.xml b/pom.xml index 052b8052ead7..cdd70cef29b0 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ 2.0 dubbo-parent - 2.5.2-SNAPSHOT + 2.5.3-SNAPSHOT pom ${project.artifactId} The parent project of dubbo From 8c17025b96f715412459ae7124fc1f8054c10119 Mon Sep 17 00:00:00 2001 From: kimi Date: Mon, 8 Oct 2012 11:07:56 +0800 Subject: [PATCH 069/200] =?UTF-8?q?DUBBO-603=20=E8=AE=BE=E7=BD=AE=20netty?= =?UTF-8?q?=20logger=20factory=20=E4=BD=BF=20netty=20=E8=83=BD=E6=AD=A3?= =?UTF-8?q?=E7=A1=AE=E6=89=93=E5=8D=B0=20log?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../remoting/transport/netty/NettyClient.java | 149 +++++++++--------- .../remoting/transport/netty/NettyHelper.java | 107 +++++++++++++ .../remoting/transport/netty/NettyServer.java | 1 + 3 files changed, 183 insertions(+), 74 deletions(-) create mode 100644 dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyHelper.java diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java index 59268af079ec..7825f88183fb 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.transport.netty; - +package com.alibaba.dubbo.remoting.transport.netty; + import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -37,53 +37,54 @@ import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.RemotingException; import com.alibaba.dubbo.remoting.transport.AbstractClient; - -/** - * NettyClient. - * - * @author qian.lei - * @author william.liangf - */ + +/** + * NettyClient. + * + * @author qian.lei + * @author william.liangf + */ public class NettyClient extends AbstractClient { - private static final Logger logger = LoggerFactory.getLogger(NettyClient.class); - - // 鍥燙hannelFactory鐨勫叧闂湁DirectMemory娉勯湶锛岄噰鐢ㄩ潤鎬佸寲瑙勯伩 - // https://issues.jboss.org/browse/NETTY-424 - private static final ChannelFactory channelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientBoss", true)), - Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientWorker", true)), - Constants.DEFAULT_IO_THREADS); - private ClientBootstrap bootstrap; - - private volatile Channel channel; // volatile, please copy reference to use - - public NettyClient(final URL url, final ChannelHandler handler) throws RemotingException{ - super(url, wrapChannelHandler(url, handler)); - } - - @Override - protected void doOpen() throws Throwable { - bootstrap = new ClientBootstrap(channelFactory); - // config - // @see org.jboss.netty.channel.socket.SocketChannelConfig - bootstrap.setOption("keepAlive", true); - bootstrap.setOption("tcpNoDelay", true); - bootstrap.setOption("connectTimeoutMillis", getTimeout()); - final NettyHandler nettyHandler = new NettyHandler(getUrl(), this); - bootstrap.setPipelineFactory(new ChannelPipelineFactory() { - public ChannelPipeline getPipeline() { - NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this); - ChannelPipeline pipeline = Channels.pipeline(); - pipeline.addLast("decoder", adapter.getDecoder()); - pipeline.addLast("encoder", adapter.getEncoder()); - pipeline.addLast("handler", nettyHandler); - return pipeline; - } - }); - } - + private static final Logger logger = LoggerFactory.getLogger(NettyClient.class); + + // 鍥燙hannelFactory鐨勫叧闂湁DirectMemory娉勯湶锛岄噰鐢ㄩ潤鎬佸寲瑙勯伩 + // https://issues.jboss.org/browse/NETTY-424 + private static final ChannelFactory channelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientBoss", true)), + Executors.newCachedThreadPool(new NamedThreadFactory("NettyClientWorker", true)), + Constants.DEFAULT_IO_THREADS); + private ClientBootstrap bootstrap; + + private volatile Channel channel; // volatile, please copy reference to use + + public NettyClient(final URL url, final ChannelHandler handler) throws RemotingException{ + super(url, wrapChannelHandler(url, handler)); + } + + @Override + protected void doOpen() throws Throwable { + NettyHelper.setNettyLoggerFactory(); + bootstrap = new ClientBootstrap(channelFactory); + // config + // @see org.jboss.netty.channel.socket.SocketChannelConfig + bootstrap.setOption("keepAlive", true); + bootstrap.setOption("tcpNoDelay", true); + bootstrap.setOption("connectTimeoutMillis", getTimeout()); + final NettyHandler nettyHandler = new NettyHandler(getUrl(), this); + bootstrap.setPipelineFactory(new ChannelPipelineFactory() { + public ChannelPipeline getPipeline() { + NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this); + ChannelPipeline pipeline = Channels.pipeline(); + pipeline.addLast("decoder", adapter.getDecoder()); + pipeline.addLast("encoder", adapter.getEncoder()); + pipeline.addLast("handler", nettyHandler); + return pipeline; + } + }); + } + protected void doConnect() throws Throwable { - long start = System.currentTimeMillis(); + long start = System.currentTimeMillis(); ChannelFuture future = bootstrap.connect(getConnectAddress()); try{ boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS); @@ -133,32 +134,32 @@ protected void doConnect() throws Throwable { future.cancel(); } } - } - - @Override - protected void doDisConnect() throws Throwable { - try { - NettyChannel.removeChannelIfDisconnected(channel); - } catch (Throwable t) { - logger.warn(t.getMessage()); - } - } - - @Override - protected void doClose() throws Throwable { - /*try { - bootstrap.releaseExternalResources(); - } catch (Throwable t) { - logger.warn(t.getMessage()); - }*/ - } - - @Override - protected com.alibaba.dubbo.remoting.Channel getChannel() { - Channel c = channel; - if (c == null || ! c.isConnected()) - return null; - return NettyChannel.getOrAddChannel(c, getUrl(), this); - } - + } + + @Override + protected void doDisConnect() throws Throwable { + try { + NettyChannel.removeChannelIfDisconnected(channel); + } catch (Throwable t) { + logger.warn(t.getMessage()); + } + } + + @Override + protected void doClose() throws Throwable { + /*try { + bootstrap.releaseExternalResources(); + } catch (Throwable t) { + logger.warn(t.getMessage()); + }*/ + } + + @Override + protected com.alibaba.dubbo.remoting.Channel getChannel() { + Channel c = channel; + if (c == null || ! c.isConnected()) + return null; + return NettyChannel.getOrAddChannel(c, getUrl(), this); + } + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyHelper.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyHelper.java new file mode 100644 index 000000000000..11c3c7dd6f6d --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyHelper.java @@ -0,0 +1,107 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.transport.netty; + +import org.jboss.netty.logging.AbstractInternalLogger; +import org.jboss.netty.logging.InternalLogger; +import org.jboss.netty.logging.InternalLoggerFactory; + +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; + +/** + * @author kimi + */ +final class NettyHelper { + + public static void setNettyLoggerFactory() { + InternalLoggerFactory factory = InternalLoggerFactory.getDefaultFactory(); + if (factory == null || !(factory instanceof DubboLoggerFactory)) { + InternalLoggerFactory.setDefaultFactory(new DubboLoggerFactory()); + } + } + + static class DubboLoggerFactory extends InternalLoggerFactory { + + @Override + public InternalLogger newInstance(String name) { + return new DubboLogger(LoggerFactory.getLogger(name)); + } + } + + static class DubboLogger extends AbstractInternalLogger { + + private Logger logger; + + DubboLogger(Logger logger) { + this.logger = logger; + } + + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + + public void debug(String msg) { + logger.debug(msg); + } + + public void debug(String msg, Throwable cause) { + logger.debug(msg, cause); + } + + public void info(String msg) { + logger.info(msg); + } + + public void info(String msg, Throwable cause) { + logger.info(msg, cause); + } + + public void warn(String msg) { + logger.warn(msg); + } + + public void warn(String msg, Throwable cause) { + logger.warn(msg, cause); + } + + public void error(String msg) { + logger.error(msg); + } + + public void error(String msg, Throwable cause) { + logger.error(msg, cause); + } + + @Override + public String toString() { + return logger.toString(); + } + } + +} diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java index af006355f9d8..8f7a92d1deb1 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyServer.java @@ -65,6 +65,7 @@ public NettyServer(URL url, ChannelHandler handler) throws RemotingException{ @Override protected void doOpen() throws Throwable { + NettyHelper.setNettyLoggerFactory(); ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true)); ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true)); ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS)); From 5ed0e9fa90f1be28f4fdc6a0ed57f38232fbe023 Mon Sep 17 00:00:00 2001 From: kimi Date: Mon, 15 Oct 2012 13:39:07 +0800 Subject: [PATCH 070/200] =?UTF-8?q?DUBBO-166=20=E5=A2=9E=E5=BC=BA=20codec?= =?UTF-8?q?=20=E9=81=BF=E5=85=8D=20copy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/remoting/ChannelCodec.java | 43 + .../com/alibaba/dubbo/remoting/Codec.java | 1 + .../buffer/AbstractChannelBuffer.java | 295 ++++++ .../buffer/ByteBufferBackedChannelBuffer.java | 244 +++++ .../dubbo/remoting/buffer/ChannelBuffer.java | 968 ++++++++++++++++++ .../remoting/buffer/ChannelBufferFactory.java | 32 + .../buffer/ChannelBufferInputStream.java | 111 ++ .../buffer/ChannelBufferOutputStream.java | 64 ++ .../dubbo/remoting/buffer/ChannelBuffers.java | 133 +++ .../buffer/DirectChannelBufferFactory.java | 77 ++ .../remoting/buffer/DynamicChannelBuffer.java | 193 ++++ .../remoting/buffer/HeapChannelBuffer.java | 202 ++++ .../buffer/HeapChannelBufferFactory.java | 56 + .../exchange/codec/ExchangeCodec.java | 76 +- .../remoting/telnet/codec/TelnetCodec.java | 274 +++-- .../remoting/transport/AbstractCodec.java | 4 +- .../remoting/transport/AbstractEndpoint.java | 80 +- .../transport/codec/ChannelCodecAdapter.java | 63 ++ .../transport/codec/TransportCodec.java | 9 +- ...> com.alibaba.dubbo.remoting.ChannelCodec} | 0 .../remoting/codec/ExchangeCodecTest.java | 113 +- .../dubbo/remoting/codec/TelnetCodecTest.java | 110 +- .../grizzly/GrizzlyCodecAdapter.java | 147 +-- .../transport/mina/MinaCodecAdapter.java | 181 ++-- .../netty/NettyBackedChannelBuffer.java | 376 +++++++ .../NettyBackedChannelBufferFactory.java | 39 + .../transport/netty/NettyCodecAdapter.java | 183 ++-- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 4 +- .../rpc/protocol/dubbo/DubboCountCodec.java | 27 +- ...> com.alibaba.dubbo.remoting.ChannelCodec} | 0 .../rpc/protocol/thrift/ThriftCodec.java | 77 +- .../protocol/thrift/ThriftNativeCodec.java | 26 +- ...> com.alibaba.dubbo.remoting.ChannelCodec} | 0 .../rpc/protocol/thrift/ThriftCodecTest.java | 57 +- 34 files changed, 3547 insertions(+), 718 deletions(-) create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ChannelCodec.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/AbstractChannelBuffer.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ByteBufferBackedChannelBuffer.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffer.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferFactory.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferInputStream.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferOutputStream.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffers.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/DirectChannelBufferFactory.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/DynamicChannelBuffer.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBuffer.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBufferFactory.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/ChannelCodecAdapter.java rename dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/{com.alibaba.dubbo.remoting.Codec => com.alibaba.dubbo.remoting.ChannelCodec} (100%) create mode 100644 dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyBackedChannelBuffer.java create mode 100644 dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyBackedChannelBufferFactory.java rename dubbo-rpc/dubbo-rpc-default/src/main/resources/META-INF/dubbo/internal/{com.alibaba.dubbo.remoting.Codec => com.alibaba.dubbo.remoting.ChannelCodec} (100%) rename dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/{com.alibaba.dubbo.remoting.Codec => com.alibaba.dubbo.remoting.ChannelCodec} (100%) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ChannelCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ChannelCodec.java new file mode 100644 index 000000000000..5303189b83c1 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ChannelCodec.java @@ -0,0 +1,43 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting; + +import java.io.IOException; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.extension.Adaptive; +import com.alibaba.dubbo.common.extension.SPI; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; + +/** + * @author kimi + */ +@SPI +public interface ChannelCodec { + + @Adaptive({Constants.CODEC_KEY}) + void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException; + + @Adaptive({Constants.CODEC_KEY}) + Object decode(Channel channel, ChannelBuffer buffer) throws IOException; + + + enum DecodeResult { + NEED_MORE_INPUT, SKIP_SOME_INPUT + } + +} + diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec.java index 8406f85d4b53..29e7be83ebab 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec.java @@ -30,6 +30,7 @@ * @author ding.lid * @author william.liangf */ +@Deprecated @SPI public interface Codec { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/AbstractChannelBuffer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/AbstractChannelBuffer.java new file mode 100644 index 000000000000..3b401afb5272 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/AbstractChannelBuffer.java @@ -0,0 +1,295 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; + +/** + * @author kimi + */ +public abstract class AbstractChannelBuffer implements ChannelBuffer { + + private int readerIndex; + + private int writerIndex; + + private int markedReaderIndex; + + private int markedWriterIndex; + + public int readerIndex() { + return readerIndex; + } + + public void readerIndex(int readerIndex) { + if (readerIndex < 0 || readerIndex > writerIndex) { + throw new IndexOutOfBoundsException(); + } + this.readerIndex = readerIndex; + } + + public int writerIndex() { + return writerIndex; + } + + public void writerIndex(int writerIndex) { + if (writerIndex < readerIndex || writerIndex > capacity()) { + throw new IndexOutOfBoundsException(); + } + this.writerIndex = writerIndex; + } + + public void setIndex(int readerIndex, int writerIndex) { + if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) { + throw new IndexOutOfBoundsException(); + } + this.readerIndex = readerIndex; + this.writerIndex = writerIndex; + } + + public void clear() { + readerIndex = writerIndex = 0; + } + + public boolean readable() { + return readableBytes() > 0; + } + + public boolean writable() { + return writableBytes() > 0; + } + + public int readableBytes() { + return writerIndex - readerIndex; + } + + public int writableBytes() { + return capacity() - writerIndex; + } + + public void markReaderIndex() { + markedReaderIndex = readerIndex; + } + + public void resetReaderIndex() { + readerIndex(markedReaderIndex); + } + + public void markWriterIndex() { + markedWriterIndex = writerIndex; + } + + public void resetWriterIndex() { + writerIndex = markedWriterIndex; + } + + public void discardReadBytes() { + if (readerIndex == 0) { + return; + } + setBytes(0, this, readerIndex, writerIndex - readerIndex); + writerIndex -= readerIndex; + markedReaderIndex = Math.max(markedReaderIndex - readerIndex, 0); + markedWriterIndex = Math.max(markedWriterIndex - readerIndex, 0); + readerIndex = 0; + } + + public void ensureWritableBytes(int writableBytes) { + if (writableBytes > writableBytes()) { + throw new IndexOutOfBoundsException(); + } + } + + public void getBytes(int index, byte[] dst) { + getBytes(index, dst, 0, dst.length); + } + + public void getBytes(int index, ChannelBuffer dst) { + getBytes(index, dst, dst.writableBytes()); + } + + public void getBytes(int index, ChannelBuffer dst, int length) { + if (length > dst.writableBytes()) { + throw new IndexOutOfBoundsException(); + } + getBytes(index, dst, dst.writerIndex(), length); + dst.writerIndex(dst.writerIndex() + length); + } + + public void setBytes(int index, byte[] src) { + setBytes(index, src, 0, src.length); + } + + public void setBytes(int index, ChannelBuffer src) { + setBytes(index, src, src.readableBytes()); + } + + public void setBytes(int index, ChannelBuffer src, int length) { + if (length > src.readableBytes()) { + throw new IndexOutOfBoundsException(); + } + setBytes(index, src, src.readerIndex(), length); + src.readerIndex(src.readerIndex() + length); + } + + public byte readByte() { + if (readerIndex == writerIndex) { + throw new IndexOutOfBoundsException(); + } + return getByte(readerIndex++); + } + + public ChannelBuffer readBytes(int length) { + checkReadableBytes(length); + if (length == 0) { + return ChannelBuffers.EMPTY_BUFFER; + } + ChannelBuffer buf = factory().getBuffer(length); + buf.writeBytes(this, readerIndex, length); + readerIndex += length; + return buf; + } + + public void readBytes(byte[] dst, int dstIndex, int length) { + checkReadableBytes(length); + getBytes(readerIndex, dst, dstIndex, length); + readerIndex += length; + } + + public void readBytes(byte[] dst) { + readBytes(dst, 0, dst.length); + } + + public void readBytes(ChannelBuffer dst) { + readBytes(dst, dst.writableBytes()); + } + + public void readBytes(ChannelBuffer dst, int length) { + if (length > dst.writableBytes()) { + throw new IndexOutOfBoundsException(); + } + readBytes(dst, dst.writerIndex(), length); + dst.writerIndex(dst.writerIndex() + length); + } + + public void readBytes(ChannelBuffer dst, int dstIndex, int length) { + checkReadableBytes(length); + getBytes(readerIndex, dst, dstIndex, length); + readerIndex += length; + } + + public void readBytes(ByteBuffer dst) { + int length = dst.remaining(); + checkReadableBytes(length); + getBytes(readerIndex, dst); + readerIndex += length; + } + + public void readBytes(OutputStream out, int length) throws IOException { + checkReadableBytes(length); + getBytes(readerIndex, out, length); + readerIndex += length; + } + + public void skipBytes(int length) { + int newReaderIndex = readerIndex + length; + if (newReaderIndex > writerIndex) { + throw new IndexOutOfBoundsException(); + } + readerIndex = newReaderIndex; + } + + public void writeByte(int value) { + setByte(writerIndex++, value); + } + + public void writeBytes(byte[] src, int srcIndex, int length) { + setBytes(writerIndex, src, srcIndex, length); + writerIndex += length; + } + + public void writeBytes(byte[] src) { + writeBytes(src, 0, src.length); + } + + public void writeBytes(ChannelBuffer src) { + writeBytes(src, src.readableBytes()); + } + + public void writeBytes(ChannelBuffer src, int length) { + if (length > src.readableBytes()) { + throw new IndexOutOfBoundsException(); + } + writeBytes(src, src.readerIndex(), length); + src.readerIndex(src.readerIndex() + length); + } + + public void writeBytes(ChannelBuffer src, int srcIndex, int length) { + setBytes(writerIndex, src, srcIndex, length); + writerIndex += length; + } + + public void writeBytes(ByteBuffer src) { + int length = src.remaining(); + setBytes(writerIndex, src); + writerIndex += length; + } + + public int writeBytes(InputStream in, int length) throws IOException { + int writtenBytes = setBytes(writerIndex, in, length); + if (writtenBytes > 0) { + writerIndex += writtenBytes; + } + return writtenBytes; + } + + public ChannelBuffer copy() { + return copy(readerIndex, readableBytes()); + } + + public ByteBuffer toByteBuffer() { + return toByteBuffer(readerIndex, readableBytes()); + } + + @Override + public boolean equals(Object o) { + return o instanceof ChannelBuffer + && ChannelBuffers.equals(this, (ChannelBuffer) o); + } + + public int compareTo(ChannelBuffer that) { + return ChannelBuffers.compare(this, that); + } + + @Override + public String toString() { + return getClass().getSimpleName() + '(' + + "ridx=" + readerIndex + ", " + + "widx=" + writerIndex + ", " + + "cap=" + capacity() + + ')'; + } + + protected void checkReadableBytes(int minimumReadableBytes) { + if (readableBytes() < minimumReadableBytes) { + throw new IndexOutOfBoundsException(); + } + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ByteBufferBackedChannelBuffer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ByteBufferBackedChannelBuffer.java new file mode 100644 index 000000000000..f571606cbfe6 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ByteBufferBackedChannelBuffer.java @@ -0,0 +1,244 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** + * @author kimi + */ +public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { + + private final ByteBuffer buffer; + + private final int capacity; + + public ByteBufferBackedChannelBuffer(ByteBuffer buffer) { + if (buffer == null) { + throw new NullPointerException("buffer"); + } + + this.buffer = buffer.slice(); + capacity = buffer.remaining(); + writerIndex(capacity); + } + + private ByteBufferBackedChannelBuffer(ByteBufferBackedChannelBuffer buffer) { + this.buffer = buffer.buffer; + capacity = buffer.capacity; + setIndex(buffer.readerIndex(), buffer.writerIndex()); + } + + public ChannelBufferFactory factory() { + if (buffer.isDirect()) { + return DirectChannelBufferFactory.getInstance(); + } else { + return HeapChannelBufferFactory.getInstance(); + } + } + + @Override + public int capacity() { + return capacity; + } + + @Override + public ChannelBuffer copy(int index, int length) { + ByteBuffer src; + try { + src = (ByteBuffer) buffer.duplicate().position(index).limit(index + length); + } catch (IllegalArgumentException e) { + throw new IndexOutOfBoundsException(); + } + + ByteBuffer dst = buffer.isDirect() + ? ByteBuffer.allocateDirect(length) + : ByteBuffer.allocate(length); + dst.put(src); + dst.clear(); + return new ByteBufferBackedChannelBuffer(dst); + } + + @Override + public byte getByte(int index) { + return buffer.get(index); + } + + @Override + public void getBytes(int index, byte[] dst, int dstIndex, int length) { + ByteBuffer data = buffer.duplicate(); + try { + data.limit(index + length).position(index); + } catch (IllegalArgumentException e) { + throw new IndexOutOfBoundsException(); + } + data.get(dst, dstIndex, length); + } + + @Override + public void getBytes(int index, ByteBuffer dst) { + ByteBuffer data = buffer.duplicate(); + int bytesToCopy = Math.min(capacity() - index, dst.remaining()); + try { + data.limit(index + bytesToCopy).position(index); + } catch (IllegalArgumentException e) { + throw new IndexOutOfBoundsException(); + } + dst.put(data); + } + + @Override + public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { + if (dst instanceof ByteBufferBackedChannelBuffer) { + ByteBufferBackedChannelBuffer bbdst = (ByteBufferBackedChannelBuffer) dst; + ByteBuffer data = bbdst.buffer.duplicate(); + + data.limit(dstIndex + length).position(dstIndex); + getBytes(index, data); + } else if (buffer.hasArray()) { + dst.setBytes(dstIndex, buffer.array(), index + buffer.arrayOffset(), length); + } else { + dst.setBytes(dstIndex, this, index, length); + } + } + + @Override + public void getBytes(int index, OutputStream out, int length) throws IOException { + if (length == 0) { + return; + } + + if (buffer.hasArray()) { + out.write( + buffer.array(), + index + buffer.arrayOffset(), + length); + } else { + byte[] tmp = new byte[length]; + ((ByteBuffer) buffer.duplicate().position(index)).get(tmp); + out.write(tmp); + } + } + + @Override + public boolean isDirect() { + return buffer.isDirect(); + } + + @Override + public void setByte(int index, int value) { + buffer.put(index, (byte) value); + } + + @Override + public void setBytes(int index, byte[] src, int srcIndex, int length) { + ByteBuffer data = buffer.duplicate(); + data.limit(index + length).position(index); + data.put(src, srcIndex, length); + } + + @Override + public void setBytes(int index, ByteBuffer src) { + ByteBuffer data = buffer.duplicate(); + data.limit(index + src.remaining()).position(index); + data.put(src); + } + + @Override + public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { + if (src instanceof ByteBufferBackedChannelBuffer) { + ByteBufferBackedChannelBuffer bbsrc = (ByteBufferBackedChannelBuffer) src; + ByteBuffer data = bbsrc.buffer.duplicate(); + + data.limit(srcIndex + length).position(srcIndex); + setBytes(index, data); + } else if (buffer.hasArray()) { + src.getBytes(srcIndex, buffer.array(), index + buffer.arrayOffset(), length); + } else { + src.getBytes(srcIndex, this, index, length); + } + } + + @Override + public ByteBuffer toByteBuffer(int index, int length) { + if (index == 0 && length == capacity()) { + return buffer.duplicate(); + } else { + return ((ByteBuffer) buffer.duplicate().position( + index).limit(index + length)).slice(); + } + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + int readBytes = 0; + + if (buffer.hasArray()) { + index += buffer.arrayOffset(); + do { + int localReadBytes = in.read(buffer.array(), index, length); + if (localReadBytes < 0) { + if (readBytes == 0) { + return -1; + } else { + break; + } + } + readBytes += localReadBytes; + index += localReadBytes; + length -= localReadBytes; + } while (length > 0); + } else { + byte[] tmp = new byte[length]; + int i = 0; + do { + int localReadBytes = in.read(tmp, i, tmp.length - i); + if (localReadBytes < 0) { + if (readBytes == 0) { + return -1; + } else { + break; + } + } + readBytes += localReadBytes; + i += readBytes; + } while (i < tmp.length); + ((ByteBuffer) buffer.duplicate().position(index)).put(tmp); + } + + return readBytes; + } + + @Override + public byte[] array() { + return buffer.array(); + } + + @Override + public boolean hasArray() { + return buffer.hasArray(); + } + + @Override + public int arrayOffset() { + return buffer.arrayOffset(); + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffer.java new file mode 100644 index 000000000000..c64c1d4bfd9e --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffer.java @@ -0,0 +1,968 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; + +/** + * A random and sequential accessible sequence of zero or more bytes (octets). + * This interface provides an abstract view for one or more primitive byte + * arrays ({@code byte[]}) and {@linkplain ByteBuffer NIO buffers}. + *

+ *

Creation of a buffer

+ *

+ * It is recommended to create a new buffer using the helper methods in {@link + * ChannelBuffers} rather than calling an individual implementation's + * constructor. + *

+ *

Random Access Indexing

+ *

+ * Just like an ordinary primitive byte array, {@link ChannelBuffer} uses zero-based + * indexing. It means the index of the first byte is always {@code 0} and + * the index of the last byte is always {@link #capacity() capacity - 1}. For + * example, to iterate all bytes of a buffer, you can do the following, + * regardless of its internal implementation: + *

+ *

+ * {@link ChannelBuffer} buffer = ...;
+ * for (int i = 0; i < buffer.capacity(); i ++) {
+ *     byte b = buffer.getByte(i);
+ *     System.out.println((char) b);
+ * }
+ * 
+ *

+ *

Sequential Access Indexing

+ *

+ * {@link ChannelBuffer} provides two pointer variables to support sequential + * read and write operations - {@link #readerIndex() readerIndex} for a read + * operation and {@link #writerIndex() writerIndex} for a write operation + * respectively. The following diagram shows how a buffer is segmented into + * three areas by the two pointers: + *

+ *

+ *      +-------------------+------------------+------------------+
+ *      | discardable bytes |  readable bytes  |  writable bytes  |
+ *      |                   |     (CONTENT)    |                  |
+ *      +-------------------+------------------+------------------+
+ *      |                   |                  |                  |
+ *      0      <=      readerIndex   <=   writerIndex    <=    capacity
+ * 
+ *

+ *

Readable bytes (the actual content)

+ *

+ * This segment is where the actual data is stored. Any operation whose name + * starts with {@code read} or {@code skip} will get or skip the data at the + * current {@link #readerIndex() readerIndex} and increase it by the number of + * read bytes. If the argument of the read operation is also a {@link + * ChannelBuffer} and no destination index is specified, the specified buffer's + * {@link #readerIndex() readerIndex} is increased together. + *

+ * If there's not enough content left, {@link IndexOutOfBoundsException} is + * raised. The default value of newly allocated, wrapped or copied buffer's + * {@link #readerIndex() readerIndex} is {@code 0}. + *

+ *

+ * // Iterates the readable bytes of a buffer.
+ * {@link ChannelBuffer} buffer = ...;
+ * while (buffer.readable()) {
+ *     System.out.println(buffer.readByte());
+ * }
+ * 
+ *

+ *

Writable bytes

+ *

+ * This segment is a undefined space which needs to be filled. Any operation + * whose name ends with {@code write} will write the data at the current {@link + * #writerIndex() writerIndex} and increase it by the number of written bytes. + * If the argument of the write operation is also a {@link ChannelBuffer}, and + * no source index is specified, the specified buffer's {@link #readerIndex() + * readerIndex} is increased together. + *

+ * If there's not enough writable bytes left, {@link IndexOutOfBoundsException} + * is raised. The default value of newly allocated buffer's {@link + * #writerIndex() writerIndex} is {@code 0}. The default value of wrapped or + * copied buffer's {@link #writerIndex() writerIndex} is the {@link #capacity() + * capacity} of the buffer. + *

+ *

+ * // Fills the writable bytes of a buffer with random integers.
+ * {@link ChannelBuffer} buffer = ...;
+ * while (buffer.writableBytes() >= 4) {
+ *     buffer.writeInt(random.nextInt());
+ * }
+ * 
+ *

+ *

Discardable bytes

+ *

+ * This segment contains the bytes which were read already by a read operation. + * Initially, the size of this segment is {@code 0}, but its size increases up + * to the {@link #writerIndex() writerIndex} as read operations are executed. + * The read bytes can be discarded by calling {@link #discardReadBytes()} to + * reclaim unused area as depicted by the following diagram: + *

+ *

+ *  BEFORE discardReadBytes()
+ *
+ *      +-------------------+------------------+------------------+
+ *      | discardable bytes |  readable bytes  |  writable bytes  |
+ *      +-------------------+------------------+------------------+
+ *      |                   |                  |                  |
+ *      0      <=      readerIndex   <=   writerIndex    <=    capacity
+ *
+ *
+ *  AFTER discardReadBytes()
+ *
+ *      +------------------+--------------------------------------+
+ *      |  readable bytes  |    writable bytes (got more space)   |
+ *      +------------------+--------------------------------------+
+ *      |                  |                                      |
+ * readerIndex (0) <= writerIndex (decreased)        <=        capacity
+ * 
+ *

+ * Please note that there is no guarantee about the content of writable bytes + * after calling {@link #discardReadBytes()}. The writable bytes will not be + * moved in most cases and could even be filled with completely different data + * depending on the underlying buffer implementation. + *

+ *

Clearing the buffer indexes

+ *

+ * You can set both {@link #readerIndex() readerIndex} and {@link #writerIndex() + * writerIndex} to {@code 0} by calling {@link #clear()}. It does not clear the + * buffer content (e.g. filling with {@code 0}) but just clears the two + * pointers. Please also note that the semantic of this operation is different + * from {@link ByteBuffer#clear()}. + *

+ *

+ *  BEFORE clear()
+ *
+ *      +-------------------+------------------+------------------+
+ *      | discardable bytes |  readable bytes  |  writable bytes  |
+ *      +-------------------+------------------+------------------+
+ *      |                   |                  |                  |
+ *      0      <=      readerIndex   <=   writerIndex    <=    capacity
+ *
+ *
+ *  AFTER clear()
+ *
+ *      +---------------------------------------------------------+
+ *      |             writable bytes (got more space)             |
+ *      +---------------------------------------------------------+
+ *      |                                                         |
+ *      0 = readerIndex = writerIndex            <=            capacity
+ * 
+ *

+ *

Mark and reset

+ *

+ * There are two marker indexes in every buffer. One is for storing {@link + * #readerIndex() readerIndex} and the other is for storing {@link + * #writerIndex() writerIndex}. You can always reposition one of the two + * indexes by calling a reset method. It works in a similar fashion to the mark + * and reset methods in {@link InputStream} except that there's no {@code + * readlimit}. + *

+ *

Conversion to existing JDK types

+ *

+ *

Byte array

+ *

+ * If a {@link ChannelBuffer} is backed by a byte array (i.e. {@code byte[]}), + * you can access it directly via the {@link #array()} method. To determine if + * a buffer is backed by a byte array, {@link #hasArray()} should be used. + *

+ *

NIO Buffers

+ *

+ * Various {@link #toByteBuffer()} methods convert a {@link ChannelBuffer} into + * one or more NIO buffers. These methods avoid buffer allocation and memory + * copy whenever possible, but there's no guarantee that memory copy will not be + * involved. + *

+ *

I/O Streams

+ *

+ * Please refer to {@link ChannelBufferInputStream} and {@link + * ChannelBufferOutputStream}. + * + * @author kimi + */ +public interface ChannelBuffer extends Comparable { + + /** + * Returns the number of bytes (octets) this buffer can contain. + */ + int capacity(); + + /** + * Sets the {@code readerIndex} and {@code writerIndex} of this buffer to + * {@code 0}. This method is identical to {@link #setIndex(int, int) + * setIndex(0, 0)}. + *

+ * Please note that the behavior of this method is different from that of + * NIO buffer, which sets the {@code limit} to the {@code capacity} of the + * buffer. + */ + void clear(); + + /** + * Returns a copy of this buffer's readable bytes. Modifying the content of + * the returned buffer or this buffer does not affect each other at all. + * This method is identical to {@code buf.copy(buf.readerIndex(), + * buf.readableBytes())}. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + */ + ChannelBuffer copy(); + + /** + * Returns a copy of this buffer's sub-region. Modifying the content of the + * returned buffer or this buffer does not affect each other at all. This + * method does not modify {@code readerIndex} or {@code writerIndex} of this + * buffer. + */ + ChannelBuffer copy(int index, int length); + + /** + * Discards the bytes between the 0th index and {@code readerIndex}. It + * moves the bytes between {@code readerIndex} and {@code writerIndex} to + * the 0th index, and sets {@code readerIndex} and {@code writerIndex} to + * {@code 0} and {@code oldWriterIndex - oldReaderIndex} respectively. + *

+ * Please refer to the class documentation for more detailed explanation. + */ + void discardReadBytes(); + + /** + * Makes sure the number of {@linkplain #writableBytes() the writable bytes} + * is equal to or greater than the specified value. If there is enough + * writable bytes in this buffer, this method returns with no side effect. + * Otherwise:

  • a non-dynamic buffer will throw an {@link + * IndexOutOfBoundsException}.
  • a dynamic buffer will expand its + * capacity so that the number of the {@link #writableBytes() writable + * bytes} becomes equal to or greater than the specified value. The + * expansion involves the reallocation of the internal buffer and + * consequently memory copy.
+ * + * @param writableBytes the expected minimum number of writable bytes + * + * @throws IndexOutOfBoundsException if {@linkplain #writableBytes() the + * writable bytes} of this buffer is less + * than the specified value and if this + * buffer is not a dynamic buffer + */ + void ensureWritableBytes(int writableBytes); + + /** + * Determines if the content of the specified buffer is identical to the + * content of this array. 'Identical' here means:
  • the size of the + * contents of the two buffers are same and
  • every single byte of + * the content of the two buffers are same.
Please note that it + * does not compare {@link #readerIndex()} nor {@link #writerIndex()}. This + * method also returns {@code false} for {@code null} and an object which is + * not an instance of {@link ChannelBuffer} type. + */ + public boolean equals(Object o); + + /** + * Returns the factory which creates a {@link ChannelBuffer} whose type and + * default {@link java.nio.ByteOrder} are same with this buffer. + */ + ChannelBufferFactory factory(); + + /** + * Gets a byte at the specified absolute {@code index} in this buffer. This + * method does not modify {@code readerIndex} or {@code writerIndex} of this + * buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0} or {@code index + 1} is + * greater than {@code this.capacity} + */ + byte getByte(int index); + + /** + * Transfers this buffer's data to the specified destination starting at the + * specified absolute {@code index}. This method does not modify {@code + * readerIndex} or {@code writerIndex} of this buffer + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0} or if {@code index + + * dst.length} is greater than {@code + * this.capacity} + */ + void getBytes(int index, byte[] dst); + + /** + * Transfers this buffer's data to the specified destination starting at the + * specified absolute {@code index}. This method does not modify {@code + * readerIndex} or {@code writerIndex} of this buffer. + * + * @param dstIndex the first index of the destination + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0}, if the specified {@code + * dstIndex} is less than {@code 0}, if + * {@code index + length} is greater than + * {@code this.capacity}, or if {@code + * dstIndex + length} is greater than + * {@code dst.length} + */ + void getBytes(int index, byte[] dst, int dstIndex, int length); + + /** + * Transfers this buffer's data to the specified destination starting at the + * specified absolute {@code index} until the destination's position reaches + * its limit. This method does not modify {@code readerIndex} or {@code + * writerIndex} of this buffer while the destination's {@code position} will + * be increased. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0} or if {@code index + + * dst.remaining()} is greater than {@code + * this.capacity} + */ + void getBytes(int index, ByteBuffer dst); + + /** + * Transfers this buffer's data to the specified destination starting at the + * specified absolute {@code index} until the destination becomes + * non-writable. This method is basically same with {@link #getBytes(int, + * ChannelBuffer, int, int)}, except that this method increases the {@code + * writerIndex} of the destination by the number of the transferred bytes + * while {@link #getBytes(int, ChannelBuffer, int, int)} does not. This + * method does not modify {@code readerIndex} or {@code writerIndex} of the + * source buffer (i.e. {@code this}). + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0} or if {@code index + + * dst.writableBytes} is greater than + * {@code this.capacity} + */ + void getBytes(int index, ChannelBuffer dst); + + /** + * Transfers this buffer's data to the specified destination starting at the + * specified absolute {@code index}. This method is basically same with + * {@link #getBytes(int, ChannelBuffer, int, int)}, except that this method + * increases the {@code writerIndex} of the destination by the number of the + * transferred bytes while {@link #getBytes(int, ChannelBuffer, int, int)} + * does not. This method does not modify {@code readerIndex} or {@code + * writerIndex} of the source buffer (i.e. {@code this}). + * + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0}, if {@code index + + * length} is greater than {@code + * this.capacity}, or if {@code length} is + * greater than {@code dst.writableBytes} + */ + void getBytes(int index, ChannelBuffer dst, int length); + + /** + * Transfers this buffer's data to the specified destination starting at the + * specified absolute {@code index}. This method does not modify {@code + * readerIndex} or {@code writerIndex} of both the source (i.e. {@code + * this}) and the destination. + * + * @param dstIndex the first index of the destination + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0}, if the specified {@code + * dstIndex} is less than {@code 0}, if + * {@code index + length} is greater than + * {@code this.capacity}, or if {@code + * dstIndex + length} is greater than + * {@code dst.capacity} + */ + void getBytes(int index, ChannelBuffer dst, int dstIndex, int length); + + /** + * Transfers this buffer's data to the specified stream starting at the + * specified absolute {@code index}. This method does not modify {@code + * readerIndex} or {@code writerIndex} of this buffer. + * + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0} or if {@code index + + * length} is greater than {@code + * this.capacity} + * @throws IOException if the specified stream threw an + * exception during I/O + */ + void getBytes(int index, OutputStream dst, int length) throws IOException; + + /** + * Returns {@code true} if and only if this buffer is backed by an NIO + * direct buffer. + */ + boolean isDirect(); + + /** + * Marks the current {@code readerIndex} in this buffer. You can reposition + * the current {@code readerIndex} to the marked {@code readerIndex} by + * calling {@link #resetReaderIndex()}. The initial value of the marked + * {@code readerIndex} is {@code 0}. + */ + void markReaderIndex(); + + /** + * Marks the current {@code writerIndex} in this buffer. You can reposition + * the current {@code writerIndex} to the marked {@code writerIndex} by + * calling {@link #resetWriterIndex()}. The initial value of the marked + * {@code writerIndex} is {@code 0}. + */ + void markWriterIndex(); + + /** + * Returns {@code true} if and only if {@code (this.writerIndex - + * this.readerIndex)} is greater than {@code 0}. + */ + boolean readable(); + + /** + * Returns the number of readable bytes which is equal to {@code + * (this.writerIndex - this.readerIndex)}. + */ + int readableBytes(); + + /** + * Gets a byte at the current {@code readerIndex} and increases the {@code + * readerIndex} by {@code 1} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less + * than {@code 1} + */ + byte readByte(); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} and increases the {@code readerIndex} by the + * number of the transferred bytes (= {@code dst.length}). + * + * @throws IndexOutOfBoundsException if {@code dst.length} is greater than + * {@code this.readableBytes} + */ + void readBytes(byte[] dst); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} and increases the {@code readerIndex} by the + * number of the transferred bytes (= {@code length}). + * + * @param dstIndex the first index of the destination + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code dstIndex} is + * less than {@code 0}, if {@code length} + * is greater than {@code this.readableBytes}, + * or if {@code dstIndex + length} is + * greater than {@code dst.length} + */ + void readBytes(byte[] dst, int dstIndex, int length); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} until the destination's position reaches its + * limit, and increases the {@code readerIndex} by the number of the + * transferred bytes. + * + * @throws IndexOutOfBoundsException if {@code dst.remaining()} is greater + * than {@code this.readableBytes} + */ + void readBytes(ByteBuffer dst); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} until the destination becomes non-writable, + * and increases the {@code readerIndex} by the number of the transferred + * bytes. This method is basically same with {@link + * #readBytes(ChannelBuffer, int, int)}, except that this method increases + * the {@code writerIndex} of the destination by the number of the + * transferred bytes while {@link #readBytes(ChannelBuffer, int, int)} does + * not. + * + * @throws IndexOutOfBoundsException if {@code dst.writableBytes} is greater + * than {@code this.readableBytes} + */ + void readBytes(ChannelBuffer dst); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} and increases the {@code readerIndex} by the + * number of the transferred bytes (= {@code length}). This method is + * basically same with {@link #readBytes(ChannelBuffer, int, int)}, except + * that this method increases the {@code writerIndex} of the destination by + * the number of the transferred bytes (= {@code length}) while {@link + * #readBytes(ChannelBuffer, int, int)} does not. + * + * @throws IndexOutOfBoundsException if {@code length} is greater than + * {@code this.readableBytes} or if {@code + * length} is greater than {@code + * dst.writableBytes} + */ + void readBytes(ChannelBuffer dst, int length); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} and increases the {@code readerIndex} by the + * number of the transferred bytes (= {@code length}). + * + * @param dstIndex the first index of the destination + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code dstIndex} is + * less than {@code 0}, if {@code length} + * is greater than {@code this.readableBytes}, + * or if {@code dstIndex + length} is + * greater than {@code dst.capacity} + */ + void readBytes(ChannelBuffer dst, int dstIndex, int length); + + /** + * Transfers this buffer's data to a newly created buffer starting at the + * current {@code readerIndex} and increases the {@code readerIndex} by the + * number of the transferred bytes (= {@code length}). The returned buffer's + * {@code readerIndex} and {@code writerIndex} are {@code 0} and {@code + * length} respectively. + * + * @param length the number of bytes to transfer + * + * @return the newly created buffer which contains the transferred bytes + * + * @throws IndexOutOfBoundsException if {@code length} is greater than + * {@code this.readableBytes} + */ + ChannelBuffer readBytes(int length); + + /** + * Repositions the current {@code readerIndex} to the marked {@code + * readerIndex} in this buffer. + * + * @throws IndexOutOfBoundsException if the current {@code writerIndex} is + * less than the marked {@code + * readerIndex} + */ + void resetReaderIndex(); + + /** + * Marks the current {@code writerIndex} in this buffer. You can reposition + * the current {@code writerIndex} to the marked {@code writerIndex} by + * calling {@link #resetWriterIndex()}. The initial value of the marked + * {@code writerIndex} is {@code 0}. + */ + void resetWriterIndex(); + + /** + * Returns the {@code readerIndex} of this buffer. + */ + int readerIndex(); + + /** + * Sets the {@code readerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code readerIndex} is + * less than {@code 0} or greater than + * {@code this.writerIndex} + */ + void readerIndex(int readerIndex); + + /** + * Transfers this buffer's data to the specified stream starting at the + * current {@code readerIndex}. + * + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if {@code length} is greater than + * {@code this.readableBytes} + * @throws IOException if the specified stream threw an + * exception during I/O + */ + void readBytes(OutputStream dst, int length) throws IOException; + + /** + * Sets the specified byte at the specified absolute {@code index} in this + * buffer. The 24 high-order bits of the specified value are ignored. This + * method does not modify {@code readerIndex} or {@code writerIndex} of this + * buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0} or {@code index + 1} is + * greater than {@code this.capacity} + */ + void setByte(int index, int value); + + /** + * Transfers the specified source array's data to this buffer starting at + * the specified absolute {@code index}. This method does not modify {@code + * readerIndex} or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0} or if {@code index + + * src.length} is greater than {@code + * this.capacity} + */ + void setBytes(int index, byte[] src); + + /** + * Transfers the specified source array's data to this buffer starting at + * the specified absolute {@code index}. This method does not modify {@code + * readerIndex} or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0}, if the specified {@code + * srcIndex} is less than {@code 0}, if + * {@code index + length} is greater than + * {@code this.capacity}, or if {@code + * srcIndex + length} is greater than + * {@code src.length} + */ + void setBytes(int index, byte[] src, int srcIndex, int length); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the specified absolute {@code index} until the source buffer's position + * reaches its limit. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0} or if {@code index + + * src.remaining()} is greater than {@code + * this.capacity} + */ + void setBytes(int index, ByteBuffer src); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the specified absolute {@code index} until the source buffer becomes + * unreadable. This method is basically same with {@link #setBytes(int, + * ChannelBuffer, int, int)}, except that this method increases the {@code + * readerIndex} of the source buffer by the number of the transferred bytes + * while {@link #setBytes(int, ChannelBuffer, int, int)} does not. This + * method does not modify {@code readerIndex} or {@code writerIndex} of the + * source buffer (i.e. {@code this}). + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0} or if {@code index + + * src.readableBytes} is greater than + * {@code this.capacity} + */ + void setBytes(int index, ChannelBuffer src); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the specified absolute {@code index}. This method is basically same with + * {@link #setBytes(int, ChannelBuffer, int, int)}, except that this method + * increases the {@code readerIndex} of the source buffer by the number of + * the transferred bytes while {@link #setBytes(int, ChannelBuffer, int, + * int)} does not. This method does not modify {@code readerIndex} or {@code + * writerIndex} of the source buffer (i.e. {@code this}). + * + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0}, if {@code index + + * length} is greater than {@code + * this.capacity}, or if {@code length} is + * greater than {@code src.readableBytes} + */ + void setBytes(int index, ChannelBuffer src, int length); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the specified absolute {@code index}. This method does not modify {@code + * readerIndex} or {@code writerIndex} of both the source (i.e. {@code + * this}) and the destination. + * + * @param srcIndex the first index of the source + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0}, if the specified {@code + * srcIndex} is less than {@code 0}, if + * {@code index + length} is greater than + * {@code this.capacity}, or if {@code + * srcIndex + length} is greater than + * {@code src.capacity} + */ + void setBytes(int index, ChannelBuffer src, int srcIndex, int length); + + /** + * Transfers the content of the specified source stream to this buffer + * starting at the specified absolute {@code index}. This method does not + * modify {@code readerIndex} or {@code writerIndex} of this buffer. + * + * @param length the number of bytes to transfer + * + * @return the actual number of bytes read in from the specified channel. + * {@code -1} if the specified channel is closed. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less + * than {@code 0} or if {@code index + + * length} is greater than {@code + * this.capacity} + * @throws IOException if the specified stream threw an + * exception during I/O + */ + int setBytes(int index, InputStream src, int length) throws IOException; + + /** + * Sets the {@code readerIndex} and {@code writerIndex} of this buffer in + * one shot. This method is useful when you have to worry about the + * invocation order of {@link #readerIndex(int)} and {@link + * #writerIndex(int)} methods. For example, the following code will fail: + *

+ *

+     * // Create a buffer whose readerIndex, writerIndex and capacity are
+     * // 0, 0 and 8 respectively.
+     * {@link ChannelBuffer} buf = {@link ChannelBuffers}.buffer(8);
+     *
+     * // IndexOutOfBoundsException is thrown because the specified
+     * // readerIndex (2) cannot be greater than the current writerIndex (0).
+     * buf.readerIndex(2);
+     * buf.writerIndex(4);
+     * 
+ *

+ * The following code will also fail: + *

+ *

+     * // Create a buffer whose readerIndex, writerIndex and capacity are
+     * // 0, 8 and 8 respectively.
+     * {@link ChannelBuffer} buf = {@link ChannelBuffers}.wrappedBuffer(new
+     * byte[8]);
+     *
+     * // readerIndex becomes 8.
+     * buf.readLong();
+     *
+     * // IndexOutOfBoundsException is thrown because the specified
+     * // writerIndex (4) cannot be less than the current readerIndex (8).
+     * buf.writerIndex(4);
+     * buf.readerIndex(2);
+     * 
+ *

+ * By contrast, {@link #setIndex(int, int)} guarantees that it never throws + * an {@link IndexOutOfBoundsException} as long as the specified indexes + * meet basic constraints, regardless what the current index values of the + * buffer are: + *

+ *

+     * // No matter what the current state of the buffer is, the following
+     * // call always succeeds as long as the capacity of the buffer is not
+     * // less than 4.
+     * buf.setIndex(2, 4);
+     * 
+ * + * @throws IndexOutOfBoundsException if the specified {@code readerIndex} is + * less than 0, if the specified {@code + * writerIndex} is less than the specified + * {@code readerIndex} or if the specified + * {@code writerIndex} is greater than + * {@code this.capacity} + */ + void setIndex(int readerIndex, int writerIndex); + + /** + * Increases the current {@code readerIndex} by the specified {@code length} + * in this buffer. + * + * @throws IndexOutOfBoundsException if {@code length} is greater than + * {@code this.readableBytes} + */ + void skipBytes(int length); + + /** + * Converts this buffer's readable bytes into a NIO buffer. The returned + * buffer might or might not share the content with this buffer, while they + * have separate indexes and marks. This method is identical to {@code + * buf.toByteBuffer(buf.readerIndex(), buf.readableBytes())}. This method + * does not modify {@code readerIndex} or {@code writerIndex} of this + * buffer. + */ + ByteBuffer toByteBuffer(); + + /** + * Converts this buffer's sub-region into a NIO buffer. The returned buffer + * might or might not share the content with this buffer, while they have + * separate indexes and marks. This method does not modify {@code + * readerIndex} or {@code writerIndex} of this buffer. + */ + ByteBuffer toByteBuffer(int index, int length); + + /** + * Returns {@code true} if and only if {@code (this.capacity - + * this.writerIndex)} is greater than {@code 0}. + */ + boolean writable(); + + /** + * Returns the number of writable bytes which is equal to {@code + * (this.capacity - this.writerIndex)}. + */ + int writableBytes(); + + /** + * Sets the specified byte at the current {@code writerIndex} and increases + * the {@code writerIndex} by {@code 1} in this buffer. The 24 high-order + * bits of the specified value are ignored. + * + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less + * than {@code 1} + */ + void writeByte(int value); + + /** + * Transfers the specified source array's data to this buffer starting at + * the current {@code writerIndex} and increases the {@code writerIndex} by + * the number of the transferred bytes (= {@code src.length}). + * + * @throws IndexOutOfBoundsException if {@code src.length} is greater than + * {@code this.writableBytes} + */ + void writeBytes(byte[] src); + + /** + * Transfers the specified source array's data to this buffer starting at + * the current {@code writerIndex} and increases the {@code writerIndex} by + * the number of the transferred bytes (= {@code length}). + * + * @param index the first index of the source + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code srcIndex} is + * less than {@code 0}, if {@code srcIndex + * + length} is greater than {@code + * src.length}, or if {@code length} is + * greater than {@code this.writableBytes} + */ + void writeBytes(byte[] src, int index, int length); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the current {@code writerIndex} until the source buffer's position + * reaches its limit, and increases the {@code writerIndex} by the number of + * the transferred bytes. + * + * @throws IndexOutOfBoundsException if {@code src.remaining()} is greater + * than {@code this.writableBytes} + */ + void writeBytes(ByteBuffer src); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the current {@code writerIndex} until the source buffer becomes + * unreadable, and increases the {@code writerIndex} by the number of the + * transferred bytes. This method is basically same with {@link + * #writeBytes(ChannelBuffer, int, int)}, except that this method increases + * the {@code readerIndex} of the source buffer by the number of the + * transferred bytes while {@link #writeBytes(ChannelBuffer, int, int)} does + * not. + * + * @throws IndexOutOfBoundsException if {@code src.readableBytes} is greater + * than {@code this.writableBytes} + */ + void writeBytes(ChannelBuffer src); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the current {@code writerIndex} and increases the {@code writerIndex} by + * the number of the transferred bytes (= {@code length}). This method is + * basically same with {@link #writeBytes(ChannelBuffer, int, int)}, except + * that this method increases the {@code readerIndex} of the source buffer + * by the number of the transferred bytes (= {@code length}) while {@link + * #writeBytes(ChannelBuffer, int, int)} does not. + * + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if {@code length} is greater than + * {@code this.writableBytes} or if {@code + * length} is greater then {@code + * src.readableBytes} + */ + void writeBytes(ChannelBuffer src, int length); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the current {@code writerIndex} and increases the {@code writerIndex} by + * the number of the transferred bytes (= {@code length}). + * + * @param srcIndex the first index of the source + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code srcIndex} is + * less than {@code 0}, if {@code srcIndex + * + length} is greater than {@code + * src.capacity}, or if {@code length} is + * greater than {@code this.writableBytes} + */ + void writeBytes(ChannelBuffer src, int srcIndex, int length); + + /** + * Transfers the content of the specified stream to this buffer starting at + * the current {@code writerIndex} and increases the {@code writerIndex} by + * the number of the transferred bytes. + * + * @param length the number of bytes to transfer + * + * @return the actual number of bytes read in from the specified stream + * + * @throws IndexOutOfBoundsException if {@code length} is greater than + * {@code this.writableBytes} + * @throws IOException if the specified stream threw an + * exception during I/O + */ + int writeBytes(InputStream src, int length) throws IOException; + + /** + * Returns the {@code writerIndex} of this buffer. + */ + int writerIndex(); + + /** + * Sets the {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code writerIndex} is + * less than {@code this.readerIndex} or + * greater than {@code this.capacity} + */ + void writerIndex(int writerIndex); + + /** + * Returns the backing byte array of this buffer. + * + * @throws UnsupportedOperationException if there no accessible backing byte + * array + */ + byte[] array(); + + /** + * Returns {@code true} if and only if this buffer has a backing byte array. + * If this method returns true, you can safely call {@link #array()} and + * {@link #arrayOffset()}. + */ + boolean hasArray(); + + /** + * Returns the offset of the first byte within the backing byte array of + * this buffer. + * + * @throws UnsupportedOperationException if there no accessible backing byte + * array + */ + int arrayOffset(); +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferFactory.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferFactory.java new file mode 100644 index 000000000000..ec913605b75c --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferFactory.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.buffer; + +import java.nio.ByteBuffer; + +/** + * @author kimi + */ +public interface ChannelBufferFactory { + + ChannelBuffer getBuffer(int capacity); + + ChannelBuffer getBuffer(byte[] array, int offset, int length); + + ChannelBuffer getBuffer(ByteBuffer nioBuffer); + +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferInputStream.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferInputStream.java new file mode 100644 index 000000000000..3ca07b8454bf --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferInputStream.java @@ -0,0 +1,111 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.buffer; + +import java.io.IOException; +import java.io.InputStream; + +/** + * @author kimi + */ +public class ChannelBufferInputStream extends InputStream { + + private final ChannelBuffer buffer; + private final int startIndex; + private final int endIndex; + + public ChannelBufferInputStream(ChannelBuffer buffer) { + this(buffer, buffer.readableBytes()); + } + + public ChannelBufferInputStream(ChannelBuffer buffer, int length) { + if (buffer == null) { + throw new NullPointerException("buffer"); + } + if (length < 0) { + throw new IllegalArgumentException("length: " + length); + } + if (length > buffer.readableBytes()) { + throw new IndexOutOfBoundsException(); + } + + this.buffer = buffer; + startIndex = buffer.readerIndex(); + endIndex = startIndex + length; + buffer.markReaderIndex(); + } + + public int readBytes() { + return buffer.readerIndex() - startIndex; + } + + @Override + public int available() throws IOException { + return endIndex - buffer.readerIndex(); + } + + @Override + public void mark(int readlimit) { + buffer.markReaderIndex(); + } + + @Override + public boolean markSupported() { + return true; + } + + @Override + public int read() throws IOException { + if (!buffer.readable()) { + return -1; + } + return buffer.readByte() & 0xff; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + int available = available(); + if (available == 0) { + return -1; + } + + len = Math.min(available, len); + buffer.readBytes(b, off, len); + return len; + } + + @Override + public void reset() throws IOException { + buffer.resetReaderIndex(); + } + + @Override + public long skip(long n) throws IOException { + if (n > Integer.MAX_VALUE) { + return skipBytes(Integer.MAX_VALUE); + } else { + return skipBytes((int) n); + } + } + + private int skipBytes(int n) throws IOException { + int nBytes = Math.min(available(), n); + buffer.skipBytes(nBytes); + return nBytes; + } + +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferOutputStream.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferOutputStream.java new file mode 100644 index 000000000000..a620c439754f --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferOutputStream.java @@ -0,0 +1,64 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.buffer; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * @author kimi + */ +public class ChannelBufferOutputStream extends OutputStream { + + private final ChannelBuffer buffer; + private final int startIndex; + + public ChannelBufferOutputStream(ChannelBuffer buffer) { + if (buffer == null) { + throw new NullPointerException("buffer"); + } + this.buffer = buffer; + startIndex = buffer.writerIndex(); + } + + public int writtenBytes() { + return buffer.writerIndex() - startIndex; + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + if (len == 0) { + return; + } + + buffer.writeBytes(b, off, len); + } + + @Override + public void write(byte[] b) throws IOException { + buffer.writeBytes(b); + } + + @Override + public void write(int b) throws IOException { + buffer.writeByte((byte) b); + } + + public ChannelBuffer buffer() { + return buffer; + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffers.java new file mode 100644 index 000000000000..506b06f3e918 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffers.java @@ -0,0 +1,133 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.buffer; + +import java.nio.ByteBuffer; + +/** + * @author kimi + */ +public final class ChannelBuffers { + + public static final ChannelBuffer EMPTY_BUFFER = new HeapChannelBuffer(0); + + public static ChannelBuffer dynamicBuffer(int capacity) { + return new DynamicChannelBuffer(capacity); + } + + public static ChannelBuffer dynamicBuffer(int capacity, + ChannelBufferFactory factory) { + return new DynamicChannelBuffer(capacity, factory); + } + + public static ChannelBuffer buffer(int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException("capacity can not be negative"); + } + if (capacity == 0) { + return EMPTY_BUFFER; + } + return new HeapChannelBuffer(capacity); + } + + public static ChannelBuffer wrappedBuffer(byte[] array, int offset, int length) { + if (array == null) { + throw new NullPointerException("array == null"); + } + byte[] dest = new byte[length]; + System.arraycopy(array, offset, dest, 0, length); + return wrappedBuffer(dest); + } + + public static ChannelBuffer wrappedBuffer(byte[] array) { + if (array == null) { + throw new NullPointerException("array == null"); + } + if (array.length == 0) { + return EMPTY_BUFFER; + } + return new HeapChannelBuffer(array); + } + + public static ChannelBuffer wrappedBuffer(ByteBuffer buffer) { + if (!buffer.hasRemaining()) { + return EMPTY_BUFFER; + } + if (buffer.hasArray()) { + return wrappedBuffer(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); + } else { + return new ByteBufferBackedChannelBuffer(buffer); + } + } + + public static ChannelBuffer directBuffer(int capacity) { + if (capacity == 0) { + return EMPTY_BUFFER; + } + + ChannelBuffer buffer = new ByteBufferBackedChannelBuffer( + ByteBuffer.allocateDirect(capacity)); + buffer.clear(); + return buffer; + } + + public static boolean equals(ChannelBuffer bufferA, ChannelBuffer bufferB) { + final int aLen = bufferA.readableBytes(); + if (aLen != bufferB.readableBytes()) { + return false; + } + + final int byteCount = aLen & 7; + + int aIndex = bufferA.readerIndex(); + int bIndex = bufferB.readerIndex(); + + for (int i = byteCount; i > 0; i--) { + if (bufferA.getByte(aIndex) != bufferB.getByte(bIndex)) { + return false; + } + aIndex++; + bIndex++; + } + + return true; + } + + public static int compare(ChannelBuffer bufferA, ChannelBuffer bufferB) { + final int aLen = bufferA.readableBytes(); + final int bLen = bufferB.readableBytes(); + final int minLength = Math.min(aLen, bLen); + + int aIndex = bufferA.readerIndex(); + int bIndex = bufferB.readerIndex(); + + for (int i = minLength; i > 0; i--) { + byte va = bufferA.getByte(aIndex); + byte vb = bufferB.getByte(bIndex); + if (va > vb) { + return 1; + } else if (va < vb) { + return -1; + } + aIndex++; + bIndex++; + } + + return aLen - bLen; + } + +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/DirectChannelBufferFactory.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/DirectChannelBufferFactory.java new file mode 100644 index 000000000000..21d537caf5e8 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/DirectChannelBufferFactory.java @@ -0,0 +1,77 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.buffer; + +import java.nio.ByteBuffer; + +/** + * @author kimi + */ +public class DirectChannelBufferFactory implements ChannelBufferFactory { + + private static final DirectChannelBufferFactory INSTANCE = new DirectChannelBufferFactory(); + + public static ChannelBufferFactory getInstance() { + return INSTANCE; + } + + public DirectChannelBufferFactory() { + super(); + } + + public ChannelBuffer getBuffer(int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException("capacity: " + capacity); + } + if (capacity == 0) { + return ChannelBuffers.EMPTY_BUFFER; + } + return ChannelBuffers.directBuffer(capacity); + } + + public ChannelBuffer getBuffer(byte[] array, int offset, int length) { + if (array == null) { + throw new NullPointerException("array"); + } + if (offset < 0) { + throw new IndexOutOfBoundsException("offset: " + offset); + } + if (length == 0) { + return ChannelBuffers.EMPTY_BUFFER; + } + if (offset + length > array.length) { + throw new IndexOutOfBoundsException("length: " + length); + } + + ChannelBuffer buf = getBuffer(length); + buf.writeBytes(array, offset, length); + return buf; + } + + public ChannelBuffer getBuffer(ByteBuffer nioBuffer) { + if (!nioBuffer.isReadOnly() && nioBuffer.isDirect()) { + return ChannelBuffers.wrappedBuffer(nioBuffer); + } + + ChannelBuffer buf = getBuffer(nioBuffer.remaining()); + int pos = nioBuffer.position(); + buf.writeBytes(nioBuffer); + nioBuffer.position(pos); + return buf; + } + +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/DynamicChannelBuffer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/DynamicChannelBuffer.java new file mode 100644 index 000000000000..9c0220153f23 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/DynamicChannelBuffer.java @@ -0,0 +1,193 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** + * @author kimi + */ +public class DynamicChannelBuffer extends AbstractChannelBuffer { + + private final ChannelBufferFactory factory; + + private ChannelBuffer buffer; + + public DynamicChannelBuffer(int estimatedLength) { + this(estimatedLength, HeapChannelBufferFactory.getInstance()); + } + + public DynamicChannelBuffer(int estimatedLength, ChannelBufferFactory factory) { + if (estimatedLength < 0) { + throw new IllegalArgumentException("estimatedLength: " + estimatedLength); + } + if (factory == null) { + throw new NullPointerException("factory"); + } + this.factory = factory; + buffer = factory.getBuffer(estimatedLength); + } + + @Override + public void ensureWritableBytes(int minWritableBytes) { + if (minWritableBytes <= writableBytes()) { + return; + } + + int newCapacity; + if (capacity() == 0) { + newCapacity = 1; + } else { + newCapacity = capacity(); + } + int minNewCapacity = writerIndex() + minWritableBytes; + while (newCapacity < minNewCapacity) { + newCapacity <<= 1; + } + + ChannelBuffer newBuffer = factory().getBuffer(newCapacity); + newBuffer.writeBytes(buffer, 0, writerIndex()); + buffer = newBuffer; + } + + @Override + public int capacity() { + return buffer.capacity(); + } + + @Override + public ChannelBuffer copy(int index, int length) { + DynamicChannelBuffer copiedBuffer = new DynamicChannelBuffer(Math.max(length, 64), factory()); + copiedBuffer.buffer = buffer.copy(index, length); + copiedBuffer.setIndex(0, length); + return copiedBuffer; + } + + @Override + public ChannelBufferFactory factory() { + return factory; + } + + @Override + public byte getByte(int index) { + return buffer.getByte(index); + } + + @Override + public void getBytes(int index, byte[] dst, int dstIndex, int length) { + buffer.getBytes(index, dst, dstIndex, length); + } + + @Override + public void getBytes(int index, ByteBuffer dst) { + buffer.getBytes(index, dst); + } + + @Override + public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { + buffer.getBytes(index, dst, dstIndex, length); + } + + @Override + public void getBytes(int index, OutputStream dst, int length) throws IOException { + buffer.getBytes(index, dst, length); + } + + @Override + public boolean isDirect() { + return buffer.isDirect(); + } + + @Override + public void setByte(int index, int value) { + buffer.setByte(index, value); + } + + @Override + public void setBytes(int index, byte[] src, int srcIndex, int length) { + buffer.setBytes(index, src, srcIndex, length); + } + + @Override + public void setBytes(int index, ByteBuffer src) { + buffer.setBytes(index, src); + } + + @Override + public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { + buffer.setBytes(index, src, srcIndex, length); + } + + @Override + public int setBytes(int index, InputStream src, int length) throws IOException { + return buffer.setBytes(index, src, length); + } + + @Override + public ByteBuffer toByteBuffer(int index, int length) { + return buffer.toByteBuffer(index, length); + } + + @Override + public void writeByte(int value) { + ensureWritableBytes(1); + super.writeByte(value); + } + + @Override + public void writeBytes(byte[] src, int srcIndex, int length) { + ensureWritableBytes(length); + super.writeBytes(src, srcIndex, length); + } + + @Override + public void writeBytes(ChannelBuffer src, int srcIndex, int length) { + ensureWritableBytes(length); + super.writeBytes(src, srcIndex, length); + } + + @Override + public void writeBytes(ByteBuffer src) { + ensureWritableBytes(src.remaining()); + super.writeBytes(src); + } + + @Override + public int writeBytes(InputStream in, int length) throws IOException { + ensureWritableBytes(length); + return super.writeBytes(in, length); + } + + @Override + public byte[] array() { + return buffer.array(); + } + + @Override + public boolean hasArray() { + return buffer.hasArray(); + } + + @Override + public int arrayOffset() { + return buffer.arrayOffset(); + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBuffer.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBuffer.java new file mode 100644 index 000000000000..65b440d0a239 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBuffer.java @@ -0,0 +1,202 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; + +/** + * @author kimi + */ +public class HeapChannelBuffer extends AbstractChannelBuffer { + + /** + * The underlying heap byte array that this buffer is wrapping. + */ + protected final byte[] array; + + /** + * Creates a new heap buffer with a newly allocated byte array. + * + * @param length the length of the new byte array + */ + public HeapChannelBuffer(int length) { + this(new byte[length], 0, 0); + } + + /** + * Creates a new heap buffer with an existing byte array. + * + * @param array the byte array to wrap + */ + public HeapChannelBuffer(byte[] array) { + this(array, 0, array.length); + } + + /** + * Creates a new heap buffer with an existing byte array. + * + * @param array the byte array to wrap + * @param readerIndex the initial reader index of this buffer + * @param writerIndex the initial writer index of this buffer + */ + protected HeapChannelBuffer(byte[] array, int readerIndex, int writerIndex) { + if (array == null) { + throw new NullPointerException("array"); + } + this.array = array; + setIndex(readerIndex, writerIndex); + } + + public boolean isDirect() { + return false; + } + + public int capacity() { + return array.length; + } + + public boolean hasArray() { + return true; + } + + public byte[] array() { + return array; + } + + public int arrayOffset() { + return 0; + } + + public byte getByte(int index) { + return array[index]; + } + + public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { + if (dst instanceof HeapChannelBuffer) { + getBytes(index, ((HeapChannelBuffer) dst).array, dstIndex, length); + } else { + dst.setBytes(dstIndex, array, index, length); + } + } + + public void getBytes(int index, byte[] dst, int dstIndex, int length) { + System.arraycopy(array, index, dst, dstIndex, length); + } + + public void getBytes(int index, ByteBuffer dst) { + dst.put(array, index, Math.min(capacity() - index, dst.remaining())); + } + + public void getBytes(int index, OutputStream out, int length) + throws IOException { + out.write(array, index, length); + } + + public int getBytes(int index, GatheringByteChannel out, int length) + throws IOException { + return out.write(ByteBuffer.wrap(array, index, length)); + } + + public void setByte(int index, int value) { + array[index] = (byte) value; + } + + public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { + if (src instanceof HeapChannelBuffer) { + setBytes(index, ((HeapChannelBuffer) src).array, srcIndex, length); + } else { + src.getBytes(srcIndex, array, index, length); + } + } + + public void setBytes(int index, byte[] src, int srcIndex, int length) { + System.arraycopy(src, srcIndex, array, index, length); + } + + public void setBytes(int index, ByteBuffer src) { + src.get(array, index, src.remaining()); + } + + public int setBytes(int index, InputStream in, int length) throws IOException { + int readBytes = 0; + do { + int localReadBytes = in.read(array, index, length); + if (localReadBytes < 0) { + if (readBytes == 0) { + return -1; + } else { + break; + } + } + readBytes += localReadBytes; + index += localReadBytes; + length -= localReadBytes; + } while (length > 0); + + return readBytes; + } + + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + ByteBuffer buf = ByteBuffer.wrap(array, index, length); + int readBytes = 0; + + do { + int localReadBytes; + try { + localReadBytes = in.read(buf); + } catch (ClosedChannelException e) { + localReadBytes = -1; + } + if (localReadBytes < 0) { + if (readBytes == 0) { + return -1; + } else { + break; + } + } else if (localReadBytes == 0) { + break; + } + readBytes += localReadBytes; + } while (readBytes < length); + + return readBytes; + } + + public ChannelBuffer copy(int index, int length) { + if (index < 0 || length < 0 || index + length > array.length) { + throw new IndexOutOfBoundsException(); + } + + byte[] copiedArray = new byte[length]; + System.arraycopy(array, index, copiedArray, 0, length); + return new HeapChannelBuffer(copiedArray); + } + + public ChannelBufferFactory factory() { + return HeapChannelBufferFactory.getInstance(); + } + + public ByteBuffer toByteBuffer(int index, int length) { + return ByteBuffer.wrap(array, index, length); + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBufferFactory.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBufferFactory.java new file mode 100644 index 000000000000..3b3245afc447 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBufferFactory.java @@ -0,0 +1,56 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.buffer; + +import java.nio.ByteBuffer; + +/** + * @author kimi + */ +public class HeapChannelBufferFactory implements ChannelBufferFactory{ + + private static final HeapChannelBufferFactory INSTANCE = new HeapChannelBufferFactory(); + + public static ChannelBufferFactory getInstance() { + return INSTANCE; + } + + public HeapChannelBufferFactory() { + super(); + } + + public ChannelBuffer getBuffer(int capacity) { + return ChannelBuffers.buffer(capacity); + } + + public ChannelBuffer getBuffer(byte[] array, int offset, int length) { + return ChannelBuffers.wrappedBuffer(array, offset, length); + } + + public ChannelBuffer getBuffer(ByteBuffer nioBuffer) { + if (nioBuffer.hasArray()) { + return ChannelBuffers.wrappedBuffer(nioBuffer); + } + + ChannelBuffer buf = getBuffer(nioBuffer.remaining()); + int pos = nioBuffer.position(); + buf.writeBytes(nioBuffer); + nioBuffer.position(pos); + return buf; + } + +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java index 6d3a8e5fe76a..a0b8c82ddc25 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/codec/ExchangeCodec.java @@ -17,12 +17,9 @@ import java.io.IOException; import java.io.InputStream; -import java.io.OutputStream; import com.alibaba.dubbo.common.io.Bytes; import com.alibaba.dubbo.common.io.StreamUtils; -import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; -import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.common.serialize.ObjectInput; @@ -31,6 +28,9 @@ import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBufferInputStream; +import com.alibaba.dubbo.remoting.buffer.ChannelBufferOutputStream; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; @@ -70,45 +70,44 @@ public Short getMagicCode() { return MAGIC; } - public void encode(Channel channel, OutputStream os, Object msg) throws IOException { + public void encode(Channel channel, ChannelBuffer buffer, Object msg) throws IOException { if (msg instanceof Request) { - encodeRequest(channel, os, (Request) msg); + encodeRequest(channel, buffer, (Request) msg); } else if (msg instanceof Response) { - encodeResponse(channel, os, (Response) msg); + encodeResponse(channel, buffer, (Response) msg); } else { - super.encode(channel, os, msg); + super.encode(channel, buffer, msg); } } - public Object decode(Channel channel, InputStream is) throws IOException { - int readable = is.available(); + public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { + int readable = buffer.readableBytes(); byte[] header = new byte[Math.min(readable, HEADER_LENGTH)]; - is.read(header); - return decode(channel, is, readable, header); + buffer.readBytes(header); + return decode(channel, buffer, readable, header); } - protected Object decode(Channel channel, InputStream is, int readable, byte[] header) throws IOException { + protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byte[] header) throws IOException { // check magic number. if (readable > 0 && header[0] != MAGIC_HIGH || readable > 1 && header[1] != MAGIC_LOW) { int length = header.length; if (header.length < readable) { header = Bytes.copyOf(header, readable); - is.read(header, length, readable - length); + buffer.readBytes(header, length, readable - length); } for (int i = 1; i < header.length - 1; i ++) { if (header[i] == MAGIC_HIGH && header[i + 1] == MAGIC_LOW) { - UnsafeByteArrayInputStream bis = ((UnsafeByteArrayInputStream) is); - bis.position(bis.position() - header.length + i); + buffer.readerIndex(buffer.readerIndex() - header.length + i); header = Bytes.copyOf(header, i); break; } } - return super.decode(channel, is, readable, header); + return super.decode(channel, buffer, readable, header); } // check length. if (readable < HEADER_LENGTH) { - return NEED_MORE_INPUT; + return DecodeResult.NEED_MORE_INPUT; } // get data length. @@ -117,12 +116,11 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] he int tt = len + HEADER_LENGTH; if( readable < tt ) { - return NEED_MORE_INPUT; + return DecodeResult.NEED_MORE_INPUT; } // limit input stream. - if( readable != tt ) - is = StreamUtils.limitedInputStream(is, len); + ChannelBufferInputStream is = new ChannelBufferInputStream(buffer, len); try { return decodeBody(channel, is, header); @@ -211,7 +209,7 @@ protected Object getRequestData(long id) { return req.getData(); } - protected void encodeRequest(Channel channel, OutputStream os, Request req) throws IOException { + protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request req) throws IOException { Serialization serialization = getSerialization(channel); // header. byte[] header = new byte[HEADER_LENGTH]; @@ -228,7 +226,9 @@ protected void encodeRequest(Channel channel, OutputStream os, Request req) thro Bytes.long2bytes(req.getId(), header, 4); // encode request data. - UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); + int savedWriteIndex = buffer.writerIndex(); + buffer.writerIndex(savedWriteIndex + HEADER_LENGTH); + ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer); ObjectOutput out = serialization.serialize(channel.getUrl(), bos); if (req.isEvent()) { encodeEventData(channel, out, req.getData()); @@ -238,16 +238,17 @@ protected void encodeRequest(Channel channel, OutputStream os, Request req) thro out.flushBuffer(); bos.flush(); bos.close(); - byte[] data = bos.toByteArray(); - checkPayload(channel, data.length); - Bytes.int2bytes(data.length, header, 12); + int len = bos.writtenBytes(); + checkPayload(channel, len); + Bytes.int2bytes(len, header, 12); // write - os.write(header); // write header. - os.write(data); // write data. + buffer.writerIndex(savedWriteIndex); + buffer.writeBytes(header); // write header. + buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len); } - protected void encodeResponse(Channel channel, OutputStream os, Response res) throws IOException { + protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response res) throws IOException { try { Serialization serialization = getSerialization(channel); // header. @@ -262,8 +263,10 @@ protected void encodeResponse(Channel channel, OutputStream os, Response res) th header[3] = status; // set request id. Bytes.long2bytes(res.getId(), header, 4); - - UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); + + int savedWriteIndex = buffer.writerIndex(); + buffer.writerIndex(savedWriteIndex + HEADER_LENGTH); + ChannelBufferOutputStream bos = new ChannelBufferOutputStream(buffer); ObjectOutput out = serialization.serialize(channel.getUrl(), bos); // encode response data or error message. if (status == Response.OK) { @@ -277,13 +280,14 @@ protected void encodeResponse(Channel channel, OutputStream os, Response res) th out.flushBuffer(); bos.flush(); bos.close(); - - byte[] data = bos.toByteArray(); - checkPayload(channel, data.length); - Bytes.int2bytes(data.length, header, 12); + + int len = bos.writtenBytes(); + checkPayload(channel, len); + Bytes.int2bytes(len, header, 12); // write - os.write(header); // write header. - os.write(data); // write data. + buffer.writerIndex(savedWriteIndex); + buffer.writeBytes(header); // write header. + buffer.writerIndex(savedWriteIndex + HEADER_LENGTH + len); } catch (Throwable t) { // 鍙戦佸け璐ヤ俊鎭粰Consumer锛屽惁鍒機onsumer鍙兘绛夎秴鏃朵簡 if (! res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) { diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java index 11f855bc8ed7..3cb8ca064d3b 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/telnet/codec/TelnetCodec.java @@ -13,11 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.remoting.telnet.codec; - +package com.alibaba.dubbo.remoting.telnet.codec; + import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Arrays; @@ -31,59 +29,59 @@ import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.transport.codec.TransportCodec; - -/** - * TelnetCodec - * - * @author heyman + +/** + * TelnetCodec + * + * @author heyman * @author william.liangf - * @author chao.liuc - */ -public class TelnetCodec extends TransportCodec { - - private static final Logger logger = LoggerFactory.getLogger(TelnetCodec.class); - - private static final String HISTORY_LIST_KEY = "telnet.history.list"; - - private static final String HISTORY_INDEX_KEY = "telnet.history.index"; - - private static final byte[] UP = new byte[] {27, 91, 65}; - - private static final byte[] DOWN = new byte[] {27, 91, 66}; - - private static final List ENTER = Arrays.asList(new Object[] { new byte[] { '\r', '\n' } /* Windows Enter */, new byte[] { '\n' } /* Linux Enter */ }); - - private static final List EXIT = Arrays.asList(new Object[] { new byte[] { 3 } /* Windows Ctrl+C */, new byte[] { -1, -12, -1, -3, 6 } /* Linux Ctrl+C */, new byte[] { -1, -19, -1, -3, 6 } /* Linux Pause */ }); - - public void encode(Channel channel, OutputStream output, Object message) throws IOException { - if (message instanceof String) { - if (isClientSide(channel)) { - message = message + "\r\n"; - } - byte[] msgData = ((String) message).getBytes(getCharset(channel).name()); - output.write(msgData); - output.flush(); - } else { - super.encode(channel, output, message); - } - } - - public Object decode(Channel channel, InputStream is) throws IOException { - int readable = is.available(); - byte[] message = new byte[readable]; - is.read(message); - return decode(channel, is, readable, message); - } - + * @author chao.liuc + */ +public class TelnetCodec extends TransportCodec { + + private static final Logger logger = LoggerFactory.getLogger(TelnetCodec.class); + + private static final String HISTORY_LIST_KEY = "telnet.history.list"; + + private static final String HISTORY_INDEX_KEY = "telnet.history.index"; + + private static final byte[] UP = new byte[] {27, 91, 65}; + + private static final byte[] DOWN = new byte[] {27, 91, 66}; + + private static final List ENTER = Arrays.asList(new Object[] { new byte[] { '\r', '\n' } /* Windows Enter */, new byte[] { '\n' } /* Linux Enter */ }); + + private static final List EXIT = Arrays.asList(new Object[] { new byte[] { 3 } /* Windows Ctrl+C */, new byte[] { -1, -12, -1, -3, 6 } /* Linux Ctrl+C */, new byte[] { -1, -19, -1, -3, 6 } /* Linux Pause */ }); + + public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException { + if (message instanceof String) { + if (isClientSide(channel)) { + message = message + "\r\n"; + } + byte[] msgData = ((String) message).getBytes(getCharset(channel).name()); + buffer.writeBytes(msgData); + } else { + super.encode(channel, buffer, message); + } + } + + public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { + int readable = buffer.readableBytes(); + byte[] message = new byte[readable]; + buffer.readBytes(message); + return decode(channel, buffer, readable, message); + } + @SuppressWarnings("unchecked") - protected Object decode(Channel channel, InputStream is, int readable, byte[] message) throws IOException { + protected Object decode(Channel channel, ChannelBuffer buffer, int readable, byte[] message) throws IOException { if (isClientSide(channel)) { return toString(message, getCharset(channel)); } checkPayload(channel, readable); if (message == null || message.length == 0) { - return NEED_MORE_INPUT; + return DecodeResult.NEED_MORE_INPUT; } if (message[message.length - 1] == '\b') { // Windows backspace echo @@ -93,7 +91,7 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] me } catch (RemotingException e) { throw new IOException(StringUtils.toString(e)); } - return NEED_MORE_INPUT; + return DecodeResult.NEED_MORE_INPUT; } for (Object command : EXIT) { @@ -111,7 +109,7 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] me if (up || down) { LinkedList history = (LinkedList) channel.getAttribute(HISTORY_LIST_KEY); if (history == null || history.size() == 0) { - return NEED_MORE_INPUT; + return DecodeResult.NEED_MORE_INPUT; } Integer index = (Integer) channel.getAttribute(HISTORY_INDEX_KEY); Integer old = index; @@ -153,7 +151,7 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] me throw new IOException(StringUtils.toString(e)); } } - return NEED_MORE_INPUT; + return DecodeResult.NEED_MORE_INPUT; } for (Object command : EXIT) { if (isEquals(message, (byte[]) command)) { @@ -172,7 +170,7 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] me } } if (enter == null) { - return NEED_MORE_INPUT; + return DecodeResult.NEED_MORE_INPUT; } LinkedList history = (LinkedList) channel.getAttribute(HISTORY_LIST_KEY); Integer index = (Integer) channel.getAttribute(HISTORY_INDEX_KEY); @@ -209,89 +207,89 @@ protected Object decode(Channel channel, InputStream is, int readable, byte[] me } return result; } - - private static Charset getCharset(Channel channel) { - if (channel != null) { - Object attribute = channel.getAttribute(Constants.CHARSET_KEY); - if (attribute instanceof String) { - try { - return Charset.forName((String) attribute); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } else if (attribute instanceof Charset) { - return (Charset) attribute; - } - URL url = channel.getUrl(); - if (url != null) { - String parameter = url.getParameter(Constants.CHARSET_KEY); - if (parameter != null && parameter.length() > 0) { - try { - return Charset.forName(parameter); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } - } - } - try { - return Charset.forName("GBK"); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - return Charset.defaultCharset(); - } - - private static String toString(byte[] message, Charset charset) throws UnsupportedEncodingException { - byte[] copy = new byte[message.length]; - int index = 0; - for (int i = 0; i < message.length; i ++) { - byte b = message[i] ; - if (b == '\b') { // backspace - if (index > 0) { - index --; - } - if (i > 2 && message[i - 2] < 0) { // double byte char - if (index > 0) { - index --; - } - } - } else if (b == 27) { // escape - if (i < message.length - 4 && message[i + 4] == 126) { - i = i + 4; - } else if (i < message.length - 3 && message[i + 3] == 126) { - i = i + 3; - } else if (i < message.length - 2) { - i = i + 2; - } - } else if (b == -1 && i < message.length - 2 - && (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake - i = i + 2; - } else { - copy[index ++] = message[i]; - } - } - if (index == 0) { - return ""; - } - return new String(copy, 0, index, charset.name()).trim(); - } - - private static boolean isEquals(byte[] message, byte[] command) throws IOException { - return message.length == command.length && endsWith(message, command); - } - - private static boolean endsWith(byte[] message, byte[] command) throws IOException { - if (message.length < command.length) { - return false; - } - int offset = message.length - command.length; - for (int i = command.length - 1; i >= 0 ; i --) { - if (message[offset + i] != command[i]) { - return false; - } - } - return true; - } - + + private static Charset getCharset(Channel channel) { + if (channel != null) { + Object attribute = channel.getAttribute(Constants.CHARSET_KEY); + if (attribute instanceof String) { + try { + return Charset.forName((String) attribute); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); + } + } else if (attribute instanceof Charset) { + return (Charset) attribute; + } + URL url = channel.getUrl(); + if (url != null) { + String parameter = url.getParameter(Constants.CHARSET_KEY); + if (parameter != null && parameter.length() > 0) { + try { + return Charset.forName(parameter); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); + } + } + } + } + try { + return Charset.forName("GBK"); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); + } + return Charset.defaultCharset(); + } + + private static String toString(byte[] message, Charset charset) throws UnsupportedEncodingException { + byte[] copy = new byte[message.length]; + int index = 0; + for (int i = 0; i < message.length; i ++) { + byte b = message[i] ; + if (b == '\b') { // backspace + if (index > 0) { + index --; + } + if (i > 2 && message[i - 2] < 0) { // double byte char + if (index > 0) { + index --; + } + } + } else if (b == 27) { // escape + if (i < message.length - 4 && message[i + 4] == 126) { + i = i + 4; + } else if (i < message.length - 3 && message[i + 3] == 126) { + i = i + 3; + } else if (i < message.length - 2) { + i = i + 2; + } + } else if (b == -1 && i < message.length - 2 + && (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake + i = i + 2; + } else { + copy[index ++] = message[i]; + } + } + if (index == 0) { + return ""; + } + return new String(copy, 0, index, charset.name()).trim(); + } + + private static boolean isEquals(byte[] message, byte[] command) throws IOException { + return message.length == command.length && endsWith(message, command); + } + + private static boolean endsWith(byte[] message, byte[] command) throws IOException { + if (message.length < command.length) { + return false; + } + int offset = message.length - command.length; + for (int i = command.length - 1; i >= 0 ; i --) { + if (message[offset + i] != command[i]) { + return false; + } + } + return true; + } + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java index f3903bd2f79a..0d9a0b49d461 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java @@ -25,14 +25,14 @@ import com.alibaba.dubbo.common.serialize.Serialization; import com.alibaba.dubbo.common.utils.NetUtils; import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.ChannelCodec; /** * AbstractCodec * * @author william.liangf */ -public abstract class AbstractCodec implements Codec { +public abstract class AbstractCodec implements ChannelCodec { private static final Logger logger = LoggerFactory.getLogger(AbstractCodec.class); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java index db493fc471da..c7581e930fd8 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java @@ -1,39 +1,41 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport; -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.Resetable; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.Resetable; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.transport.codec.ChannelCodecAdapter; /** * AbstractEndpoint * * @author william.liangf */ -public abstract class AbstractEndpoint extends AbstractPeer implements Resetable { - +public abstract class AbstractEndpoint extends AbstractPeer implements Resetable { + private static final Logger logger = LoggerFactory.getLogger(AbstractEndpoint.class); - private Codec codec; + private ChannelCodec codec; private int timeout; @@ -41,7 +43,7 @@ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable public AbstractEndpoint(URL url, ChannelHandler handler) { super(url, handler); - this.codec = ExtensionLoader.getExtensionLoader(Codec.class).getExtension(url.getParameter(Constants.CODEC_KEY, "telnet")); + this.codec = getChannelCodec(url); this.timeout = url.getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); this.connectTimeout = url.getPositiveParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT); } @@ -74,19 +76,19 @@ public void reset(URL url) { try { if (url.hasParameter(Constants.CODEC_KEY)) { String c = url.getParameter(Constants.CODEC_KEY); - this.codec = ExtensionLoader.getExtensionLoader(Codec.class).getExtension(c); + this.codec = ExtensionLoader.getExtensionLoader(ChannelCodec.class).getExtension(c); } } catch (Throwable t) { logger.error(t.getMessage(), t); } - } - - @Deprecated - public void reset(com.alibaba.dubbo.common.Parameters parameters){ - reset(getUrl().addParameters(parameters.getParameters())); + } + + @Deprecated + public void reset(com.alibaba.dubbo.common.Parameters parameters){ + reset(getUrl().addParameters(parameters.getParameters())); } - protected Codec getCodec() { + protected ChannelCodec getCodec() { return codec; } @@ -98,4 +100,14 @@ protected int getConnectTimeout() { return connectTimeout; } + protected static ChannelCodec getChannelCodec(URL url) { + String codecName = url.getParameter(Constants.CODEC_KEY, "telnet"); + if (ExtensionLoader.getExtensionLoader(ChannelCodec.class).hasExtension(codecName)) { + return ExtensionLoader.getExtensionLoader(ChannelCodec.class).getExtension(codecName); + } else { + return new ChannelCodecAdapter(ExtensionLoader.getExtensionLoader(Codec.class) + .getExtension(codecName)); + } + } + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/ChannelCodecAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/ChannelCodecAdapter.java new file mode 100644 index 000000000000..bb2d02d692e1 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/ChannelCodecAdapter.java @@ -0,0 +1,63 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.remoting.transport.codec; + +import java.io.IOException; + +import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; +import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; + +/** + * @author kimi + */ +public class ChannelCodecAdapter implements ChannelCodec { + + private Codec codec; + + public ChannelCodecAdapter(Codec codec) { + this.codec = codec; + } + + public void encode(Channel channel, ChannelBuffer buffer, Object message) + throws IOException { + UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(1024); + codec.encode(channel, os, message); + buffer.writeBytes(os.toByteArray()); + } + + public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { + byte[] bytes = new byte[buffer.readableBytes()]; + int savedReaderIndex = buffer.readerIndex(); + buffer.readBytes(bytes); + UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(bytes); + Object result = codec.decode(channel, is); + if (result == Codec.NEED_MORE_INPUT) { + buffer.readerIndex(savedReaderIndex); + } else { + buffer.readerIndex(savedReaderIndex + is.position()); + } + return result == Codec.NEED_MORE_INPUT ? DecodeResult.NEED_MORE_INPUT : result; + } + + public Codec getCodec() { + return codec; + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java index 86597859bd5e..1616a0b7eaab 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/TransportCodec.java @@ -23,6 +23,9 @@ import com.alibaba.dubbo.common.serialize.ObjectOutput; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBufferInputStream; +import com.alibaba.dubbo.remoting.buffer.ChannelBufferOutputStream; import com.alibaba.dubbo.remoting.transport.AbstractCodec; /** @@ -32,13 +35,15 @@ */ public class TransportCodec extends AbstractCodec { - public void encode(Channel channel, OutputStream output, Object message) throws IOException { + public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException { + OutputStream output = new ChannelBufferOutputStream(buffer); ObjectOutput objectOutput = getSerialization(channel).serialize(channel.getUrl(), output); encodeData(channel, objectOutput, message); objectOutput.flushBuffer(); } - public Object decode(Channel channel, InputStream input) throws IOException { + public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { + InputStream input = new ChannelBufferInputStream(buffer); return decodeData(channel, getSerialization(channel).deserialize(channel.getUrl(), input)); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec b/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec similarity index 100% rename from dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec rename to dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java index 77023b006b38..14500fed7919 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/ExchangeCodecTest.java @@ -16,33 +16,31 @@ package com.alibaba.dubbo.remoting.codec; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.util.Date; import java.util.HashMap; -import junit.framework.Assert; - import org.junit.Before; import org.junit.Test; import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.io.Bytes; -import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; import com.alibaba.dubbo.common.serialize.ObjectOutput; import com.alibaba.dubbo.common.serialize.Serialization; import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.codec.ExchangeCodec; import com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec; +import junit.framework.Assert; +import static org.junit.Assert.fail; + /** * @author chao.liuc * byte 16 @@ -69,10 +67,10 @@ public class ExchangeCodecTest extends TelnetCodecTest{ private Object decode(byte[] request) throws IOException{ - InputStream input = new UnsafeByteArrayInputStream(request); + ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request); AbstractMockChannel channel = getServerSideChannel(url); //decode - Object obj = codec.decode(channel, input); + Object obj = codec.decode(channel, buffer); return obj; } @@ -111,9 +109,9 @@ public void setUp() throws Exception { @Test public void test_Decode_Error_MagicNum() throws IOException{ HashMap inputBytes = new HashMap(); - inputBytes.put( new byte[] { 0 }, TelnetCodec.NEED_MORE_INPUT ); - inputBytes.put( new byte[] { MAGIC_HIGH, 0 }, TelnetCodec.NEED_MORE_INPUT ); - inputBytes.put( new byte[] { 0 , MAGIC_LOW }, TelnetCodec.NEED_MORE_INPUT ); + inputBytes.put( new byte[] { 0 }, TelnetCodec.DecodeResult.NEED_MORE_INPUT ); + inputBytes.put( new byte[] { MAGIC_HIGH, 0 }, TelnetCodec.DecodeResult.NEED_MORE_INPUT ); + inputBytes.put( new byte[] { 0 , MAGIC_LOW }, TelnetCodec.DecodeResult.NEED_MORE_INPUT ); for (byte[] input : inputBytes.keySet()){ testDecode_assertEquals(assemblyDataProtocol(input) ,inputBytes.get(input)); @@ -128,12 +126,11 @@ public void test_Decode_Error_Length() throws IOException{ Channel channel = getServerSideChannel(url); byte[] baddata = new byte[]{1,2}; - UnsafeByteArrayInputStream input = new UnsafeByteArrayInputStream(join(request, baddata)); - Response obj = (Response)codec.decode(channel, input); + ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(join(request, baddata)); + Response obj = (Response)codec.decode(channel, buffer); Assert.assertEquals(person, obj.getResult()); - System.out.println(input.available()); //only decode necessary bytes - Assert.assertEquals(request.length, input.position()); + Assert.assertEquals(request.length, buffer.readerIndex()); } @Test public void test_Decode_Error_Response_Object() throws IOException{ @@ -154,7 +151,7 @@ public void test_Decode_Check_Payload() throws IOException { byte[] header = new byte[]{MAGIC_HIGH, MAGIC_LOW, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; byte[] request = assemblyDataProtocol(header); try { - testDecode_assertEquals(request, TelnetCodec.NEED_MORE_INPUT); + testDecode_assertEquals(request, TelnetCodec.DecodeResult.NEED_MORE_INPUT); fail(); } catch (IOException expected) { Assert.assertTrue(expected.getMessage().startsWith("Data length too large: " + Bytes.bytes2int(new byte[]{1, 1, 1, 1}))); @@ -163,13 +160,13 @@ public void test_Decode_Check_Payload() throws IOException { @Test public void test_Decode_Header_Need_Readmore() throws IOException{ byte[] header = new byte[] { MAGIC_HIGH , MAGIC_LOW , 0 ,0 ,0 ,0 ,0 , 0 ,0 ,0 ,0 }; - testDecode_assertEquals(header, TelnetCodec.NEED_MORE_INPUT); + testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT); } @Test public void test_Decode_Body_Need_Readmore() throws IOException{ byte[] header = new byte[] { MAGIC_HIGH , MAGIC_LOW , 0 ,0 ,0 ,0 ,0 , 0 ,0 ,0 ,0, 0, 0, 0 , 1 ,1, 'a', 'a' }; - testDecode_assertEquals(header, TelnetCodec.NEED_MORE_INPUT); + testDecode_assertEquals(header, TelnetCodec.DecodeResult.NEED_MORE_INPUT); } @Test public void test_Decode_MigicCodec_Contain_ExchangeHeader() throws IOException{ @@ -177,11 +174,11 @@ public void test_Decode_MigicCodec_Contain_ExchangeHeader() throws IOException{ byte[] header = new byte[] { 0, 0, MAGIC_HIGH , MAGIC_LOW , 0 ,0 ,0 ,0 ,0 , 0 ,0 ,0 ,0 }; Channel channel = getServerSideChannel(url); - UnsafeByteArrayInputStream input = new UnsafeByteArrayInputStream(header); - Object obj = codec.decode(channel, input); - Assert.assertEquals(TelnetCodec.NEED_MORE_INPUT, obj); + ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(header); + Object obj = codec.decode(channel, buffer); + Assert.assertEquals(TelnetCodec.DecodeResult.NEED_MORE_INPUT, obj); //濡傛灉telnet鏁版嵁涓巖equest鏁版嵁鍦ㄥ悓涓涓暟鎹寘涓紝涓嶈兘鍥犱负telnet娌℃湁缁撳熬瀛楃鑰屽奖鍝嶅叾浠栨暟鎹殑鎺ユ敹. - Assert.assertEquals(2, input.position()); + Assert.assertEquals(2, buffer.readerIndex()); } @Test @@ -307,20 +304,19 @@ public void test_Header_Response_Heartbeat() throws IOException{ @Test public void test_Encode_Request() throws IOException{ - UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); + ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(2014); Channel channel = getCliendSideChannel(url); Request request = new Request(); Person person = new Person(); request.setData(person); - codec.encode(channel, bos, request); - byte[] data = bos.toByteArray(); - bos.flush(); - bos.close(); - - //encode resault check need decode - InputStream input = new UnsafeByteArrayInputStream(data); - Request obj = (Request)codec.decode(channel, input); + codec.encode(channel, encodeBuffer, request); + + //encode resault check need decode + byte[] data = new byte[encodeBuffer.writerIndex()]; + encodeBuffer.readBytes(data); + ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); + Request obj = (Request)codec.decode(channel, decodeBuffer); Assert.assertEquals(request.isBroken(), obj.isBroken()); Assert.assertEquals(request.isHeartbeat(), obj.isHeartbeat()); Assert.assertEquals(request.isTwoWay(), obj.isTwoWay()); @@ -329,7 +325,7 @@ public void test_Encode_Request() throws IOException{ @Test public void test_Encode_Response() throws IOException{ - UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); + ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); Channel channel = getCliendSideChannel(url); Response response = new Response(); response.setHeartbeat(true); @@ -339,14 +335,13 @@ public void test_Encode_Response() throws IOException{ Person person = new Person(); response.setResult(person); - codec.encode(channel, bos, response); - byte[] data = bos.toByteArray(); - bos.flush(); - bos.close(); - + codec.encode(channel, encodeBuffer, response); + byte[] data = new byte[encodeBuffer.writerIndex()]; + encodeBuffer.readBytes(data); + //encode resault check need decode - InputStream input = new UnsafeByteArrayInputStream(data); - Response obj = (Response)codec.decode(channel, input); + ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); + Response obj = (Response)codec.decode(channel, decodeBuffer); Assert.assertEquals(response.getId(), obj.getId()); Assert.assertEquals(response.getStatus(), obj.getStatus()); @@ -359,7 +354,7 @@ public void test_Encode_Response() throws IOException{ @Test public void test_Encode_Error_Response() throws IOException{ - UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); + ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); Channel channel = getCliendSideChannel(url); Response response = new Response(); response.setHeartbeat(true); @@ -371,14 +366,13 @@ public void test_Encode_Error_Response() throws IOException{ Person person = new Person(); response.setResult(person); - codec.encode(channel, bos, response); - byte[] data = bos.toByteArray(); - bos.flush(); - bos.close(); - + codec.encode(channel, encodeBuffer, response); + byte[] data = new byte[encodeBuffer.writerIndex()]; + encodeBuffer.readBytes(data); + //encode resault check need decode - InputStream input = new UnsafeByteArrayInputStream(data); - Response obj = (Response)codec.decode(channel, input); + ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(data); + Response obj = (Response)codec.decode(channel, decodeBuffer); Assert.assertEquals(response.getId(), obj.getId()); Assert.assertEquals(response.getStatus(), obj.getStatus()); Assert.assertEquals(response.isHeartbeat(), obj.isHeartbeat()); @@ -395,9 +389,10 @@ public void testMessageLengthGreaterThanMessageActualLength() throws Exception { request.setVersion("2.0.0"); Date date = new Date(); request.setData(date); - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); - codec.encode(channel, outputStream, request); - byte[] bytes = outputStream.toByteArray(); + ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(1024); + codec.encode(channel, encodeBuffer, request); + byte[] bytes = new byte[encodeBuffer.writerIndex()]; + encodeBuffer.readBytes(bytes); int len = Bytes.bytes2int(bytes, 12); ByteArrayOutputStream out = new ByteArrayOutputStream(1024); out.write(bytes, 0, 12); @@ -413,11 +408,11 @@ public void testMessageLengthGreaterThanMessageActualLength() throws Exception { } out.write(bytes); /* request|1111...|request */ - UnsafeByteArrayInputStream inputStream = new UnsafeByteArrayInputStream(out.toByteArray()); - Request decodedRequest = (Request)codec.decode(channel, inputStream); + ChannelBuffer decodeBuffer = ChannelBuffers.wrappedBuffer(out.toByteArray()); + Request decodedRequest = (Request)codec.decode(channel, decodeBuffer); Assert.assertTrue(date.equals(decodedRequest.getData())); - Assert.assertEquals(bytes.length + padding, inputStream.position()); - decodedRequest = (Request)codec.decode(channel, inputStream); + Assert.assertEquals(bytes.length + padding, decodeBuffer.readerIndex()); + decodedRequest = (Request)codec.decode(channel, decodeBuffer); Assert.assertTrue(date.equals(decodedRequest.getData())); } @@ -425,10 +420,10 @@ public void testMessageLengthGreaterThanMessageActualLength() throws Exception { public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { Request request = new Request(1L); request.setData("hello"); - UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(512); + ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(512); AbstractMockChannel channel = getCliendSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); try { - codec.encode(channel, bos, request); + codec.encode(channel, encodeBuffer, request); Assert.fail(); } catch (IOException e) { Assert.assertTrue(e.getMessage().startsWith("Data length too large: " + 6)); @@ -436,9 +431,9 @@ public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception { Response response = new Response(1L); response.setResult("hello"); - bos = new UnsafeByteArrayOutputStream(512); + encodeBuffer = ChannelBuffers.dynamicBuffer(512); channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4)); - codec.encode(channel, bos, response); + codec.encode(channel, encodeBuffer, response); Assert.assertTrue(channel.getReceivedMessage() instanceof Response); Response receiveMessage = (Response) channel.getReceivedMessage(); Assert.assertEquals(Response.BAD_RESPONSE, receiveMessage.getStatus()); diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java index 1f87b4beb563..fb8e62fb59f7 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java @@ -1,48 +1,47 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.codec; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; -import junit.framework.Assert; - import org.junit.Before; import org.junit.Test; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; -import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; import com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec; +import junit.framework.Assert; + /** * @author chao.liuc * */ public class TelnetCodecTest { - protected Codec codec ; + protected ChannelCodec codec ; byte[] UP = new byte[] {27, 91, 65}; byte[] DOWN = new byte[] {27, 91, 66}; /** @@ -150,10 +149,10 @@ protected void testDecode_assertEquals(byte[] request,Object ret, boolean isServ //init channel Channel channel = isServerside? getServerSideChannel(url) : getCliendSideChannel(url); //init request string - InputStream input = new UnsafeByteArrayInputStream(request); - + ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(request); + //decode - Object obj = codec.decode(channel, input); + Object obj = codec.decode(channel, buffer); Assert.assertEquals(ret, obj); } @@ -162,16 +161,13 @@ protected void testDecode_assertEquals(byte[] request,Object ret, boolean isServ protected void testEecode_assertEquals(Object request,byte[] ret, boolean isServerside) throws IOException{ //init channel Channel channel = isServerside? getServerSideChannel(url) : getCliendSideChannel(url); - - UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); - - codec.encode(channel, bos, request); - bos.flush(); - bos.close(); - InputStream is = new ByteArrayInputStream(bos.toByteArray()); - byte[] data = new byte[is.available()]; - is.read(data); - + + ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024); + + codec.encode(channel, buffer, request); + byte[] data = new byte[buffer.readableBytes()]; + buffer.readBytes(data); + Assert.assertEquals(ret.length, data.length); for(int i=0;i connection = context.getConnection(); GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); try { - UnsafeByteArrayOutputStream output = new UnsafeByteArrayOutputStream(1024); // 涓嶉渶瑕佸叧闂 + ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer(1024); // 涓嶉渶瑕佸叧闂 Object msg = context.getMessage(); - codec.encode(channel, output, msg); + codec.encode(channel, channelBuffer, msg); GrizzlyChannel.removeChannelIfDisconnectd(connection); - byte[] bytes = output.toByteArray(); - Buffer buffer = connection.getTransport().getMemoryManager().allocate(bytes.length); - buffer.put(bytes); + Buffer buffer = connection.getTransport().getMemoryManager().allocate(channelBuffer.readableBytes()); + buffer.put(channelBuffer.toByteBuffer()); buffer.flip(); buffer.allowBufferDispose(true); context.setMessage(buffer); @@ -87,34 +86,51 @@ public NextAction handleRead(FilterChainContext context) throws IOException { Channel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); try { if (message instanceof Buffer) { // 鏀跺埌鏂扮殑鏁版嵁鍖 - Buffer buffer = (Buffer) message; // 缂撳瓨 - int readable = buffer.capacity(); // 鏈鍙鍙栨柊鏁版嵁鐨勫ぇ灏 - if (readable == 0) { - return context.getStopAction(); - } - byte[] bytes; // byte[]缂撳瓨鍖猴紝灏咮uffer杞垚byte[]锛屽啀杞垚UnsafeByteArrayInputStream - int offset; // 鎸囧悜宸茬敤鏁版嵁鐨勫亸绉婚噺锛宱ff涔嬪墠鐨勬暟鎹兘鏄凡鐢ㄨ繃鐨 - int limit; // 鏈夋晥闀垮害锛宭imit涔嬪悗鐨勯暱搴︽槸绌虹櫧鎴栨棤鏁堟暟鎹紝off鍒發imit涔嬮棿鐨勬暟鎹槸鍑嗗浣跨敤鐨勬湁鏁堟暟鎹 - Object[] remainder = (Object[]) channel.getAttribute(BUFFER_KEY); // 涓婃搴忓垪鍖栧墿涓嬬殑鏁版嵁 - channel.removeAttribute(BUFFER_KEY); - if (remainder == null) { // 濡傛灉娌℃湁锛屽垱寤烘柊鐨刡ytes缂撳瓨 - bytes = new byte[bufferSize]; - offset = 0; - limit = 0; - } else { // 濡傛灉鏈夛紝浣跨敤鍓╀笅鐨刡ytes缂撳瓨 - bytes = (byte[]) remainder[0]; - offset = (Integer) remainder[1]; - limit = (Integer) remainder[2]; + Buffer grizzlyBuffer = (Buffer) message; // 缂撳瓨 + + ChannelBuffer frame; + + if (previousData.readable()) { + if (previousData instanceof DynamicChannelBuffer) { + previousData.writeBytes(grizzlyBuffer.toByteBuffer()); + frame = previousData; + } else { + int size = previousData.readableBytes() + grizzlyBuffer.remaining(); + frame = ChannelBuffers.dynamicBuffer(size > bufferSize ? size : bufferSize); + frame.writeBytes(previousData, previousData.readableBytes()); + frame.writeBytes(grizzlyBuffer.toByteBuffer()); + } + } else { + frame = ChannelBuffers.wrappedBuffer(grizzlyBuffer.toByteBuffer()); } - return receive(context, channel, buffer, readable, bytes, offset, limit); - } else if (message instanceof Object[]) { // 鍚屼竴Buffer澶氳疆Filter锛屽嵆锛氫竴涓狟uffer閲屾湁澶氫釜璇锋眰 - Object[] remainder = (Object[]) message; - Buffer buffer = (Buffer) remainder[0]; - int readable = (Integer) remainder[1]; - byte[] bytes = (byte[]) remainder[2]; - int offset = (Integer) remainder[3]; - int limit = (Integer) remainder[4]; - return receive(context, channel, buffer, readable, bytes, offset, limit); + + Object msg; + int savedReadIndex; + + do { + savedReadIndex = frame.readerIndex(); + try { + msg = codec.decode(channel, frame); + } catch (Exception e) { + previousData = ChannelBuffers.EMPTY_BUFFER; + throw new IOException(e.getMessage(), e); + } + if (msg == ChannelCodec.DecodeResult.NEED_MORE_INPUT) { + frame.readerIndex(savedReadIndex); + return context.getStopAction(); + } else { + if (savedReadIndex == frame.readerIndex()) { + previousData = ChannelBuffers.EMPTY_BUFFER; + throw new IOException("Decode without read data."); + } + if (msg != null) { + context.setMessage(msg); + return context.getInvokeAction(); + } else { + return context.getInvokeAction(); + } + } + } while (frame.readable()); } else { // 鍏跺畠浜嬩欢鐩存帴寰涓嬩紶 return context.getInvokeAction(); } @@ -122,56 +138,5 @@ public NextAction handleRead(FilterChainContext context) throws IOException { GrizzlyChannel.removeChannelIfDisconnectd(connection); } } - - /* - * 鎺ユ敹 - * - * @param context 涓婁笅鏂 - * @param channel 閫氶亾 - * @param buffer 缂撳瓨 - * @param readable 缂撳瓨鍙 - * @param bytes 杈撳叆缂撳瓨 - * @param offset 鎸囧悜宸茶鏁版嵁鐨勫亸绉婚噺锛宱ff涔嬪墠鐨勬暟鎹兘鏄凡鐢ㄨ繃鐨 - * @param limit 鏈夋晥闀垮害锛宭imit涔嬪悗鐨勯暱搴︽槸绌虹櫧鎴栨棤鏁堟暟鎹紝off鍒發imit涔嬮棿鐨勬暟鎹槸鍑嗗浣跨敤鐨勬暟鎹 - * @return 鍚庣画鍔ㄤ綔 - * @throws IOException - */ - private NextAction receive(FilterChainContext context, Channel channel, Buffer buffer, int readable, byte[] bytes, int offset, int limit) throws IOException { - for(;;) { - int read = Math.min(readable, bytes.length - limit); // 鍙朾ytes缂撳瓨绌洪棽鍖猴紝鍜屽彲璇诲彇鏂版暟鎹紝鐨勬渶灏忓硷紝鍗筹細姝ゆ鏈澶氳鍐欐暟鎹殑澶у皬 - buffer.get(bytes, limit, read); // 浠庡彲璇诲彇鏂版暟鎹腑锛岃鍙栨暟鎹紝灏介噺濉弧bytes缂撳瓨绌洪棽鍖 - limit += read; // 鏈夋晥鏁版嵁鍙橀暱 - readable -= read; // 鍙鏁版嵁鍙樺皯 - UnsafeByteArrayInputStream input = new UnsafeByteArrayInputStream(bytes, offset, limit - offset); // 灏哹ytes缂撳瓨杞垚InputStream锛屼笉闇瑕佸叧闂 - Object msg = codec.decode(channel, input); // 璋冪敤Codec鎺ュ彛锛岃В鐮佹暟鎹 - if (msg == Codec.NEED_MORE_INPUT) { // 濡傛灉Codec瑙夊緱鏁版嵁涓嶅锛屼笉瓒充互瑙g爜鎴愪竴涓璞 - if (readable == 0) { // 濡傛灉娌℃湁鏇村鍙鏁版嵁 - channel.setAttribute(BUFFER_KEY, new Object[] { bytes, offset, limit }); // 鏀惧叆閫氶亾灞炴т腑锛岀瓑寰呬笅涓涓狟uffer鐨勫埌鏉 - return context.getStopAction(); - } else { // 鎵╁厖鎴栨尓鍑虹┖闂插尯锛屽苟寰幆锛岀洿鍒板彲璇绘暟鎹兘鍔犺浇鍒癰ytes缂撳瓨 - if (offset == 0) { // 濡傛灉bytes缂撳瓨鍏ㄩ儴娌℃湁琚娇鐢紝濡傛灉杩欐椂鏁版嵁杩樹笉澶 - bytes = Bytes.copyOf(bytes, bytes.length << 1); // 灏哹ytes缂撳瓨鎵╁ぇ涓鍊 - } else { // 濡傛灉bytes缂撳瓨鏈変竴娈垫暟鎹凡琚娇鐢 - int len = limit - offset; // 璁$畻鏈夋晥鏁版嵁闀垮害 - System.arraycopy(bytes, offset, bytes, 0, len); // 灏嗘暟鎹悜鍓嶇Щ鍒帮紝鍘嬬缉鍒板凡浣跨敤鐨勯儴鍒嗭紝杩欐牱limit鍚庨潰灏变細澶氬嚭涓浜涚┖闂诧紝鍙互鏀炬暟鎹 - offset = 0; // 绉诲埌鍚庯紝bytes缂撳瓨娌℃湁鏁版嵁琚娇鐢 - limit = len; // 绉诲埌鍚庯紝鏈夋晥鏁版嵁閮藉湪bytes缂撳瓨鏈鍓嶉潰 - } - } - } else { // 濡傛灉瑙f瀽鍑轰竴涓粨鏋 - int position = input.position(); // 璁板綍InputStream鐢ㄤ簡澶氬皯 - if (position == offset) { // 濡傛灉InputStream娌℃湁琚杩囷紝灏辫繑鍥炰簡鏁版嵁锛岀洿鎺ユ姤閿欙紝鍚﹀垯InputStream姘歌繙璇讳笉瀹岋紝浼氭閫掑綊 - throw new IOException("Decode without read data."); - } - offset = position; // 璁板綍宸茶鏁版嵁 - context.setMessage(msg); // 灏嗘秷鎭敼涓鸿В鐮佸悗鐨勫璞★紝浠ヤ究琚悗闈㈢殑Filter浣跨敤銆 - if (limit - offset > 0 || readable > 0) { // 濡傛灉鏈夋晥鏁版嵁娌℃湁琚瀹岋紝鎴栬匓uffer鍖鸿繕鏈夋湭璇绘暟鎹 - return context.getInvokeAction(new Object[] { buffer, readable, bytes, offset, limit }); // 姝e父鎵ц瀹孎ilter锛屽苟閲嶆柊鍙戣捣涓杞瓼ilter锛岀户缁 - } else { // 鍚﹀垯鎵鏈夋暟鎹瀹 - return context.getInvokeAction(); // 姝e父鎵ц瀹孎ilter - } - } - } - } } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java index aa86990e8f6a..68285173ac38 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java @@ -1,65 +1,61 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.mina; -import java.io.IOException; - -import org.apache.mina.common.ByteBuffer; -import org.apache.mina.common.IoSession; -import org.apache.mina.filter.codec.ProtocolCodecFactory; -import org.apache.mina.filter.codec.ProtocolDecoder; -import org.apache.mina.filter.codec.ProtocolDecoderOutput; -import org.apache.mina.filter.codec.ProtocolEncoder; -import org.apache.mina.filter.codec.ProtocolEncoderOutput; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.io.Bytes; -import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; -import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.Codec; +import org.apache.mina.common.ByteBuffer; +import org.apache.mina.common.IoSession; +import org.apache.mina.filter.codec.ProtocolCodecFactory; +import org.apache.mina.filter.codec.ProtocolDecoder; +import org.apache.mina.filter.codec.ProtocolDecoderOutput; +import org.apache.mina.filter.codec.ProtocolEncoder; +import org.apache.mina.filter.codec.ProtocolEncoderOutput; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; +import com.alibaba.dubbo.remoting.buffer.DynamicChannelBuffer; /** * MinaCodecAdapter. - * + * * @author qian.lei */ final class MinaCodecAdapter implements ProtocolCodecFactory { - private static final String BUFFER_KEY = MinaCodecAdapter.class.getName() + ".BUFFER"; - private final ProtocolEncoder encoder = new InternalEncoder(); private final ProtocolDecoder decoder = new InternalDecoder(); - private final Codec codec; + private final ChannelCodec codec; private final URL url; - + private final ChannelHandler handler; private final int bufferSize; - - public MinaCodecAdapter(Codec codec, URL url, ChannelHandler handler) { + + public MinaCodecAdapter(ChannelCodec codec, URL url, ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; - int b = url.getPositiveParameter(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); + int b = url.getPositiveParameter(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); this.bufferSize = b >= Constants.MIN_BUFFER_SIZE && b <= Constants.MAX_BUFFER_SIZE ? b : Constants.DEFAULT_BUFFER_SIZE; } @@ -77,93 +73,74 @@ public void dispose(IoSession session) throws Exception { } public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) throws Exception { - UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(1024); // 涓嶉渶瑕佸叧闂 + ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024); MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler); try { - codec.encode(channel, os, msg); + codec.encode(channel, buffer, msg); } finally { MinaChannel.removeChannelIfDisconnectd(session); } - out.write(ByteBuffer.wrap(os.toByteArray())); + out.write(ByteBuffer.wrap(buffer.toByteBuffer())); out.flush(); } } private class InternalDecoder implements ProtocolDecoder { + private ChannelBuffer buffer = ChannelBuffers.EMPTY_BUFFER; + public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { int readable = in.limit(); if (readable <= 0) return; - int off, limit; - byte[] buf; - // load buffer from context. - Object[] tmp = (Object[]) session.getAttribute(BUFFER_KEY); - if (tmp == null) { - buf = new byte[bufferSize]; - off = limit = 0; + ChannelBuffer frame; + + if (buffer.readable()) { + if (buffer instanceof DynamicChannelBuffer) { + buffer.writeBytes(in.buf()); + frame = buffer; + } else { + int size = buffer.readableBytes() + in.remaining(); + frame = ChannelBuffers.dynamicBuffer(size > bufferSize ? size : bufferSize); + frame.writeBytes(buffer, buffer.readableBytes()); + frame.writeBytes(in.buf()); + } } else { - buf = (byte[]) tmp[0]; - off = (Integer) tmp[1]; - limit = (Integer) tmp[2]; + frame = ChannelBuffers.wrappedBuffer(in.buf()); } Channel channel = MinaChannel.getOrAddChannel(session, url, handler); - boolean remaining = true; Object msg; - UnsafeByteArrayInputStream bis; + int savedReadIndex; + try { do { - // read data into buffer. - int read = Math.min(readable, buf.length - limit); - in.get(buf, limit, read); - limit += read; - readable -= read; - bis = new UnsafeByteArrayInputStream(buf, off, limit - off); // 涓嶉渶瑕佸叧闂 - // decode object. - do { - try { - msg = codec.decode(channel, bis); - } catch (IOException e) { - remaining = false; - throw e; + savedReadIndex = frame.readerIndex(); + try { + msg = codec.decode(channel, frame); + } catch (Exception e) { + buffer = ChannelBuffers.EMPTY_BUFFER; + throw e; + } + if (msg == ChannelCodec.DecodeResult.NEED_MORE_INPUT) { + frame.readerIndex(savedReadIndex); + break; + } else { + if (savedReadIndex == frame.readerIndex()) { + buffer = ChannelBuffers.EMPTY_BUFFER; + throw new Exception("Decode without read data."); } - if (msg == Codec.NEED_MORE_INPUT) { - if (off == 0) { - if (readable > 0) { - buf = Bytes.copyOf(buf, buf.length << 1); - } - } else { - int len = limit - off; - System.arraycopy(buf, off, buf, 0, len); - off = 0; - limit = len; - } - break; - } else { - int pos = bis.position(); - if (pos == off) { - remaining = false; - throw new IOException("Decode without read data."); - } - if (msg != null) { - out.write(msg); - } - off = pos; + if (msg != null) { + out.write(msg); } - } while (bis.available() > 0); - } while (readable > 0); - } finally { - if (remaining) { - int len = limit - off; - if (len < buf.length / 2) { - System.arraycopy(buf, off, buf, 0, len); - off = 0; - limit = len; } - session.setAttribute(BUFFER_KEY, new Object[] { buf, off, limit }); + } while (frame.readable()); + } finally { + if (frame.readable()) { + frame.discardReadBytes(); + buffer = frame; } else { - session.removeAttribute(BUFFER_KEY); + buffer = ChannelBuffers.EMPTY_BUFFER; } MinaChannel.removeChannelIfDisconnectd(session); } diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyBackedChannelBuffer.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyBackedChannelBuffer.java new file mode 100644 index 000000000000..9ed56f5f00fb --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyBackedChannelBuffer.java @@ -0,0 +1,376 @@ +package com.alibaba.dubbo.remoting.transport.netty; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; + +import com.alibaba.dubbo.common.utils.Assert; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBufferFactory; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; + +/** + * @author kimi + */ +public class NettyBackedChannelBuffer implements ChannelBuffer { + + private org.jboss.netty.buffer.ChannelBuffer buffer; + + public org.jboss.netty.buffer.ChannelBuffer nettyChannelBuffer() { + return buffer; + } + + public NettyBackedChannelBuffer(org.jboss.netty.buffer.ChannelBuffer buffer) { + Assert.notNull(buffer, "buffer == null"); + this.buffer = buffer; + } + + @Override + public int capacity() { + return buffer.capacity(); + } + + @Override + public ChannelBuffer copy(int index, int length) { + return new NettyBackedChannelBuffer(buffer.copy(index, length)); + } + + @Override + public ChannelBufferFactory factory() { + return NettyBackedChannelBufferFactory.getInstance(); + } + + @Override + public byte getByte(int index) { + return buffer.getByte(index); + } + + @Override + public void getBytes(int index, byte[] dst, int dstIndex, int length) { + buffer.getBytes(index, dst, dstIndex, length); + } + + @Override + public void getBytes(int index, ByteBuffer dst) { + buffer.getBytes(index, dst); + } + + @Override + public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { + // careful + byte[] data = new byte[length]; + buffer.getBytes(index, data, 0, length); + dst.setBytes(dstIndex, data, 0, length); + } + + @Override + public void getBytes(int index, OutputStream dst, int length) throws IOException { + buffer.getBytes(index, dst, length); + } + + @Override + public boolean isDirect() { + return buffer.isDirect(); + } + + @Override + public void setByte(int index, int value) { + buffer.setByte(index, value); + } + + @Override + public void setBytes(int index, byte[] src, int srcIndex, int length) { + buffer.setBytes(index, src, srcIndex, length); + } + + @Override + public void setBytes(int index, ByteBuffer src) { + buffer.setBytes(index, src); + } + + @Override + public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { + // careful + byte[] data = new byte[length]; + buffer.getBytes(srcIndex, data, 0, length); + setBytes(0, data, index, length); + } + + @Override + public int setBytes(int index, InputStream src, int length) throws IOException { + return buffer.setBytes(index, src, length); + } + + @Override + public ByteBuffer toByteBuffer(int index, int length) { + return buffer.toByteBuffer(index, length); + } + + @Override + public byte[] array() { + return buffer.array(); + } + + @Override + public boolean hasArray() { + return buffer.hasArray(); + } + + @Override + public int arrayOffset() { + return buffer.arrayOffset(); + } + + + // AbstractChannelBuffer + + + @Override + public void clear() { + buffer.clear(); + } + + @Override + public ChannelBuffer copy() { + return new NettyBackedChannelBuffer(buffer.copy()); + } + + @Override + public void discardReadBytes() { + buffer.discardReadBytes(); + } + + @Override + public void ensureWritableBytes(int writableBytes) { + buffer.ensureWritableBytes(writableBytes); + } + + @Override + public void getBytes(int index, byte[] dst) { + buffer.getBytes(index, dst); + } + + @Override + public void getBytes(int index, ChannelBuffer dst) { + // careful + getBytes(index, dst, dst.writableBytes()); + } + + @Override + public void getBytes(int index, ChannelBuffer dst, int length) { + // careful + if (length > dst.writableBytes()) { + throw new IndexOutOfBoundsException(); + } + getBytes(index, dst, dst.writerIndex(), length); + dst.writerIndex(dst.writerIndex() + length); + } + + @Override + public void markReaderIndex() { + buffer.markReaderIndex(); + } + + @Override + public void markWriterIndex() { + buffer.markWriterIndex(); + } + + @Override + public boolean readable() { + return buffer.readable(); + } + + @Override + public int readableBytes() { + return buffer.readableBytes(); + } + + @Override + public byte readByte() { + return buffer.readByte(); + } + + @Override + public void readBytes(byte[] dst) { + buffer.readBytes(dst); + } + + @Override + public void readBytes(byte[] dst, int dstIndex, int length) { + buffer.readBytes(dst, dstIndex, length); + } + + @Override + public void readBytes(ByteBuffer dst) { + buffer.readBytes(dst); + } + + @Override + public void readBytes(ChannelBuffer dst) { + // careful + readBytes(dst, dst.writableBytes()); + } + + @Override + public void readBytes(ChannelBuffer dst, int length) { + // carefule + if (length > dst.writableBytes()) { + throw new IndexOutOfBoundsException(); + } + readBytes(dst, dst.writerIndex(), length); + dst.writerIndex(dst.writerIndex() + length); + } + + @Override + public void readBytes(ChannelBuffer dst, int dstIndex, int length) { + // careful + if (readableBytes() < length) { + throw new IndexOutOfBoundsException(); + } + byte[] data = new byte[length]; + buffer.readBytes(data, 0, length); + dst.setBytes(dstIndex, data, 0, length); + } + + @Override + public ChannelBuffer readBytes(int length) { + return new NettyBackedChannelBuffer(buffer.readBytes(length)); + } + + @Override + public void resetReaderIndex() { + buffer.resetReaderIndex(); + } + + @Override + public void resetWriterIndex() { + buffer.resetWriterIndex(); + } + + @Override + public int readerIndex() { + return buffer.readerIndex(); + } + + @Override + public void readerIndex(int readerIndex) { + buffer.readerIndex(readerIndex); + } + + @Override + public void readBytes(OutputStream dst, int length) throws IOException { + buffer.readBytes(dst, length); + } + + @Override + public void setBytes(int index, byte[] src) { + buffer.setBytes(index, src); + } + + @Override + public void setBytes(int index, ChannelBuffer src) { + // careful + setBytes(index, src, src.readableBytes()); + } + + @Override + public void setBytes(int index, ChannelBuffer src, int length) { + // careful + if (length > src.readableBytes()) { + throw new IndexOutOfBoundsException(); + } + setBytes(index, src, src.readerIndex(), length); + src.readerIndex(src.readerIndex() + length); + } + + @Override + public void setIndex(int readerIndex, int writerIndex) { + buffer.setIndex(readerIndex, writerIndex); + } + + @Override + public void skipBytes(int length) { + buffer.skipBytes(length); + } + + @Override + public ByteBuffer toByteBuffer() { + return buffer.toByteBuffer(); + } + + @Override + public boolean writable() { + return buffer.writable(); + } + + @Override + public int writableBytes() { + return buffer.writableBytes(); + } + + @Override + public void writeByte(int value) { + buffer.writeByte(value); + } + + @Override + public void writeBytes(byte[] src) { + buffer.writeBytes(src); + } + + @Override + public void writeBytes(byte[] src, int index, int length) { + buffer.writeBytes(src, index, length); + } + + @Override + public void writeBytes(ByteBuffer src) { + buffer.writeBytes(src); + } + + @Override + public void writeBytes(ChannelBuffer src) { + // careful + writeBytes(src, src.readableBytes()); + } + + @Override + public void writeBytes(ChannelBuffer src, int length) { + // careful + if (length > src.readableBytes()) { + throw new IndexOutOfBoundsException(); + } + writeBytes(src, src.readerIndex(), length); + src.readerIndex(src.readerIndex() + length); + } + + @Override + public void writeBytes(ChannelBuffer src, int srcIndex, int length) { + // careful + byte[] data = new byte[length]; + src.getBytes(srcIndex, data, 0, length); + writeBytes(data, 0, length); + } + + @Override + public int writeBytes(InputStream src, int length) throws IOException { + return buffer.writeBytes(src, length); + } + + @Override + public int writerIndex() { + return buffer.writerIndex(); + } + + @Override + public void writerIndex(int writerIndex) { + buffer.writerIndex(writerIndex); + } + + @Override + public int compareTo(ChannelBuffer o) { + return ChannelBuffers.compare(this, o); + } +} diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyBackedChannelBufferFactory.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyBackedChannelBufferFactory.java new file mode 100644 index 000000000000..aa1ae80cfc38 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyBackedChannelBufferFactory.java @@ -0,0 +1,39 @@ +package com.alibaba.dubbo.remoting.transport.netty; + +import java.nio.ByteBuffer; + +import org.jboss.netty.buffer.ChannelBuffers; + +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBufferFactory; + +/** + * Wrap netty dynamic channel buffer. + * + * @author kimi + */ +public class NettyBackedChannelBufferFactory implements ChannelBufferFactory { + + private static final NettyBackedChannelBufferFactory INSTANCE = new NettyBackedChannelBufferFactory(); + + public static ChannelBufferFactory getInstance() { + return INSTANCE; + } + + @Override + public ChannelBuffer getBuffer(int capacity) { + return new NettyBackedChannelBuffer(ChannelBuffers.dynamicBuffer(capacity)); + } + + @Override + public ChannelBuffer getBuffer(byte[] array, int offset, int length) { + org.jboss.netty.buffer.ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(length); + buffer.writeBytes(array, offset, length); + return new NettyBackedChannelBuffer(buffer); + } + + @Override + public ChannelBuffer getBuffer(ByteBuffer nioBuffer) { + return new NettyBackedChannelBuffer(ChannelBuffers.wrappedBuffer(nioBuffer)); + } +} diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java index 86f466d8735c..9155aa09eeec 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java @@ -1,40 +1,38 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.transport.netty; -import java.io.IOException; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.jboss.netty.channel.Channel; -import org.jboss.netty.channel.ChannelHandler; -import org.jboss.netty.channel.ChannelHandler.Sharable; -import org.jboss.netty.channel.ChannelHandlerContext; -import org.jboss.netty.channel.Channels; -import org.jboss.netty.channel.ExceptionEvent; -import org.jboss.netty.channel.MessageEvent; -import org.jboss.netty.channel.SimpleChannelUpstreamHandler; -import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.io.Bytes; -import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; -import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; -import com.alibaba.dubbo.remoting.Codec; +import java.io.IOException; + +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelHandler; +import org.jboss.netty.channel.ChannelHandler.Sharable; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.ExceptionEvent; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.channel.SimpleChannelUpstreamHandler; +import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.buffer.DynamicChannelBuffer; /** * NettyCodecAdapter. @@ -47,7 +45,7 @@ final class NettyCodecAdapter { private final ChannelHandler decoder = new InternalDecoder(); - private final Codec codec; + private final ChannelCodec codec; private final URL url; @@ -55,11 +53,11 @@ final class NettyCodecAdapter { private final com.alibaba.dubbo.remoting.ChannelHandler handler; - public NettyCodecAdapter(Codec codec, URL url, com.alibaba.dubbo.remoting.ChannelHandler handler) { + public NettyCodecAdapter(ChannelCodec codec, URL url, com.alibaba.dubbo.remoting.ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; - int b = url.getPositiveParameter(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); + int b = url.getPositiveParameter(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); this.bufferSize = b >= Constants.MIN_BUFFER_SIZE && b <= Constants.MAX_BUFFER_SIZE ? b : Constants.DEFAULT_BUFFER_SIZE; } @@ -76,22 +74,22 @@ private class InternalEncoder extends OneToOneEncoder { @Override protected Object encode(ChannelHandlerContext ctx, Channel ch, Object msg) throws Exception { - UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(1024); // 涓嶉渶瑕佸叧闂 + com.alibaba.dubbo.remoting.buffer.ChannelBuffer buffer = + com.alibaba.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(1024); NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler); try { - codec.encode(channel, os, msg); + codec.encode(channel, buffer, msg); } finally { NettyChannel.removeChannelIfDisconnected(ch); } - return ChannelBuffers.wrappedBuffer(os.toByteBuffer()); + return ChannelBuffers.wrappedBuffer(buffer.toByteBuffer()); } } private class InternalDecoder extends SimpleChannelUpstreamHandler { - private int mOffset = 0, mLimit = 0; - - private byte[] mBuffer = null; + private com.alibaba.dubbo.remoting.buffer.ChannelBuffer buffer = + com.alibaba.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER; @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throws Exception { @@ -107,75 +105,56 @@ public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throw return; } - int off, limit; - byte[] buf = mBuffer; - if (buf == null) { - buf = new byte[bufferSize]; - off = limit = 0; + com.alibaba.dubbo.remoting.buffer.ChannelBuffer message; + if (buffer.readable()) { + if (buffer instanceof DynamicChannelBuffer) { + buffer.writeBytes(input.toByteBuffer()); + message = buffer; + } else { + int size = buffer.readableBytes() + input.readableBytes(); + message = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer( + size > bufferSize ? size : bufferSize); + message.writeBytes(buffer, buffer.readableBytes()); + message.writeBytes(input.toByteBuffer()); + } } else { - off = mOffset; - limit = mLimit; + message = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.wrappedBuffer( + input.toByteBuffer()); } NettyChannel channel = NettyChannel.getOrAddChannel(ctx.getChannel(), url, handler); - boolean remaining = true; Object msg; - UnsafeByteArrayInputStream bis; + int saveReaderIndex; + try { + // decode object. do { - // read data into buffer. - int read = Math.min(readable, buf.length - limit); - input.readBytes(buf, limit, read); - limit += read; - readable -= read; - bis = new UnsafeByteArrayInputStream(buf, off, limit - off); // 涓嶉渶瑕佸叧闂 - // decode object. - do { - try { - msg = codec.decode(channel, bis); - } catch (IOException e) { - remaining = false; - throw e; + saveReaderIndex = message.readerIndex(); + try { + msg = codec.decode(channel, message); + } catch (IOException e) { + buffer = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER; + throw e; + } + if (msg == ChannelCodec.DecodeResult.NEED_MORE_INPUT) { + message.readerIndex(saveReaderIndex); + break; + } else { + if (saveReaderIndex == message.readerIndex()) { + buffer = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER; + throw new IOException("Decode without read data."); } - if (msg == Codec.NEED_MORE_INPUT) { - if (off == 0) { - if (readable > 0) { - buf = Bytes.copyOf(buf, buf.length << 1); - } - } else { - int len = limit - off; - System.arraycopy(buf, off, buf, 0, len); // adjust buffer. - off = 0; - limit = len; - } - break; - } else { - int pos = bis.position(); - if (off == pos) { - remaining = false; - throw new IOException("Decode without read data."); - } - if (msg != null) { - Channels.fireMessageReceived(ctx, msg, event.getRemoteAddress()); - } - off = pos; + if (msg != null) { + Channels.fireMessageReceived(ctx, msg, event.getRemoteAddress()); } - } while (bis.available() > 0); - } while (readable > 0); - } finally { - if (remaining) { - int len = limit - off; - if (len < buf.length / 2) { - System.arraycopy(buf, off, buf, 0, len); - off = 0; - limit = len; } - mBuffer = buf; - mOffset = off; - mLimit = limit; + } while (message.readable()); + } finally { + if (message.readable()) { + message.discardReadBytes(); + buffer = message; } else { - mBuffer = null; - mOffset = mLimit = 0; + buffer = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER; } NettyChannel.removeChannelIfDisconnected(ctx.getChannel()); } diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java index 6a003d3c1c62..881a14da742e 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -31,7 +31,7 @@ import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.ChannelCodec; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.codec.ExchangeCodec; @@ -48,7 +48,7 @@ * @author qianlei * @author chao.liuc */ -public class DubboCodec extends ExchangeCodec implements Codec { +public class DubboCodec extends ExchangeCodec implements ChannelCodec { private static final Logger log = LoggerFactory.getLogger(DubboCodec.class); diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java index e8ace97b7e52..4c79344071f3 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java @@ -22,9 +22,9 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; -import com.alibaba.dubbo.remoting.exchange.support.MultiMessage; import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.support.MultiMessage; @@ -34,31 +34,30 @@ /** * @author kimi */ -public final class DubboCountCodec implements Codec { +public final class DubboCountCodec implements ChannelCodec { private DubboCodec codec = new DubboCodec(); - public void encode(Channel channel, OutputStream output, Object msg) throws IOException { - codec.encode(channel, output, msg); + public void encode(Channel channel, ChannelBuffer buffer, Object msg) throws IOException { + codec.encode(channel, buffer, msg); } - public Object decode(Channel channel, InputStream input) throws IOException { - UnsafeByteArrayInputStream bis = (UnsafeByteArrayInputStream)input; - int save = bis.position(); + public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { + int save = buffer.readerIndex(); MultiMessage result = MultiMessage.create(); do { - Object obj = codec.decode(channel, bis); - if (NEED_MORE_INPUT == obj) { - bis.position(save); + Object obj = codec.decode(channel, buffer); + if (ChannelCodec.DecodeResult.NEED_MORE_INPUT == obj) { + buffer.readerIndex(save); break; } else { result.addMessage(obj); - logMessageLength(obj, bis.position() - save); - save = bis.position(); + logMessageLength(obj, buffer.readerIndex() - save); + save = buffer.readerIndex(); } } while (true); if (result.isEmpty()) { - return NEED_MORE_INPUT; + return ChannelCodec.DecodeResult.NEED_MORE_INPUT; } if (result.size() == 1) { return result.get(0); diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec b/dubbo-rpc/dubbo-rpc-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec similarity index 100% rename from dubbo-rpc/dubbo-rpc-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec rename to dubbo-rpc/dubbo-rpc-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java index a7ef95a7ced7..9951e31a06d7 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java @@ -14,17 +14,16 @@ package com.alibaba.dubbo.rpc.protocol.thrift; -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.common.utils.ClassHelper; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.Codec; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.RpcResult; -import com.alibaba.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; + import org.apache.commons.lang.StringUtils; import org.apache.thrift.TApplicationException; import org.apache.thrift.TBase; @@ -37,17 +36,19 @@ import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TIOStreamTransport; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.utils.ClassHelper; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBufferInputStream; +import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.RpcInvocation; +import com.alibaba.dubbo.rpc.RpcResult; +import com.alibaba.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; /** * Thrift framed protocol codec. @@ -70,7 +71,7 @@ * * @author gang.lvg */ -public class ThriftCodec implements Codec { +public class ThriftCodec implements ChannelCodec { private static final AtomicInteger THRIFT_SEQ_ID = new AtomicInteger( 0 ); @@ -94,14 +95,14 @@ public class ThriftCodec implements Codec { public static final short MAGIC = (short) 0xdabc; - public void encode( Channel channel, OutputStream output, Object message ) + public void encode( Channel channel, ChannelBuffer buffer, Object message ) throws IOException { if ( message instanceof Request ) { - encodeRequest( channel, output, ( Request ) message ); + encodeRequest( channel, buffer, ( Request ) message ); } else if ( message instanceof Response ) { - encodeResponse( channel, output, ( Response ) message ); + encodeResponse( channel, buffer, ( Response ) message ); } else { throw new UnsupportedOperationException( new StringBuilder( 32 ) @@ -114,17 +115,17 @@ else if ( message instanceof Response ) { } - public Object decode( Channel channel, InputStream input ) throws IOException { + public Object decode( Channel channel, ChannelBuffer buffer ) throws IOException { - int available = input.available(); + int available = buffer.readableBytes(); if ( available < MESSAGE_SHORTEST_LENGTH ) { - return Codec.NEED_MORE_INPUT; + return DecodeResult.NEED_MORE_INPUT; } else { - TIOStreamTransport transport = new TIOStreamTransport( input ); + TIOStreamTransport transport = new TIOStreamTransport( new ChannelBufferInputStream(buffer)); TBinaryProtocol protocol = new TBinaryProtocol( transport ); @@ -150,7 +151,7 @@ public Object decode( Channel channel, InputStream input ) throws IOException { .toString() ); } - if ( available < messageLength ) { return NEED_MORE_INPUT; } + if ( available < messageLength ) { return DecodeResult.NEED_MORE_INPUT; } return decode( protocol ); @@ -390,7 +391,7 @@ private Object decode( TProtocol protocol ) } - private void encodeRequest( Channel channel, OutputStream output, Request request ) + private void encodeRequest( Channel channel, ChannelBuffer buffer, Request request ) throws IOException { RpcInvocation inv = ( RpcInvocation ) request.getData(); @@ -524,13 +525,12 @@ private void encodeRequest( Channel channel, OutputStream output, Request reques throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); } - output.write( bytes ); - bos.writeTo( output ); - output.flush(); + buffer.writeBytes(bytes); + buffer.writeBytes(bos.toByteArray()); } - private void encodeResponse( Channel channel, OutputStream output, Response response ) + private void encodeResponse( Channel channel, ChannelBuffer buffer, Response response ) throws IOException { RpcResult result = ( RpcResult ) response.getResult(); @@ -687,9 +687,8 @@ private void encodeResponse( Channel channel, OutputStream output, Response resp throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); } - output.write( bytes ); - bos.writeTo( output ); - output.flush(); + buffer.writeBytes(bytes); + buffer.writeBytes(bos.toByteArray()); } diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java index e2ed97e39f51..f0c11564d389 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java @@ -1,8 +1,6 @@ package com.alibaba.dubbo.rpc.protocol.thrift; import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import java.util.concurrent.atomic.AtomicInteger; import org.apache.thrift.TException; @@ -15,7 +13,9 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBufferOutputStream; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.rpc.Invocation; @@ -23,26 +23,26 @@ /** * @author kimi */ -public class ThriftNativeCodec implements Codec { +public class ThriftNativeCodec implements ChannelCodec { private final AtomicInteger thriftSeq = new AtomicInteger(0); - public void encode(Channel channel, OutputStream output, Object message) + public void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException { if (message instanceof Request) { - encodeRequest(channel, output, (Request)message); + encodeRequest(channel, buffer, (Request)message); } else if (message instanceof Response) { - encodeResponse(channel, output, (Response)message); + encodeResponse(channel, buffer, (Response)message); } else { throw new IOException("Unsupported message type " + message.getClass().getName()); } } - protected void encodeRequest(Channel channel, OutputStream output, Request request) + protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request request) throws IOException { Invocation invocation = (Invocation) request.getData(); - TProtocol protocol = newProtocol(channel.getUrl(), output); + TProtocol protocol = newProtocol(channel.getUrl(), buffer); try { protocol.writeMessageBegin(new TMessage( invocation.getMethodName(), TMessageType.CALL, @@ -58,20 +58,20 @@ protected void encodeRequest(Channel channel, OutputStream output, Request reque } - protected void encodeResponse(Channel channel, OutputStream output, Response response) + protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response response) throws IOException { } - public Object decode(Channel channel, InputStream input) throws IOException { + public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { return null; } - protected static TProtocol newProtocol(URL url, OutputStream output) throws IOException { + protected static TProtocol newProtocol(URL url, ChannelBuffer buffer) throws IOException { String protocol = url.getParameter(ThriftConstants.THRIFT_PROTOCOL_KEY, ThriftConstants.DEFAULT_PROTOCOL); if (ThriftConstants.BINARY_THRIFT_PROTOCOL.equals(protocol)) { - return new TBinaryProtocol(new TIOStreamTransport(output)); + return new TBinaryProtocol(new TIOStreamTransport(new ChannelBufferOutputStream(buffer))); } throw new IOException("Unsupported protocol type " + protocol); } diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec b/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec similarity index 100% rename from dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec rename to dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java index 4a1a08b7417b..4b0ecdaa0d1a 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java @@ -13,9 +13,23 @@ */ package com.alibaba.dubbo.rpc.protocol.thrift; +import java.io.ByteArrayInputStream; + +import org.apache.thrift.TApplicationException; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TMessage; +import org.apache.thrift.protocol.TMessageType; +import org.apache.thrift.transport.TFramedTransport; +import org.apache.thrift.transport.TIOStreamTransport; +import org.apache.thrift.transport.TTransport; +import org.junit.Assert; +import org.junit.Test; + import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; @@ -24,18 +38,6 @@ import com.alibaba.dubbo.rpc.RpcResult; import com.alibaba.dubbo.rpc.gen.thrift.Demo; import com.alibaba.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; -import org.apache.thrift.TApplicationException; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TIOStreamTransport; -import org.apache.thrift.transport.TTransport; -import org.junit.Assert; -import org.junit.Test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; /** * @author gang.lvg @@ -50,11 +52,12 @@ public void testEncodeRequest() throws Exception { Request request = createRequest(); - ByteArrayOutputStream output = new ByteArrayOutputStream( 1024 ); + ChannelBuffer output = ChannelBuffers.dynamicBuffer(1024); codec.encode( channel, output, request ); - byte[] bytes = output.toByteArray(); + byte[] bytes = new byte[output.readableBytes()]; + output.readBytes(bytes); ByteArrayInputStream bis = new ByteArrayInputStream( bytes ); @@ -161,7 +164,7 @@ public void testDecodeReplyResponse() throws Exception { byte[] buf = new byte[ 4 + bos.size()]; System.arraycopy( bos.toByteArray(), 0, buf, 4, bos.size() ); - ByteArrayInputStream bis = new ByteArrayInputStream( buf ); + ChannelBuffer bis = ChannelBuffers.wrappedBuffer(buf); Object obj = codec.decode( ( Channel ) null, bis ); @@ -231,7 +234,7 @@ public void testDecodeExceptionResponse() throws Exception { } // prepare - ByteArrayInputStream bis = new ByteArrayInputStream( encodeFrame( bos.toByteArray() ) ); + ChannelBuffer bis = ChannelBuffers.wrappedBuffer(encodeFrame(bos.toByteArray())); Object obj = codec.decode( ( Channel ) null, bis ); @@ -266,15 +269,15 @@ public void testEncodeReplyResponse() throws Exception { Response response = new Response(); response.setResult( rpcResult ); response.setId( request.getId() ); - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 1024 ); + ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024); ThriftCodec.RequestData rd = ThriftCodec.RequestData.create( ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString" ); ThriftCodec.cachedRequest.putIfAbsent( request.getId(), rd ); codec.encode( channel, bos, response ); - byte[] buf = new byte[bos.size() - 4]; - System.arraycopy( bos.toByteArray(), 4, buf, 0, bos.size() - 4 ); + byte[] buf = new byte[bos.writerIndex() - 4]; + System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 ); ByteArrayInputStream bis = new ByteArrayInputStream( buf ); @@ -286,7 +289,7 @@ public void testEncodeReplyResponse() throws Exception { TBinaryProtocol protocol = new TBinaryProtocol( transport ); Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() ); - Assert.assertEquals( protocol.readI32() + 4, bos.toByteArray().length ); + Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() ); int headerLength = protocol.readI16(); Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() ); @@ -306,7 +309,7 @@ public void testEncodeReplyResponse() throws Exception { result.read( protocol ); protocol.readMessageEnd(); - Assert.assertEquals( rpcResult.getResult(), result.getSuccess() ); + Assert.assertEquals( rpcResult.getValue(), result.getSuccess() ); } @Test @@ -325,15 +328,15 @@ public void testEncodeExceptionResponse() throws Exception { Response response = new Response(); response.setResult( rpcResult ); response.setId( request.getId() ); - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 1024 ); + ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024); ThriftCodec.RequestData rd = ThriftCodec.RequestData.create( ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString" ); ThriftCodec.cachedRequest.put( request.getId(), rd ); codec.encode( channel, bos, response ); - byte[] buf = new byte[bos.size() - 4]; - System.arraycopy( bos.toByteArray(), 4, buf, 0, bos.size() - 4 ); + byte[] buf = new byte[bos.writerIndex() - 4]; + System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 ); ByteArrayInputStream bis = new ByteArrayInputStream( buf); if ( bis.markSupported() ) { @@ -344,7 +347,7 @@ public void testEncodeExceptionResponse() throws Exception { TBinaryProtocol protocol = new TBinaryProtocol( transport ); Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() ); - Assert.assertEquals( protocol.readI32() + 4, bos.toByteArray().length ); + Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() ); int headerLength = protocol.readI16(); Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() ); @@ -410,8 +413,8 @@ public void testDecodeRequest() throws Exception { bos.setWriteIndex( oldIndex ); } - Object obj = codec.decode( ( Channel ) null, new ByteArrayInputStream( - encodeFrame( bos.toByteArray() ) ) ); + Object obj = codec.decode( ( Channel ) null, ChannelBuffers.wrappedBuffer( + encodeFrame(bos.toByteArray())) ); Assert.assertTrue( obj instanceof Request ); From 955a1a77fee69e66538cd10873c416704d8d0d9a Mon Sep 17 00:00:00 2001 From: kimi Date: Mon, 15 Oct 2012 18:25:18 +0800 Subject: [PATCH 071/200] =?UTF-8?q?DUBBO-166=20=E5=A2=9E=E5=BC=BA=20codec?= =?UTF-8?q?=20=E9=81=BF=E5=85=8D=E6=95=B0=E6=8D=AE=20copy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/remoting/buffer/ChannelBuffers.java | 6 + .../remoting/transport/AbstractEndpoint.java | 3 +- .../transport/codec/ChannelCodecAdapter.java | 2 + .../buffer/AbstractChannelBufferTest.java | 862 ++++++++++++++++++ .../ByteBufferBackedChannelBufferTest.java | 22 + .../buffer/ChannelBufferStreamTest.java | 91 ++ .../buffer/DirectChannelBufferTest.java | 23 + .../buffer/DynamicChannelBufferTest.java | 47 + .../buffer/HeapChannelBufferTest.java | 23 + 9 files changed, 1077 insertions(+), 2 deletions(-) create mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/AbstractChannelBufferTest.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/ByteBufferBackedChannelBufferTest.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferStreamTest.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/DirectChannelBufferTest.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/DynamicChannelBufferTest.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBufferTest.java diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffers.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffers.java index 506b06f3e918..23e906e7d097 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffers.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/buffer/ChannelBuffers.java @@ -25,6 +25,12 @@ public final class ChannelBuffers { public static final ChannelBuffer EMPTY_BUFFER = new HeapChannelBuffer(0); + private ChannelBuffers() {} + + public static ChannelBuffer dynamicBuffer() { + return dynamicBuffer(256); + } + public static ChannelBuffer dynamicBuffer(int capacity) { return new DynamicChannelBuffer(capacity); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java index c7581e930fd8..3019c922e32a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java @@ -75,8 +75,7 @@ public void reset(URL url) { } try { if (url.hasParameter(Constants.CODEC_KEY)) { - String c = url.getParameter(Constants.CODEC_KEY); - this.codec = ExtensionLoader.getExtensionLoader(ChannelCodec.class).getExtension(c); + this.codec = getChannelCodec(url); } } catch (Throwable t) { logger.error(t.getMessage(), t); diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/ChannelCodecAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/ChannelCodecAdapter.java index bb2d02d692e1..ad15c5cb5990 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/ChannelCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/ChannelCodecAdapter.java @@ -20,6 +20,7 @@ import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; +import com.alibaba.dubbo.common.utils.Assert; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.Codec; import com.alibaba.dubbo.remoting.ChannelCodec; @@ -33,6 +34,7 @@ public class ChannelCodecAdapter implements ChannelCodec { private Codec codec; public ChannelCodecAdapter(Codec codec) { + Assert.notNull(codec, "codec == null"); this.codec = codec; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/AbstractChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/AbstractChannelBufferTest.java new file mode 100644 index 000000000000..e276ddd98c0a --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/AbstractChannelBufferTest.java @@ -0,0 +1,862 @@ +package com.alibaba.dubbo.remoting.buffer; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.Random; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static com.alibaba.dubbo.remoting.buffer.ChannelBuffers.directBuffer; +import static com.alibaba.dubbo.remoting.buffer.ChannelBuffers.wrappedBuffer; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + + +/** + * @author kimi + */ +public abstract class AbstractChannelBufferTest { + + private static final int CAPACITY = 4096; // Must be even + private static final int BLOCK_SIZE = 128; + + private long seed; + private Random random; + private ChannelBuffer buffer; + + protected abstract ChannelBuffer newBuffer(int capacity); + protected abstract ChannelBuffer[] components(); + + protected boolean discardReadBytesDoesNotMoveWritableBytes() { + return true; + } + + + @Before + public void init() { + buffer = newBuffer(CAPACITY); + seed = System.currentTimeMillis(); + random = new Random(seed); + } + + @After + public void dispose() { + buffer = null; + } + + @Test + public void initialState() { + assertEquals(CAPACITY, buffer.capacity()); + assertEquals(0, buffer.readerIndex()); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void readerIndexBoundaryCheck1() { + try { + buffer.writerIndex(0); + } catch (IndexOutOfBoundsException e) { + fail(); + } + buffer.readerIndex(-1); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void readerIndexBoundaryCheck2() { + try { + buffer.writerIndex(buffer.capacity()); + } catch (IndexOutOfBoundsException e) { + fail(); + } + buffer.readerIndex(buffer.capacity() + 1); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void readerIndexBoundaryCheck3() { + try { + buffer.writerIndex(CAPACITY / 2); + } catch (IndexOutOfBoundsException e) { + fail(); + } + buffer.readerIndex(CAPACITY * 3 / 2); + } + + @Test + public void readerIndexBoundaryCheck4() { + buffer.writerIndex(0); + buffer.readerIndex(0); + buffer.writerIndex(buffer.capacity()); + buffer.readerIndex(buffer.capacity()); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void writerIndexBoundaryCheck1() { + buffer.writerIndex(-1); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void writerIndexBoundaryCheck2() { + try { + buffer.writerIndex(CAPACITY); + buffer.readerIndex(CAPACITY); + } catch (IndexOutOfBoundsException e) { + fail(); + } + buffer.writerIndex(buffer.capacity() + 1); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void writerIndexBoundaryCheck3() { + try { + buffer.writerIndex(CAPACITY); + buffer.readerIndex(CAPACITY / 2); + } catch (IndexOutOfBoundsException e) { + fail(); + } + buffer.writerIndex(CAPACITY / 4); + } + + @Test + public void writerIndexBoundaryCheck4() { + buffer.writerIndex(0); + buffer.readerIndex(0); + buffer.writerIndex(CAPACITY); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void getByteBoundaryCheck1() { + buffer.getByte(-1); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void getByteBoundaryCheck2() { + buffer.getByte(buffer.capacity()); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void getByteArrayBoundaryCheck1() { + buffer.getBytes(-1, new byte[0]); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void getByteArrayBoundaryCheck2() { + buffer.getBytes(-1, new byte[0], 0, 0); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void getByteBufferBoundaryCheck() { + buffer.getBytes(-1, ByteBuffer.allocate(0)); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void copyBoundaryCheck1() { + buffer.copy(-1, 0); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void copyBoundaryCheck2() { + buffer.copy(0, buffer.capacity() + 1); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void copyBoundaryCheck3() { + buffer.copy(buffer.capacity() + 1, 0); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void copyBoundaryCheck4() { + buffer.copy(buffer.capacity(), 1); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void setIndexBoundaryCheck1() { + buffer.setIndex(-1, CAPACITY); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void setIndexBoundaryCheck2() { + buffer.setIndex(CAPACITY / 2, CAPACITY / 4); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void setIndexBoundaryCheck3() { + buffer.setIndex(0, CAPACITY + 1); + } + + @Test + public void getByteBufferState() { + ByteBuffer dst = ByteBuffer.allocate(4); + dst.position(1); + dst.limit(3); + + buffer.setByte(0, (byte) 1); + buffer.setByte(1, (byte) 2); + buffer.setByte(2, (byte) 3); + buffer.setByte(3, (byte) 4); + buffer.getBytes(1, dst); + + assertEquals(3, dst.position()); + assertEquals(3, dst.limit()); + + dst.clear(); + assertEquals(0, dst.get(0)); + assertEquals(2, dst.get(1)); + assertEquals(3, dst.get(2)); + assertEquals(0, dst.get(3)); + } + + @Test(expected=IndexOutOfBoundsException.class) + public void getDirectByteBufferBoundaryCheck() { + buffer.getBytes(-1, ByteBuffer.allocateDirect(0)); + } + + @Test + public void getDirectByteBufferState() { + ByteBuffer dst = ByteBuffer.allocateDirect(4); + dst.position(1); + dst.limit(3); + + buffer.setByte(0, (byte) 1); + buffer.setByte(1, (byte) 2); + buffer.setByte(2, (byte) 3); + buffer.setByte(3, (byte) 4); + buffer.getBytes(1, dst); + + assertEquals(3, dst.position()); + assertEquals(3, dst.limit()); + + dst.clear(); + assertEquals(0, dst.get(0)); + assertEquals(2, dst.get(1)); + assertEquals(3, dst.get(2)); + assertEquals(0, dst.get(3)); + } + + @Test + public void testRandomByteAccess() { + for (int i = 0; i < buffer.capacity(); i ++) { + byte value = (byte) random.nextInt(); + buffer.setByte(i, value); + } + + random.setSeed(seed); + for (int i = 0; i < buffer.capacity(); i ++) { + byte value = (byte) random.nextInt(); + assertEquals(value, buffer.getByte(i)); + } + } + + @Test + public void testSequentialByteAccess() { + buffer.writerIndex(0); + for (int i = 0; i < buffer.capacity(); i ++) { + byte value = (byte) random.nextInt(); + assertEquals(i, buffer.writerIndex()); + assertTrue(buffer.writable()); + buffer.writeByte(value); + } + + assertEquals(0, buffer.readerIndex()); + assertEquals(buffer.capacity(), buffer.writerIndex()); + assertFalse(buffer.writable()); + + random.setSeed(seed); + for (int i = 0; i < buffer.capacity(); i ++) { + byte value = (byte) random.nextInt(); + assertEquals(i, buffer.readerIndex()); + assertTrue(buffer.readable()); + assertEquals(value, buffer.readByte()); + } + + assertEquals(buffer.capacity(), buffer.readerIndex()); + assertEquals(buffer.capacity(), buffer.writerIndex()); + assertFalse(buffer.readable()); + assertFalse(buffer.writable()); + } + + @Test + public void testByteArrayTransfer() { + byte[] value = new byte[BLOCK_SIZE * 2]; + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(value); + buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); + } + + random.setSeed(seed); + byte[] expectedValue = new byte[BLOCK_SIZE * 2]; + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValue); + int valueOffset = random.nextInt(BLOCK_SIZE); + buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue[j], value[j]); + } + } + } + + @Test + public void testRandomByteArrayTransfer1() { + byte[] value= new byte[BLOCK_SIZE]; + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(value); + buffer.setBytes(i, value); + } + + random.setSeed(seed); + byte[] expectedValueContent = new byte[BLOCK_SIZE]; + ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValueContent); + buffer.getBytes(i, value); + for (int j = 0; j < BLOCK_SIZE; j ++) { + assertEquals(expectedValue.getByte(j), value[j]); + } + } + } + + @Test + public void testRandomByteArrayTransfer2() { + byte[] value= new byte[BLOCK_SIZE * 2]; + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(value); + buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); + } + + random.setSeed(seed); + byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValueContent); + int valueOffset = random.nextInt(BLOCK_SIZE); + buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue.getByte(j), value[j]); + } + } + } + + @Test + public void testRandomHeapBufferTransfer1() { + byte[] valueContent = new byte[BLOCK_SIZE]; + ChannelBuffer value = wrappedBuffer(valueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(valueContent); + value.setIndex(0, BLOCK_SIZE); + buffer.setBytes(i, value); + assertEquals(BLOCK_SIZE, value.readerIndex()); + assertEquals(BLOCK_SIZE, value.writerIndex()); + } + + random.setSeed(seed); + byte[] expectedValueContent = new byte[BLOCK_SIZE]; + ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValueContent); + value.clear(); + buffer.getBytes(i, value); + assertEquals(0, value.readerIndex()); + assertEquals(BLOCK_SIZE, value.writerIndex()); + for (int j = 0; j < BLOCK_SIZE; j ++) { + assertEquals(expectedValue.getByte(j), value.getByte(j)); + } + } + } + + @Test + public void testRandomHeapBufferTransfer2() { + byte[] valueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer value = wrappedBuffer(valueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(valueContent); + buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); + } + + random.setSeed(seed); + byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValueContent); + int valueOffset = random.nextInt(BLOCK_SIZE); + buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue.getByte(j), value.getByte(j)); + } + } + } + + @Test + public void testRandomDirectBufferTransfer() { + byte[] tmp = new byte[BLOCK_SIZE * 2]; + ChannelBuffer value = directBuffer(BLOCK_SIZE * 2); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(tmp); + value.setBytes(0, tmp, 0, value.capacity()); + buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); + } + + random.setSeed(seed); + ChannelBuffer expectedValue = directBuffer(BLOCK_SIZE * 2); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(tmp); + expectedValue.setBytes(0, tmp, 0, expectedValue.capacity()); + int valueOffset = random.nextInt(BLOCK_SIZE); + buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue.getByte(j), value.getByte(j)); + } + } + } + + @Test + public void testRandomByteBufferTransfer() { + ByteBuffer value = ByteBuffer.allocate(BLOCK_SIZE * 2); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(value.array()); + value.clear().position(random.nextInt(BLOCK_SIZE)); + value.limit(value.position() + BLOCK_SIZE); + buffer.setBytes(i, value); + } + + random.setSeed(seed); + ByteBuffer expectedValue = ByteBuffer.allocate(BLOCK_SIZE * 2); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValue.array()); + int valueOffset = random.nextInt(BLOCK_SIZE); + value.clear().position(valueOffset).limit(valueOffset + BLOCK_SIZE); + buffer.getBytes(i, value); + assertEquals(valueOffset + BLOCK_SIZE, value.position()); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue.get(j), value.get(j)); + } + } + } + + @Test + public void testSequentialByteArrayTransfer1() { + byte[] value= new byte[BLOCK_SIZE]; + buffer.writerIndex(0); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(value); + assertEquals(0, buffer.readerIndex()); + assertEquals(i, buffer.writerIndex()); + buffer.writeBytes(value); + } + + random.setSeed(seed); + byte[] expectedValue = new byte[BLOCK_SIZE]; + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValue); + assertEquals(i, buffer.readerIndex()); + assertEquals(CAPACITY, buffer.writerIndex()); + buffer.readBytes(value); + for (int j = 0; j < BLOCK_SIZE; j ++) { + assertEquals(expectedValue[j], value[j]); + } + } + } + + @Test + public void testSequentialByteArrayTransfer2() { + byte[] value = new byte[BLOCK_SIZE * 2]; + buffer.writerIndex(0); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(value); + assertEquals(0, buffer.readerIndex()); + assertEquals(i, buffer.writerIndex()); + int readerIndex = random.nextInt(BLOCK_SIZE); + buffer.writeBytes(value, readerIndex, BLOCK_SIZE); + } + + random.setSeed(seed); + byte[] expectedValue= new byte[BLOCK_SIZE * 2]; + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValue); + int valueOffset = random.nextInt(BLOCK_SIZE); + assertEquals(i, buffer.readerIndex()); + assertEquals(CAPACITY, buffer.writerIndex()); + buffer.readBytes(value, valueOffset, BLOCK_SIZE); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue[j], value[j]); + } + } + } + + @Test + public void testSequentialHeapBufferTransfer1() { + byte[] valueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer value = wrappedBuffer(valueContent); + buffer.writerIndex(0); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(valueContent); + assertEquals(0, buffer.readerIndex()); + assertEquals(i, buffer.writerIndex()); + buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); + assertEquals(0, value.readerIndex()); + assertEquals(valueContent.length, value.writerIndex()); + } + + random.setSeed(seed); + byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValueContent); + int valueOffset = random.nextInt(BLOCK_SIZE); + assertEquals(i, buffer.readerIndex()); + assertEquals(CAPACITY, buffer.writerIndex()); + buffer.readBytes(value, valueOffset, BLOCK_SIZE); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue.getByte(j), value.getByte(j)); + } + assertEquals(0, value.readerIndex()); + assertEquals(valueContent.length, value.writerIndex()); + } + } + + @Test + public void testSequentialHeapBufferTransfer2() { + byte[] valueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer value = wrappedBuffer(valueContent); + buffer.writerIndex(0); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(valueContent); + assertEquals(0, buffer.readerIndex()); + assertEquals(i, buffer.writerIndex()); + int readerIndex = random.nextInt(BLOCK_SIZE); + value.readerIndex(readerIndex); + value.writerIndex(readerIndex + BLOCK_SIZE); + buffer.writeBytes(value); + assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex()); + assertEquals(value.writerIndex(), value.readerIndex()); + } + + random.setSeed(seed); + byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValueContent); + int valueOffset = random.nextInt(BLOCK_SIZE); + assertEquals(i, buffer.readerIndex()); + assertEquals(CAPACITY, buffer.writerIndex()); + value.readerIndex(valueOffset); + value.writerIndex(valueOffset); + buffer.readBytes(value, BLOCK_SIZE); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue.getByte(j), value.getByte(j)); + } + assertEquals(valueOffset, value.readerIndex()); + assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex()); + } + } + + @Test + public void testSequentialDirectBufferTransfer1() { + byte[] valueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer value = directBuffer(BLOCK_SIZE * 2); + buffer.writerIndex(0); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(valueContent); + value.setBytes(0, valueContent); + assertEquals(0, buffer.readerIndex()); + assertEquals(i, buffer.writerIndex()); + buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); + assertEquals(0, value.readerIndex()); + assertEquals(0, value.writerIndex()); + } + + random.setSeed(seed); + byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValueContent); + int valueOffset = random.nextInt(BLOCK_SIZE); + value.setBytes(0, valueContent); + assertEquals(i, buffer.readerIndex()); + assertEquals(CAPACITY, buffer.writerIndex()); + buffer.readBytes(value, valueOffset, BLOCK_SIZE); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue.getByte(j), value.getByte(j)); + } + assertEquals(0, value.readerIndex()); + assertEquals(0, value.writerIndex()); + } + } + + @Test + public void testSequentialDirectBufferTransfer2() { + byte[] valueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer value = directBuffer(BLOCK_SIZE * 2); + buffer.writerIndex(0); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(valueContent); + value.setBytes(0, valueContent); + assertEquals(0, buffer.readerIndex()); + assertEquals(i, buffer.writerIndex()); + int readerIndex = random.nextInt(BLOCK_SIZE); + value.readerIndex(0); + value.writerIndex(readerIndex + BLOCK_SIZE); + value.readerIndex(readerIndex); + buffer.writeBytes(value); + assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex()); + assertEquals(value.writerIndex(), value.readerIndex()); + } + + random.setSeed(seed); + byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValueContent); + value.setBytes(0, valueContent); + int valueOffset = random.nextInt(BLOCK_SIZE); + assertEquals(i, buffer.readerIndex()); + assertEquals(CAPACITY, buffer.writerIndex()); + value.readerIndex(valueOffset); + value.writerIndex(valueOffset); + buffer.readBytes(value, BLOCK_SIZE); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue.getByte(j), value.getByte(j)); + } + assertEquals(valueOffset, value.readerIndex()); + assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex()); + } + } + + @Test + public void testSequentialByteBufferBackedHeapBufferTransfer1() { + byte[] valueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer value = wrappedBuffer(ByteBuffer.allocate(BLOCK_SIZE * 2)); + value.writerIndex(0); + buffer.writerIndex(0); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(valueContent); + value.setBytes(0, valueContent); + assertEquals(0, buffer.readerIndex()); + assertEquals(i, buffer.writerIndex()); + buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); + assertEquals(0, value.readerIndex()); + assertEquals(0, value.writerIndex()); + } + + random.setSeed(seed); + byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValueContent); + int valueOffset = random.nextInt(BLOCK_SIZE); + value.setBytes(0, valueContent); + assertEquals(i, buffer.readerIndex()); + assertEquals(CAPACITY, buffer.writerIndex()); + buffer.readBytes(value, valueOffset, BLOCK_SIZE); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue.getByte(j), value.getByte(j)); + } + assertEquals(0, value.readerIndex()); + assertEquals(0, value.writerIndex()); + } + } + + @Test + public void testSequentialByteBufferBackedHeapBufferTransfer2() { + byte[] valueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer value = wrappedBuffer(ByteBuffer.allocate(BLOCK_SIZE * 2)); + value.writerIndex(0); + buffer.writerIndex(0); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(valueContent); + value.setBytes(0, valueContent); + assertEquals(0, buffer.readerIndex()); + assertEquals(i, buffer.writerIndex()); + int readerIndex = random.nextInt(BLOCK_SIZE); + value.readerIndex(0); + value.writerIndex(readerIndex + BLOCK_SIZE); + value.readerIndex(readerIndex); + buffer.writeBytes(value); + assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex()); + assertEquals(value.writerIndex(), value.readerIndex()); + } + + random.setSeed(seed); + byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; + ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValueContent); + value.setBytes(0, valueContent); + int valueOffset = random.nextInt(BLOCK_SIZE); + assertEquals(i, buffer.readerIndex()); + assertEquals(CAPACITY, buffer.writerIndex()); + value.readerIndex(valueOffset); + value.writerIndex(valueOffset); + buffer.readBytes(value, BLOCK_SIZE); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue.getByte(j), value.getByte(j)); + } + assertEquals(valueOffset, value.readerIndex()); + assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex()); + } + } + + @Test + public void testSequentialByteBufferTransfer() { + buffer.writerIndex(0); + ByteBuffer value = ByteBuffer.allocate(BLOCK_SIZE * 2); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(value.array()); + value.clear().position(random.nextInt(BLOCK_SIZE)); + value.limit(value.position() + BLOCK_SIZE); + buffer.writeBytes(value); + } + + random.setSeed(seed); + ByteBuffer expectedValue = ByteBuffer.allocate(BLOCK_SIZE * 2); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValue.array()); + int valueOffset = random.nextInt(BLOCK_SIZE); + value.clear().position(valueOffset).limit(valueOffset + BLOCK_SIZE); + buffer.readBytes(value); + assertEquals(valueOffset + BLOCK_SIZE, value.position()); + for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { + assertEquals(expectedValue.get(j), value.get(j)); + } + } + } + + @Test + public void testSequentialCopiedBufferTransfer1() { + buffer.writerIndex(0); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + byte[] value = new byte[BLOCK_SIZE]; + random.nextBytes(value); + assertEquals(0, buffer.readerIndex()); + assertEquals(i, buffer.writerIndex()); + buffer.writeBytes(value); + } + + random.setSeed(seed); + byte[] expectedValue = new byte[BLOCK_SIZE]; + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + random.nextBytes(expectedValue); + assertEquals(i, buffer.readerIndex()); + assertEquals(CAPACITY, buffer.writerIndex()); + ChannelBuffer actualValue = buffer.readBytes(BLOCK_SIZE); + assertEquals(wrappedBuffer(expectedValue), actualValue); + + // Make sure if it is a copied buffer. + actualValue.setByte(0, (byte) (actualValue.getByte(0) + 1)); + assertFalse(buffer.getByte(i) == actualValue.getByte(0)); + } + } + + @Test + public void testStreamTransfer1() throws Exception { + byte[] expected = new byte[buffer.capacity()]; + random.nextBytes(expected); + + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + ByteArrayInputStream in = new ByteArrayInputStream(expected, i, BLOCK_SIZE); + assertEquals(BLOCK_SIZE, buffer.setBytes(i, in, BLOCK_SIZE)); + assertEquals(-1, buffer.setBytes(i, in, 0)); + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + buffer.getBytes(i, out, BLOCK_SIZE); + } + + assertTrue(Arrays.equals(expected, out.toByteArray())); + } + + @Test + public void testStreamTransfer2() throws Exception { + byte[] expected = new byte[buffer.capacity()]; + random.nextBytes(expected); + buffer.clear(); + + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + ByteArrayInputStream in = new ByteArrayInputStream(expected, i, BLOCK_SIZE); + assertEquals(i, buffer.writerIndex()); + buffer.writeBytes(in, BLOCK_SIZE); + assertEquals(i + BLOCK_SIZE, buffer.writerIndex()); + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + assertEquals(i, buffer.readerIndex()); + buffer.readBytes(out, BLOCK_SIZE); + assertEquals(i + BLOCK_SIZE, buffer.readerIndex()); + } + + assertTrue(Arrays.equals(expected, out.toByteArray())); + } + + @Test + public void testCopy() { + for (int i = 0; i < buffer.capacity(); i ++) { + byte value = (byte) random.nextInt(); + buffer.setByte(i, value); + } + + final int readerIndex = CAPACITY / 3; + final int writerIndex = CAPACITY * 2 / 3; + buffer.setIndex(readerIndex, writerIndex); + + // Make sure all properties are copied. + ChannelBuffer copy = buffer.copy(); + assertEquals(0, copy.readerIndex()); + assertEquals(buffer.readableBytes(), copy.writerIndex()); + assertEquals(buffer.readableBytes(), copy.capacity()); + for (int i = 0; i < copy.capacity(); i ++) { + assertEquals(buffer.getByte(i + readerIndex), copy.getByte(i)); + } + + // Make sure the buffer content is independent from each other. + buffer.setByte(readerIndex, (byte) (buffer.getByte(readerIndex) + 1)); + assertTrue(buffer.getByte(readerIndex) != copy.getByte(0)); + copy.setByte(1, (byte) (copy.getByte(1) + 1)); + assertTrue(buffer.getByte(readerIndex + 1) != copy.getByte(1)); + } + + @Test + public void testToByteBuffer1() { + byte[] value = new byte[buffer.capacity()]; + random.nextBytes(value); + buffer.clear(); + buffer.writeBytes(value); + + assertEquals(ByteBuffer.wrap(value), buffer.toByteBuffer()); + } + + @Test + public void testToByteBuffer2() { + byte[] value = new byte[buffer.capacity()]; + random.nextBytes(value); + buffer.clear(); + buffer.writeBytes(value); + + for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { + assertEquals(ByteBuffer.wrap(value, i, BLOCK_SIZE), buffer.toByteBuffer(i, BLOCK_SIZE)); + } + } + + @Test + public void testSkipBytes1() { + buffer.setIndex(CAPACITY / 4, CAPACITY / 2); + + buffer.skipBytes(CAPACITY / 4); + assertEquals(CAPACITY / 4 * 2, buffer.readerIndex()); + + try { + buffer.skipBytes(CAPACITY / 4 + 1); + fail(); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + // Should remain unchanged. + assertEquals(CAPACITY / 4 * 2, buffer.readerIndex()); + } + +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/ByteBufferBackedChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/ByteBufferBackedChannelBufferTest.java new file mode 100644 index 000000000000..b8f6aa3ab989 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/ByteBufferBackedChannelBufferTest.java @@ -0,0 +1,22 @@ +package com.alibaba.dubbo.remoting.buffer; + +import java.nio.ByteBuffer; + +/** + * @author kimi + */ +public class ByteBufferBackedChannelBufferTest extends AbstractChannelBufferTest { + + private ChannelBuffer buffer; + + @Override + protected ChannelBuffer newBuffer(int capacity) { + buffer = new ByteBufferBackedChannelBuffer(ByteBuffer.allocate(capacity)); + return buffer; + } + + @Override + protected ChannelBuffer[] components() { + return new ChannelBuffer[]{buffer}; + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferStreamTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferStreamTest.java new file mode 100644 index 000000000000..c1f1532530c7 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/ChannelBufferStreamTest.java @@ -0,0 +1,91 @@ +package com.alibaba.dubbo.remoting.buffer; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * @author kimi + */ +public class ChannelBufferStreamTest { + + @Test + public void testAll() throws Exception { + ChannelBuffer buf = ChannelBuffers.dynamicBuffer(); + + try { + new ChannelBufferOutputStream(null); + fail(); + } catch (NullPointerException e) { + // Expected + } + + ChannelBufferOutputStream out = new ChannelBufferOutputStream(buf); + assertSame(buf, out.buffer()); + out.write(new byte[0]); + out.write(new byte[]{1, 2, 3, 4}); + out.write(new byte[]{1, 3, 3, 4}, 0, 0); + out.close(); + + try { + new ChannelBufferInputStream(null); + fail(); + } catch (NullPointerException e) { + // Expected + } + + try { + new ChannelBufferInputStream(null, 0); + fail(); + } catch (NullPointerException e) { + // Expected + } + + try { + new ChannelBufferInputStream(buf, -1); + } catch (IllegalArgumentException e) { + // Expected + } + + try { + new ChannelBufferInputStream(buf, buf.capacity() + 1); + } catch (IndexOutOfBoundsException e) { + // Expected + } + + ChannelBufferInputStream in = new ChannelBufferInputStream(buf); + + assertTrue(in.markSupported()); + in.mark(Integer.MAX_VALUE); + + assertEquals(buf.writerIndex(), in.skip(Long.MAX_VALUE)); + assertFalse(buf.readable()); + + in.reset(); + assertEquals(0, buf.readerIndex()); + + assertEquals(4, in.skip(4)); + assertEquals(4, buf.readerIndex()); + in.reset(); + + + byte[] tmp = new byte[13]; + in.read(tmp); + + assertEquals(1, tmp[0]); + assertEquals(2, tmp[1]); + assertEquals(3, tmp[2]); + assertEquals(4, tmp[3]); + + assertEquals(-1, in.read()); + assertEquals(-1, in.read(tmp)); + + in.close(); + + assertEquals(buf.readerIndex(), in.readBytes()); + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/DirectChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/DirectChannelBufferTest.java new file mode 100644 index 000000000000..590ff66c53d1 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/DirectChannelBufferTest.java @@ -0,0 +1,23 @@ +package com.alibaba.dubbo.remoting.buffer; + +import junit.framework.Assert; + +/** + * @author kimi + */ +public class DirectChannelBufferTest extends AbstractChannelBufferTest{ + + private ChannelBuffer buffer; + + @Override + protected ChannelBuffer newBuffer(int capacity) { + buffer = ChannelBuffers.directBuffer(capacity); + Assert.assertEquals(0, buffer.writerIndex()); + return buffer; + } + + @Override + protected ChannelBuffer[] components() { + return new ChannelBuffer[]{buffer}; + } +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/DynamicChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/DynamicChannelBufferTest.java new file mode 100644 index 000000000000..a02a1c291eb7 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/DynamicChannelBufferTest.java @@ -0,0 +1,47 @@ +package com.alibaba.dubbo.remoting.buffer; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** + * @author kimi + */ +public class DynamicChannelBufferTest extends AbstractChannelBufferTest { + + private ChannelBuffer buffer; + + @Override + protected ChannelBuffer newBuffer(int length) { + buffer = ChannelBuffers.dynamicBuffer(length); + + assertEquals(0, buffer.readerIndex()); + assertEquals(0, buffer.writerIndex()); + assertEquals(length, buffer.capacity()); + + return buffer; + } + + @Override + protected ChannelBuffer[] components() { + return new ChannelBuffer[]{buffer}; + } + + @Test + public void shouldNotFailOnInitialIndexUpdate() { + new DynamicChannelBuffer(10).setIndex(0, 10); + } + + @Test + public void shouldNotFailOnInitialIndexUpdate2() { + new DynamicChannelBuffer(10).writerIndex(10); + } + + @Test + public void shouldNotFailOnInitialIndexUpdate3() { + ChannelBuffer buf = new DynamicChannelBuffer(10); + buf.writerIndex(10); + buf.readerIndex(10); + } +} + diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBufferTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBufferTest.java new file mode 100644 index 000000000000..7319bb45c14d --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/buffer/HeapChannelBufferTest.java @@ -0,0 +1,23 @@ +package com.alibaba.dubbo.remoting.buffer; + +import junit.framework.Assert; + +/** + * @author kimi + */ +public class HeapChannelBufferTest extends AbstractChannelBufferTest { + + private ChannelBuffer buffer; + + @Override + protected ChannelBuffer newBuffer(int capacity) { + buffer = ChannelBuffers.buffer(capacity); + Assert.assertEquals(0, buffer.writerIndex()); + return buffer; + } + + @Override + protected ChannelBuffer[] components() { + return new ChannelBuffer[]{buffer}; + } +} From ae562840557bae790e56c1d6d2a82a4ba055790a Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 18 Oct 2012 11:21:03 +0800 Subject: [PATCH 072/200] =?UTF-8?q?DUBBO-166=20=E5=A2=9E=E5=BC=BA=20codec?= =?UTF-8?q?=20=E9=81=BF=E5=85=8D=E6=95=B0=E6=8D=AE=20copy=EF=BC=8C?= =?UTF-8?q?=E9=87=8D=E6=9E=84=E7=B1=BB=E5=90=8D=EF=BC=8C=E6=B7=BB=E5=8A=A0?= =?UTF-8?q?=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95=EF=BC=8C=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=20CodecAdapter=20=E4=BB=A5=E5=8F=8A=20mina=20=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{ChannelCodec.java => Codec2.java} | 2 +- .../remoting/transport/AbstractCodec.java | 154 +++---- .../remoting/transport/AbstractEndpoint.java | 16 +- ...nelCodecAdapter.java => CodecAdapter.java} | 12 +- ...odec => com.alibaba.dubbo.remoting.Codec2} | 4 +- .../dubbo/remoting/codec/TelnetCodecTest.java | 28 +- .../transport/codec/CodecAdapterTest.java | 29 ++ .../codec/DeprecatedExchangeCodec.java | 404 ++++++++++++++++++ .../codec/DeprecatedTelnetCodec.java | 315 ++++++++++++++ .../grizzly/GrizzlyCodecAdapter.java | 282 ++++++------ .../transport/mina/MinaCodecAdapter.java | 8 +- .../transport/netty/NettyCodecAdapter.java | 8 +- dubbo-rpc/dubbo-rpc-default/pom.xml | 134 +++--- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 4 +- .../rpc/protocol/dubbo/DubboCountCodec.java | 11 +- ...odec => com.alibaba.dubbo.remoting.Codec2} | 0 .../rpc/protocol/dubbo/DubboProtocolTest.java | 225 ++++++---- .../rpc/protocol/thrift/ThriftCodec.java | 4 +- .../protocol/thrift/ThriftNativeCodec.java | 4 +- ...odec => com.alibaba.dubbo.remoting.Codec2} | 0 20 files changed, 1214 insertions(+), 430 deletions(-) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/{ChannelCodec.java => Codec2.java} (97%) rename dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/{ChannelCodecAdapter.java => CodecAdapter.java} (85%) rename dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/{com.alibaba.dubbo.remoting.ChannelCodec => com.alibaba.dubbo.remoting.Codec2} (98%) create mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java create mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java rename dubbo-rpc/dubbo-rpc-default/src/main/resources/META-INF/dubbo/internal/{com.alibaba.dubbo.remoting.ChannelCodec => com.alibaba.dubbo.remoting.Codec2} (100%) rename dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/{com.alibaba.dubbo.remoting.ChannelCodec => com.alibaba.dubbo.remoting.Codec2} (100%) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ChannelCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec2.java similarity index 97% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ChannelCodec.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec2.java index 5303189b83c1..bfdc7871d77c 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/ChannelCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/Codec2.java @@ -26,7 +26,7 @@ * @author kimi */ @SPI -public interface ChannelCodec { +public interface Codec2 { @Adaptive({Constants.CODEC_KEY}) void encode(Channel channel, ChannelBuffer buffer, Object message) throws IOException; diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java index 0d9a0b49d461..d3026f6cc0c9 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java @@ -1,78 +1,78 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting.transport; - -import java.io.IOException; -import java.net.InetSocketAddress; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.serialize.Serialization; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelCodec; - -/** - * AbstractCodec - * - * @author william.liangf - */ -public abstract class AbstractCodec implements ChannelCodec { - - private static final Logger logger = LoggerFactory.getLogger(AbstractCodec.class); - - protected Serialization getSerialization(Channel channel) { - return CodecSupport.getSerialization(channel.getUrl()); - } - - protected static void checkPayload(Channel channel, long size) throws IOException { - int payload = Constants.DEFAULT_PAYLOAD; - if (channel != null && channel.getUrl() != null) { - payload = channel.getUrl().getPositiveParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); - } - if (size > payload) { - IOException e = new IOException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); - logger.error(e); - throw e; - } - } - - protected boolean isClientSide(Channel channel) { - String side = (String) channel.getAttribute(Constants.SIDE_KEY); - if ("client".equals(side)) { - return true; - } else if ("server".equals(side)) { - return false; - } else { - InetSocketAddress address = channel.getRemoteAddress(); - URL url = channel.getUrl(); - boolean client = url.getPort() == address.getPort() - && NetUtils.filterLocalHost(url.getIp()).equals( - NetUtils.filterLocalHost(address.getAddress() - .getHostAddress())); - channel.setAttribute(Constants.SIDE_KEY, client ? "client" - : "server"); - return client; - } - } - - protected boolean isServerSide(Channel channel) { - return !isClientSide(channel); - } - +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.transport; + +import java.io.IOException; +import java.net.InetSocketAddress; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.serialize.Serialization; +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.Codec2; + +/** + * AbstractCodec + * + * @author william.liangf + */ +public abstract class AbstractCodec implements Codec2 { + + private static final Logger logger = LoggerFactory.getLogger(AbstractCodec.class); + + protected Serialization getSerialization(Channel channel) { + return CodecSupport.getSerialization(channel.getUrl()); + } + + protected static void checkPayload(Channel channel, long size) throws IOException { + int payload = Constants.DEFAULT_PAYLOAD; + if (channel != null && channel.getUrl() != null) { + payload = channel.getUrl().getPositiveParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); + } + if (size > payload) { + IOException e = new IOException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); + logger.error(e); + throw e; + } + } + + protected boolean isClientSide(Channel channel) { + String side = (String) channel.getAttribute(Constants.SIDE_KEY); + if ("client".equals(side)) { + return true; + } else if ("server".equals(side)) { + return false; + } else { + InetSocketAddress address = channel.getRemoteAddress(); + URL url = channel.getUrl(); + boolean client = url.getPort() == address.getPort() + && NetUtils.filterLocalHost(url.getIp()).equals( + NetUtils.filterLocalHost(address.getAddress() + .getHostAddress())); + channel.setAttribute(Constants.SIDE_KEY, client ? "client" + : "server"); + return client; + } + } + + protected boolean isServerSide(Channel channel) { + return !isClientSide(channel); + } + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java index 3019c922e32a..9fc02918eac8 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractEndpoint.java @@ -21,10 +21,10 @@ import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.Codec; -import com.alibaba.dubbo.remoting.transport.codec.ChannelCodecAdapter; +import com.alibaba.dubbo.remoting.transport.codec.CodecAdapter; /** * AbstractEndpoint @@ -35,7 +35,7 @@ public abstract class AbstractEndpoint extends AbstractPeer implements Resetable private static final Logger logger = LoggerFactory.getLogger(AbstractEndpoint.class); - private ChannelCodec codec; + private Codec2 codec; private int timeout; @@ -87,7 +87,7 @@ public void reset(com.alibaba.dubbo.common.Parameters parameters){ reset(getUrl().addParameters(parameters.getParameters())); } - protected ChannelCodec getCodec() { + protected Codec2 getCodec() { return codec; } @@ -99,12 +99,12 @@ protected int getConnectTimeout() { return connectTimeout; } - protected static ChannelCodec getChannelCodec(URL url) { + protected static Codec2 getChannelCodec(URL url) { String codecName = url.getParameter(Constants.CODEC_KEY, "telnet"); - if (ExtensionLoader.getExtensionLoader(ChannelCodec.class).hasExtension(codecName)) { - return ExtensionLoader.getExtensionLoader(ChannelCodec.class).getExtension(codecName); + if (ExtensionLoader.getExtensionLoader(Codec2.class).hasExtension(codecName)) { + return ExtensionLoader.getExtensionLoader(Codec2.class).getExtension(codecName); } else { - return new ChannelCodecAdapter(ExtensionLoader.getExtensionLoader(Codec.class) + return new CodecAdapter(ExtensionLoader.getExtensionLoader(Codec.class) .getExtension(codecName)); } } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/ChannelCodecAdapter.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapter.java similarity index 85% rename from dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/ChannelCodecAdapter.java rename to dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapter.java index ad15c5cb5990..c3ab52c29969 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/ChannelCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapter.java @@ -23,17 +23,17 @@ import com.alibaba.dubbo.common.utils.Assert; import com.alibaba.dubbo.remoting.Channel; import com.alibaba.dubbo.remoting.Codec; -import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; /** * @author kimi */ -public class ChannelCodecAdapter implements ChannelCodec { +public class CodecAdapter implements Codec2 { private Codec codec; - public ChannelCodecAdapter(Codec codec) { + public CodecAdapter(Codec codec) { Assert.notNull(codec, "codec == null"); this.codec = codec; } @@ -51,11 +51,7 @@ public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { buffer.readBytes(bytes); UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(bytes); Object result = codec.decode(channel, is); - if (result == Codec.NEED_MORE_INPUT) { - buffer.readerIndex(savedReaderIndex); - } else { - buffer.readerIndex(savedReaderIndex + is.position()); - } + buffer.readerIndex(savedReaderIndex + is.position()); return result == Codec.NEED_MORE_INPUT ? DecodeResult.NEED_MORE_INPUT : result; } diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec b/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 similarity index 98% rename from dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec rename to dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 index d72ce444fe46..be80199d9d1a 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec +++ b/dubbo-remoting/dubbo-remoting-api/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 @@ -1,3 +1,3 @@ -transport=com.alibaba.dubbo.remoting.transport.codec.TransportCodec -telnet=com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec +transport=com.alibaba.dubbo.remoting.transport.codec.TransportCodec +telnet=com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec exchange=com.alibaba.dubbo.remoting.exchange.codec.ExchangeCodec \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java index fb8e62fb59f7..e3de9d3de871 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/codec/TelnetCodecTest.java @@ -29,7 +29,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; import com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec; @@ -41,7 +41,7 @@ * */ public class TelnetCodecTest { - protected ChannelCodec codec ; + protected Codec2 codec ; byte[] UP = new byte[] {27, 91, 65}; byte[] DOWN = new byte[] {27, 91, 66}; /** @@ -210,7 +210,7 @@ private void testDecode_PersonWithEnterByte(byte[] enterbytes ,boolean isNeedmor //decode Object obj = codec.decode(channel, buffer); if (isNeedmore){ - Assert.assertEquals(ChannelCodec.DecodeResult.NEED_MORE_INPUT , obj); + Assert.assertEquals(Codec2.DecodeResult.NEED_MORE_INPUT , obj); }else { Assert.assertTrue("return must string ", obj instanceof String); } @@ -237,12 +237,12 @@ public void testDecode_String_ClientSide() throws IOException{ @Test public void testDecode_BlankMessage() throws IOException{ - testDecode_assertEquals(new byte[]{}, ChannelCodec.DecodeResult.NEED_MORE_INPUT); + testDecode_assertEquals(new byte[]{}, Codec2.DecodeResult.NEED_MORE_INPUT); } @Test public void testDecode_String_NoEnter() throws IOException{ - testDecode_assertEquals("aaa", ChannelCodec.DecodeResult.NEED_MORE_INPUT); + testDecode_assertEquals("aaa", Codec2.DecodeResult.NEED_MORE_INPUT); } @Test @@ -251,12 +251,12 @@ public void testDecode_String_WithEnter() throws IOException{ } @Test public void testDecode_String_MiddleWithEnter() throws IOException{ - testDecode_assertEquals("aaa\r\naaa", ChannelCodec.DecodeResult.NEED_MORE_INPUT); + testDecode_assertEquals("aaa\r\naaa", Codec2.DecodeResult.NEED_MORE_INPUT); } @Test public void testDecode_Person_ObjectOnly() throws IOException{ - testDecode_assertEquals(new Person(), ChannelCodec.DecodeResult.NEED_MORE_INPUT); + testDecode_assertEquals(new Person(), Codec2.DecodeResult.NEED_MORE_INPUT); } @Test public void testDecode_Person_WithEnter() throws IOException{ @@ -282,14 +282,14 @@ public void testDecode_WithExitByte() throws IOException{ @Test public void testDecode_Backspace() throws IOException{ //32 8 鍏堝姞绌烘牸鍦ㄨˉ閫鏍. - testDecode_assertEquals(new byte[]{'\b'}, ChannelCodec.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 8})); + testDecode_assertEquals(new byte[]{'\b'}, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 8})); //娴嬭瘯涓枃 byte[] chineseBytes = "涓".getBytes(); byte[] request = join(chineseBytes, new byte[]{'\b'}); - testDecode_assertEquals(request, ChannelCodec.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 32, 8, 8})); + testDecode_assertEquals(request, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 32, 8, 8})); //涓枃浼氬甫鏉ユ闂 (-鏁板垽鏂) 蹇界暐姝ら棶棰橈紝閫鏍奸敭鍙湁鍦ㄧ湡鐨則elnet绋嬪簭涓墠杈撳叆鏈夋剰涔. - testDecode_assertEquals(new byte[]{'a', 'x', -1, 'x', '\b'}, ChannelCodec.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 32, 8, 8})); + testDecode_assertEquals(new byte[]{'a', 'x', -1, 'x', '\b'}, Codec2.DecodeResult.NEED_MORE_INPUT, new String(new byte[] {32, 32, 8, 8})); } @Test(expected = IOException.class) @@ -304,14 +304,14 @@ public void testDecode_History_UP() throws IOException{ //init channel AbstractMockChannel channel = getServerSideChannel(url); - testDecode_assertEquals(channel, UP, ChannelCodec.DecodeResult.NEED_MORE_INPUT, null); + testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, null); String request1 = "aaa\n"; Object expected1 = "aaa"; //init history testDecode_assertEquals(channel, request1, expected1, null); - testDecode_assertEquals(channel, UP, ChannelCodec.DecodeResult.NEED_MORE_INPUT, expected1); + testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, expected1); } @Test(expected = IOException.class) @@ -321,14 +321,14 @@ public void testDecode_UPorDOWN_WithError() throws IOException{ //init channel AbstractMockChannel channel = getServerSideChannel(url); - testDecode_assertEquals(channel, UP, ChannelCodec.DecodeResult.NEED_MORE_INPUT, null); + testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, null); String request1 = "aaa\n"; Object expected1 = "aaa"; //init history testDecode_assertEquals(channel, request1, expected1, null); - testDecode_assertEquals(channel, UP, ChannelCodec.DecodeResult.NEED_MORE_INPUT, expected1); + testDecode_assertEquals(channel, UP, Codec2.DecodeResult.NEED_MORE_INPUT, expected1); url = url.removeParameter(AbstractMockChannel.ERROR_WHEN_SEND); } diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java new file mode 100644 index 000000000000..7852dde02e06 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/CodecAdapterTest.java @@ -0,0 +1,29 @@ +package com.alibaba.dubbo.remoting.transport.codec; + +import java.io.IOException; + +import org.junit.Before; +import org.junit.Test; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; +import com.alibaba.dubbo.remoting.codec.ExchangeCodecTest; +import com.alibaba.dubbo.remoting.telnet.codec.TelnetCodec; + +import junit.framework.Assert; + +/** + * @author kimi + */ +public class CodecAdapterTest extends ExchangeCodecTest { + + @Before + public void setUp() throws Exception { + codec = new CodecAdapter(new DeprecatedExchangeCodec()); + } + +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java new file mode 100644 index 000000000000..3c9b8b175a50 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedExchangeCodec.java @@ -0,0 +1,404 @@ +package com.alibaba.dubbo.remoting.transport.codec; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.io.Bytes; +import com.alibaba.dubbo.common.io.StreamUtils; +import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; +import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.serialize.ObjectInput; +import com.alibaba.dubbo.common.serialize.ObjectOutput; +import com.alibaba.dubbo.common.serialize.Serialization; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.exchange.Request; +import com.alibaba.dubbo.remoting.exchange.Response; +import com.alibaba.dubbo.remoting.exchange.support.DefaultFuture; +import com.alibaba.dubbo.remoting.transport.CodecSupport; + +/** + * @author kimi + */ +final class DeprecatedExchangeCodec extends DeprecatedTelnetCodec implements Codec { + + private static final Logger logger = LoggerFactory.getLogger(DeprecatedExchangeCodec.class); + + // header length. + protected static final int HEADER_LENGTH = 16; + + // magic header. + protected static final short MAGIC = (short) 0xdabb; + + protected static final byte MAGIC_HIGH = Bytes.short2bytes(MAGIC)[0]; + + protected static final byte MAGIC_LOW = Bytes.short2bytes(MAGIC)[1]; + + // message flag. + protected static final byte FLAG_REQUEST = (byte) 0x80; + + protected static final byte FLAG_TWOWAY = (byte) 0x40; + + protected static final byte FLAG_EVENT = (byte) 0x20; + + protected static final int SERIALIZATION_MASK = 0x1f; + + public Short getMagicCode() { + return MAGIC; + } + + public void encode(Channel channel, OutputStream os, Object msg) throws IOException { + if (msg instanceof Request) { + encodeRequest(channel, os, (Request) msg); + } else if (msg instanceof Response) { + encodeResponse(channel, os, (Response) msg); + } else { + super.encode(channel, os, msg); + } + } + + public Object decode(Channel channel, InputStream is) throws IOException { + int readable = is.available(); + byte[] header = new byte[Math.min(readable, HEADER_LENGTH)]; + is.read(header); + return decode(channel, is, readable, header); + } + + protected Object decode(Channel channel, InputStream is, int readable, byte[] header) throws IOException { + // check magic number. + if (readable > 0 && header[0] != MAGIC_HIGH + || readable > 1 && header[1] != MAGIC_LOW) { + int length = header.length; + if (header.length < readable) { + header = Bytes.copyOf(header, readable); + is.read(header, length, readable - length); + } + for (int i = 1; i < header.length - 1; i++) { + if (header[i] == MAGIC_HIGH && header[i + 1] == MAGIC_LOW) { + UnsafeByteArrayInputStream bis = ((UnsafeByteArrayInputStream) is); + bis.position(bis.position() - header.length + i); + header = Bytes.copyOf(header, i); + break; + } + } + return super.decode(channel, is, readable, header); + } + // check length. + if (readable < HEADER_LENGTH) { + return NEED_MORE_INPUT; + } + + // get data length. + int len = Bytes.bytes2int(header, 12); + checkPayload(channel, len); + + int tt = len + HEADER_LENGTH; + if (readable < tt) { + return NEED_MORE_INPUT; + } + + // limit input stream. + if (readable != tt) + is = StreamUtils.limitedInputStream(is, len); + + try { + return decodeBody(channel, is, header); + } finally { + if (is.available() > 0) { + try { + if (logger.isWarnEnabled()) { + logger.warn("Skip input stream " + is.available()); + } + StreamUtils.skipUnusedStream(is); + } catch (IOException e) { + logger.warn(e.getMessage(), e); + } + } + } + } + + protected Object decodeBody(Channel channel, InputStream is, byte[] header) throws IOException { + byte flag = header[2], proto = (byte) (flag & SERIALIZATION_MASK); + Serialization s = CodecSupport.getSerialization(channel.getUrl(), proto); + ObjectInput in = s.deserialize(channel.getUrl(), is); + // get request id. + long id = Bytes.bytes2long(header, 4); + if ((flag & FLAG_REQUEST) == 0) { + // decode response. + Response res = new Response(id); + if ((flag & FLAG_EVENT) != 0) { + res.setEvent(Response.HEARTBEAT_EVENT); + } + // get status. + byte status = header[3]; + res.setStatus(status); + if (status == Response.OK) { + try { + Object data; + if (res.isHeartbeat()) { + data = decodeHeartbeatData(channel, in); + } else if (res.isEvent()) { + data = decodeEventData(channel, in); + } else { + data = decodeResponseData(channel, in, getRequestData(id)); + } + res.setResult(data); + } catch (Throwable t) { + res.setStatus(Response.CLIENT_ERROR); + res.setErrorMessage(StringUtils.toString(t)); + } + } else { + res.setErrorMessage(in.readUTF()); + } + return res; + } else { + // decode request. + Request req = new Request(id); + req.setVersion("2.0.0"); + req.setTwoWay((flag & FLAG_TWOWAY) != 0); + if ((flag & FLAG_EVENT) != 0) { + req.setEvent(Request.HEARTBEAT_EVENT); + } + try { + Object data; + if (req.isHeartbeat()) { + data = decodeHeartbeatData(channel, in); + } else if (req.isEvent()) { + data = decodeEventData(channel, in); + } else { + data = decodeRequestData(channel, in); + } + req.setData(data); + } catch (Throwable t) { + // bad request + req.setBroken(true); + req.setData(t); + } + return req; + } + } + + protected Object getRequestData(long id) { + DefaultFuture future = DefaultFuture.getFuture(id); + if (future == null) + return null; + Request req = future.getRequest(); + if (req == null) + return null; + return req.getData(); + } + + protected void encodeRequest(Channel channel, OutputStream os, Request req) throws IOException { + Serialization serialization = CodecSupport.getSerialization(channel.getUrl()); + // header. + byte[] header = new byte[HEADER_LENGTH]; + // set magic number. + Bytes.short2bytes(MAGIC, header); + + // set request and serialization flag. + header[2] = (byte) (FLAG_REQUEST | serialization.getContentTypeId()); + + if (req.isTwoWay()) header[2] |= FLAG_TWOWAY; + if (req.isEvent()) header[2] |= FLAG_EVENT; + + // set request id. + Bytes.long2bytes(req.getId(), header, 4); + + // encode request data. + UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); + ObjectOutput out = serialization.serialize(channel.getUrl(), bos); + if (req.isEvent()) { + encodeEventData(channel, out, req.getData()); + } else { + encodeRequestData(channel, out, req.getData()); + } + out.flushBuffer(); + bos.flush(); + bos.close(); + byte[] data = bos.toByteArray(); + checkPayload(channel, data.length); + Bytes.int2bytes(data.length, header, 12); + + // write + os.write(header); // write header. + os.write(data); // write data. + } + + protected void encodeResponse(Channel channel, OutputStream os, Response res) throws IOException { + try { + Serialization serialization = CodecSupport.getSerialization(channel.getUrl()); + // header. + byte[] header = new byte[HEADER_LENGTH]; + // set magic number. + Bytes.short2bytes(MAGIC, header); + // set request and serialization flag. + header[2] = serialization.getContentTypeId(); + if (res.isHeartbeat()) header[2] |= FLAG_EVENT; + // set response status. + byte status = res.getStatus(); + header[3] = status; + // set request id. + Bytes.long2bytes(res.getId(), header, 4); + + UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(1024); + ObjectOutput out = serialization.serialize(channel.getUrl(), bos); + // encode response data or error message. + if (status == Response.OK) { + if (res.isHeartbeat()) { + encodeHeartbeatData(channel, out, res.getResult()); + } else { + encodeResponseData(channel, out, res.getResult()); + } + } else out.writeUTF(res.getErrorMessage()); + out.flushBuffer(); + bos.flush(); + bos.close(); + + byte[] data = bos.toByteArray(); + checkPayload(channel, data.length); + Bytes.int2bytes(data.length, header, 12); + // write + os.write(header); // write header. + os.write(data); // write data. + } catch (Throwable t) { + // 鍙戦佸け璐ヤ俊鎭粰Consumer锛屽惁鍒機onsumer鍙兘绛夎秴鏃朵簡 + if (!res.isEvent() && res.getStatus() != Response.BAD_RESPONSE) { + try { + // FIXME 鍦–odec涓墦鍗板嚭閿欐棩蹇楋紵鍦↖oHanndler鐨刢aught涓粺涓澶勭悊锛 + logger.warn("Fail to encode response: " + res + ", send bad_response info instead, cause: " + t.getMessage(), t); + + Response r = new Response(res.getId(), res.getVersion()); + r.setStatus(Response.BAD_RESPONSE); + r.setErrorMessage("Failed to send response: " + res + ", cause: " + StringUtils.toString(t)); + channel.send(r); + + return; + } catch (RemotingException e) { + logger.warn("Failed to send bad_response info back: " + res + ", cause: " + e.getMessage(), e); + } + } + + // 閲嶆柊鎶涘嚭鏀跺埌鐨勫紓甯 + if (t instanceof IOException) { + throw (IOException) t; + } else if (t instanceof RuntimeException) { + throw (RuntimeException) t; + } else if (t instanceof Error) { + throw (Error) t; + } else { + throw new RuntimeException(t.getMessage(), t); + } + } + } + + protected Object decodeData(ObjectInput in) throws IOException { + return decodeRequestData(in); + } + + @Deprecated + protected Object decodeHeartbeatData(ObjectInput in) throws IOException { + try { + return in.readObject(); + } catch (ClassNotFoundException e) { + throw new IOException(StringUtils.toString("Read object failed.", e)); + } + } + + protected Object decodeRequestData(ObjectInput in) throws IOException { + try { + return in.readObject(); + } catch (ClassNotFoundException e) { + throw new IOException(StringUtils.toString("Read object failed.", e)); + } + } + + protected Object decodeResponseData(ObjectInput in) throws IOException { + try { + return in.readObject(); + } catch (ClassNotFoundException e) { + throw new IOException(StringUtils.toString("Read object failed.", e)); + } + } + + protected void encodeData(ObjectOutput out, Object data) throws IOException { + encodeRequestData(out, data); + } + + private void encodeEventData(ObjectOutput out, Object data) throws IOException { + out.writeObject(data); + } + + @Deprecated + protected void encodeHeartbeatData(ObjectOutput out, Object data) throws IOException { + encodeEventData(out, data); + } + + protected void encodeRequestData(ObjectOutput out, Object data) throws IOException { + out.writeObject(data); + } + + protected void encodeResponseData(ObjectOutput out, Object data) throws IOException { + out.writeObject(data); + } + + protected Object decodeData(Channel channel, ObjectInput in) throws IOException { + return decodeRequestData(channel, in); + } + + protected Object decodeEventData(Channel channel, ObjectInput in) throws IOException { + try { + return in.readObject(); + } catch (ClassNotFoundException e) { + throw new IOException(StringUtils.toString("Read object failed.", e)); + } + } + + @Deprecated + protected Object decodeHeartbeatData(Channel channel, ObjectInput in) throws IOException { + try { + return in.readObject(); + } catch (ClassNotFoundException e) { + throw new IOException(StringUtils.toString("Read object failed.", e)); + } + } + + protected Object decodeRequestData(Channel channel, ObjectInput in) throws IOException { + return decodeRequestData(in); + } + + protected Object decodeResponseData(Channel channel, ObjectInput in) throws IOException { + return decodeResponseData(in); + } + + protected Object decodeResponseData(Channel channel, ObjectInput in, Object requestData) throws IOException { + return decodeResponseData(channel, in); + } + + protected void encodeData(Channel channel, ObjectOutput out, Object data) throws IOException { + encodeRequestData(channel, out, data); + } + + private void encodeEventData(Channel channel, ObjectOutput out, Object data) throws IOException { + encodeEventData(out, data); + } + + @Deprecated + protected void encodeHeartbeatData(Channel channel, ObjectOutput out, Object data) throws IOException { + encodeHeartbeatData(out, data); + } + + protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) throws IOException { + encodeRequestData(out, data); + } + + protected void encodeResponseData(Channel channel, ObjectOutput out, Object data) throws IOException { + encodeResponseData(out, data); + } + +} diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java new file mode 100644 index 000000000000..74314cd3e181 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/codec/DeprecatedTelnetCodec.java @@ -0,0 +1,315 @@ +package com.alibaba.dubbo.remoting.transport.codec; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.InetSocketAddress; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.serialize.ObjectOutput; +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.Codec; +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.buffer.ChannelBufferOutputStream; +import com.alibaba.dubbo.remoting.transport.CodecSupport; + +/** + * @author kimi + */ +public class DeprecatedTelnetCodec implements Codec { + + private static final Logger logger = LoggerFactory.getLogger(DeprecatedTelnetCodec.class); + + private static final String HISTORY_LIST_KEY = "telnet.history.list"; + + private static final String HISTORY_INDEX_KEY = "telnet.history.index"; + + private static final byte[] UP = new byte[]{27, 91, 65}; + + private static final byte[] DOWN = new byte[]{27, 91, 66}; + + private static final List ENTER = Arrays.asList(new Object[]{new byte[]{'\r', '\n'} /* Windows Enter */, new byte[]{'\n'} /* Linux Enter */}); + + private static final List EXIT = Arrays.asList(new Object[]{new byte[]{3} /* Windows Ctrl+C */, new byte[]{-1, -12, -1, -3, 6} /* Linux Ctrl+C */, new byte[]{-1, -19, -1, -3, 6} /* Linux Pause */}); + + static void checkPayload(Channel channel, long size) throws IOException { + int payload = Constants.DEFAULT_PAYLOAD; + if (channel != null && channel.getUrl() != null) { + payload = channel.getUrl().getPositiveParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); + } + if (size > payload) { + IOException e = new IOException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); + logger.error(e); + throw e; + } + } + + protected boolean isClientSide(Channel channel) { + String side = (String) channel.getAttribute(Constants.SIDE_KEY); + if ("client".equals(side)) { + return true; + } else if ("server".equals(side)) { + return false; + } else { + InetSocketAddress address = channel.getRemoteAddress(); + URL url = channel.getUrl(); + boolean client = url.getPort() == address.getPort() + && NetUtils.filterLocalHost(url.getIp()).equals( + NetUtils.filterLocalHost(address.getAddress() + .getHostAddress())); + channel.setAttribute(Constants.SIDE_KEY, client ? "client" + : "server"); + return client; + } + } + + public void encode(Channel channel, OutputStream output, Object message) throws IOException { + if (message instanceof String) { + if (isClientSide(channel)) { + message = message + "\r\n"; + } + byte[] msgData = ((String) message).getBytes(getCharset(channel).name()); + output.write(msgData); + output.flush(); + } else { + ObjectOutput objectOutput = CodecSupport.getSerialization(channel.getUrl()).serialize(channel.getUrl(), output); + objectOutput.writeObject(message); + objectOutput.flushBuffer(); + } + } + + public Object decode(Channel channel, InputStream is) throws IOException { + int readable = is.available(); + byte[] message = new byte[readable]; + is.read(message); + return decode(channel, is, readable, message); + } + + @SuppressWarnings("unchecked") + protected Object decode(Channel channel, InputStream is, int readable, byte[] message) throws IOException { + if (isClientSide(channel)) { + return toString(message, getCharset(channel)); + } + checkPayload(channel, readable); + if (message == null || message.length == 0) { + return NEED_MORE_INPUT; + } + + if (message[message.length - 1] == '\b') { // Windows backspace echo + try { + boolean doublechar = message.length >= 3 && message[message.length - 3] < 0; // double byte char + channel.send(new String(doublechar ? new byte[]{32, 32, 8, 8} : new byte[]{32, 8}, getCharset(channel).name())); + } catch (RemotingException e) { + throw new IOException(StringUtils.toString(e)); + } + return NEED_MORE_INPUT; + } + + for (Object command : EXIT) { + if (isEquals(message, (byte[]) command)) { + if (logger.isInfoEnabled()) { + logger.info(new Exception("Close channel " + channel + " on exit command: " + Arrays.toString((byte[]) command))); + } + channel.close(); + return null; + } + } + + boolean up = endsWith(message, UP); + boolean down = endsWith(message, DOWN); + if (up || down) { + LinkedList history = (LinkedList) channel.getAttribute(HISTORY_LIST_KEY); + if (history == null || history.size() == 0) { + return NEED_MORE_INPUT; + } + Integer index = (Integer) channel.getAttribute(HISTORY_INDEX_KEY); + Integer old = index; + if (index == null) { + index = history.size() - 1; + } else { + if (up) { + index = index - 1; + if (index < 0) { + index = history.size() - 1; + } + } else { + index = index + 1; + if (index > history.size() - 1) { + index = 0; + } + } + } + if (old == null || !old.equals(index)) { + channel.setAttribute(HISTORY_INDEX_KEY, index); + String value = history.get(index); + if (old != null && old >= 0 && old < history.size()) { + String ov = history.get(old); + StringBuilder buf = new StringBuilder(); + for (int i = 0; i < ov.length(); i++) { + buf.append("\b"); + } + for (int i = 0; i < ov.length(); i++) { + buf.append(" "); + } + for (int i = 0; i < ov.length(); i++) { + buf.append("\b"); + } + value = buf.toString() + value; + } + try { + channel.send(value); + } catch (RemotingException e) { + throw new IOException(StringUtils.toString(e)); + } + } + return NEED_MORE_INPUT; + } + for (Object command : EXIT) { + if (isEquals(message, (byte[]) command)) { + if (logger.isInfoEnabled()) { + logger.info(new Exception("Close channel " + channel + " on exit command " + command)); + } + channel.close(); + return null; + } + } + byte[] enter = null; + for (Object command : ENTER) { + if (endsWith(message, (byte[]) command)) { + enter = (byte[]) command; + break; + } + } + if (enter == null) { + return NEED_MORE_INPUT; + } + LinkedList history = (LinkedList) channel.getAttribute(HISTORY_LIST_KEY); + Integer index = (Integer) channel.getAttribute(HISTORY_INDEX_KEY); + channel.removeAttribute(HISTORY_INDEX_KEY); + if (history != null && history.size() > 0 && index != null && index >= 0 && index < history.size()) { + String value = history.get(index); + if (value != null) { + byte[] b1 = value.getBytes(); + if (message != null && message.length > 0) { + byte[] b2 = new byte[b1.length + message.length]; + System.arraycopy(b1, 0, b2, 0, b1.length); + System.arraycopy(message, 0, b2, b1.length, message.length); + message = b2; + } else { + message = b1; + } + } + } + String result = toString(message, getCharset(channel)); + if (result != null && result.trim().length() > 0) { + if (history == null) { + history = new LinkedList(); + channel.setAttribute(HISTORY_LIST_KEY, history); + } + if (history.size() == 0) { + history.addLast(result); + } else if (!result.equals(history.getLast())) { + history.remove(result); + history.addLast(result); + if (history.size() > 10) { + history.removeFirst(); + } + } + } + return result; + } + + private static Charset getCharset(Channel channel) { + if (channel != null) { + Object attribute = channel.getAttribute(Constants.CHARSET_KEY); + if (attribute instanceof String) { + try { + return Charset.forName((String) attribute); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); + } + } else if (attribute instanceof Charset) { + return (Charset) attribute; + } + URL url = channel.getUrl(); + if (url != null) { + String parameter = url.getParameter(Constants.CHARSET_KEY); + if (parameter != null && parameter.length() > 0) { + try { + return Charset.forName(parameter); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); + } + } + } + } + try { + return Charset.forName("GBK"); + } catch (Throwable t) { + logger.warn(t.getMessage(), t); + } + return Charset.defaultCharset(); + } + + private static String toString(byte[] message, Charset charset) throws UnsupportedEncodingException { + byte[] copy = new byte[message.length]; + int index = 0; + for (int i = 0; i < message.length; i++) { + byte b = message[i]; + if (b == '\b') { // backspace + if (index > 0) { + index--; + } + if (i > 2 && message[i - 2] < 0) { // double byte char + if (index > 0) { + index--; + } + } + } else if (b == 27) { // escape + if (i < message.length - 4 && message[i + 4] == 126) { + i = i + 4; + } else if (i < message.length - 3 && message[i + 3] == 126) { + i = i + 3; + } else if (i < message.length - 2) { + i = i + 2; + } + } else if (b == -1 && i < message.length - 2 + && (message[i + 1] == -3 || message[i + 1] == -5)) { // handshake + i = i + 2; + } else { + copy[index++] = message[i]; + } + } + if (index == 0) { + return ""; + } + return new String(copy, 0, index, charset.name()).trim(); + } + + private static boolean isEquals(byte[] message, byte[] command) throws IOException { + return message.length == command.length && endsWith(message, command); + } + + private static boolean endsWith(byte[] message, byte[] command) throws IOException { + if (message.length < command.length) { + return false; + } + int offset = message.length - command.length; + for (int i = command.length - 1; i >= 0; i--) { + if (message[offset + i] != command[i]) { + return false; + } + } + return true; + } +} diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java index edcc613d7b84..f3169e63ffef 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/com/alibaba/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java @@ -1,142 +1,142 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.remoting.transport.grizzly; - -import java.io.IOException; - -import org.glassfish.grizzly.Buffer; -import org.glassfish.grizzly.Connection; -import org.glassfish.grizzly.filterchain.BaseFilter; -import org.glassfish.grizzly.filterchain.FilterChainContext; -import org.glassfish.grizzly.filterchain.NextAction; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelCodec; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; -import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; -import com.alibaba.dubbo.remoting.buffer.DynamicChannelBuffer; - -/** - * GrizzlyCodecAdapter - * - * @author william.liangf - */ -public class GrizzlyCodecAdapter extends BaseFilter { - - private final ChannelCodec codec; - - private final URL url; - - private final ChannelHandler handler; - - private final int bufferSize; - - private ChannelBuffer previousData = ChannelBuffers.EMPTY_BUFFER; - - public GrizzlyCodecAdapter(ChannelCodec codec, URL url, ChannelHandler handler) { - this.codec = codec; - this.url = url; - this.handler = handler; - int b = url.getPositiveParameter(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); - this.bufferSize = b >= Constants.MIN_BUFFER_SIZE && b <= Constants.MAX_BUFFER_SIZE ? b : Constants.DEFAULT_BUFFER_SIZE; - } - - @Override - public NextAction handleWrite(FilterChainContext context) throws IOException { - Connection connection = context.getConnection(); - GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); - try { - ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer(1024); // 涓嶉渶瑕佸叧闂 - - Object msg = context.getMessage(); - codec.encode(channel, channelBuffer, msg); - - GrizzlyChannel.removeChannelIfDisconnectd(connection); - Buffer buffer = connection.getTransport().getMemoryManager().allocate(channelBuffer.readableBytes()); - buffer.put(channelBuffer.toByteBuffer()); - buffer.flip(); - buffer.allowBufferDispose(true); - context.setMessage(buffer); - } finally { - GrizzlyChannel.removeChannelIfDisconnectd(connection); - } - return context.getInvokeAction(); - } - - @Override - public NextAction handleRead(FilterChainContext context) throws IOException { - Object message = context.getMessage(); - Connection connection = context.getConnection(); - Channel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); - try { - if (message instanceof Buffer) { // 鏀跺埌鏂扮殑鏁版嵁鍖 - Buffer grizzlyBuffer = (Buffer) message; // 缂撳瓨 - - ChannelBuffer frame; - - if (previousData.readable()) { - if (previousData instanceof DynamicChannelBuffer) { - previousData.writeBytes(grizzlyBuffer.toByteBuffer()); - frame = previousData; - } else { - int size = previousData.readableBytes() + grizzlyBuffer.remaining(); - frame = ChannelBuffers.dynamicBuffer(size > bufferSize ? size : bufferSize); - frame.writeBytes(previousData, previousData.readableBytes()); - frame.writeBytes(grizzlyBuffer.toByteBuffer()); - } - } else { - frame = ChannelBuffers.wrappedBuffer(grizzlyBuffer.toByteBuffer()); - } - - Object msg; - int savedReadIndex; - - do { - savedReadIndex = frame.readerIndex(); - try { - msg = codec.decode(channel, frame); - } catch (Exception e) { - previousData = ChannelBuffers.EMPTY_BUFFER; - throw new IOException(e.getMessage(), e); - } - if (msg == ChannelCodec.DecodeResult.NEED_MORE_INPUT) { - frame.readerIndex(savedReadIndex); - return context.getStopAction(); - } else { - if (savedReadIndex == frame.readerIndex()) { - previousData = ChannelBuffers.EMPTY_BUFFER; - throw new IOException("Decode without read data."); - } - if (msg != null) { - context.setMessage(msg); - return context.getInvokeAction(); - } else { - return context.getInvokeAction(); - } - } - } while (frame.readable()); - } else { // 鍏跺畠浜嬩欢鐩存帴寰涓嬩紶 - return context.getInvokeAction(); - } - } finally { - GrizzlyChannel.removeChannelIfDisconnectd(connection); - } - } - +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.transport.grizzly; + +import java.io.IOException; + +import org.glassfish.grizzly.Buffer; +import org.glassfish.grizzly.Connection; +import org.glassfish.grizzly.filterchain.BaseFilter; +import org.glassfish.grizzly.filterchain.FilterChainContext; +import org.glassfish.grizzly.filterchain.NextAction; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.Channel; +import com.alibaba.dubbo.remoting.Codec2; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; +import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; +import com.alibaba.dubbo.remoting.buffer.DynamicChannelBuffer; + +/** + * GrizzlyCodecAdapter + * + * @author william.liangf + */ +public class GrizzlyCodecAdapter extends BaseFilter { + + private final Codec2 codec; + + private final URL url; + + private final ChannelHandler handler; + + private final int bufferSize; + + private ChannelBuffer previousData = ChannelBuffers.EMPTY_BUFFER; + + public GrizzlyCodecAdapter(Codec2 codec, URL url, ChannelHandler handler) { + this.codec = codec; + this.url = url; + this.handler = handler; + int b = url.getPositiveParameter(Constants.BUFFER_KEY, Constants.DEFAULT_BUFFER_SIZE); + this.bufferSize = b >= Constants.MIN_BUFFER_SIZE && b <= Constants.MAX_BUFFER_SIZE ? b : Constants.DEFAULT_BUFFER_SIZE; + } + + @Override + public NextAction handleWrite(FilterChainContext context) throws IOException { + Connection connection = context.getConnection(); + GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); + try { + ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer(1024); // 涓嶉渶瑕佸叧闂 + + Object msg = context.getMessage(); + codec.encode(channel, channelBuffer, msg); + + GrizzlyChannel.removeChannelIfDisconnectd(connection); + Buffer buffer = connection.getTransport().getMemoryManager().allocate(channelBuffer.readableBytes()); + buffer.put(channelBuffer.toByteBuffer()); + buffer.flip(); + buffer.allowBufferDispose(true); + context.setMessage(buffer); + } finally { + GrizzlyChannel.removeChannelIfDisconnectd(connection); + } + return context.getInvokeAction(); + } + + @Override + public NextAction handleRead(FilterChainContext context) throws IOException { + Object message = context.getMessage(); + Connection connection = context.getConnection(); + Channel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); + try { + if (message instanceof Buffer) { // 鏀跺埌鏂扮殑鏁版嵁鍖 + Buffer grizzlyBuffer = (Buffer) message; // 缂撳瓨 + + ChannelBuffer frame; + + if (previousData.readable()) { + if (previousData instanceof DynamicChannelBuffer) { + previousData.writeBytes(grizzlyBuffer.toByteBuffer()); + frame = previousData; + } else { + int size = previousData.readableBytes() + grizzlyBuffer.remaining(); + frame = ChannelBuffers.dynamicBuffer(size > bufferSize ? size : bufferSize); + frame.writeBytes(previousData, previousData.readableBytes()); + frame.writeBytes(grizzlyBuffer.toByteBuffer()); + } + } else { + frame = ChannelBuffers.wrappedBuffer(grizzlyBuffer.toByteBuffer()); + } + + Object msg; + int savedReadIndex; + + do { + savedReadIndex = frame.readerIndex(); + try { + msg = codec.decode(channel, frame); + } catch (Exception e) { + previousData = ChannelBuffers.EMPTY_BUFFER; + throw new IOException(e.getMessage(), e); + } + if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) { + frame.readerIndex(savedReadIndex); + return context.getStopAction(); + } else { + if (savedReadIndex == frame.readerIndex()) { + previousData = ChannelBuffers.EMPTY_BUFFER; + throw new IOException("Decode without read data."); + } + if (msg != null) { + context.setMessage(msg); + return context.getInvokeAction(); + } else { + return context.getInvokeAction(); + } + } + } while (frame.readable()); + } else { // 鍏跺畠浜嬩欢鐩存帴寰涓嬩紶 + return context.getInvokeAction(); + } + } finally { + GrizzlyChannel.removeChannelIfDisconnectd(connection); + } + } + } \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java index 68285173ac38..8d675af7b651 100644 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-mina/src/main/java/com/alibaba/dubbo/remoting/transport/mina/MinaCodecAdapter.java @@ -26,7 +26,7 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.ChannelHandler; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBuffers; @@ -43,7 +43,7 @@ final class MinaCodecAdapter implements ProtocolCodecFactory { private final ProtocolDecoder decoder = new InternalDecoder(); - private final ChannelCodec codec; + private final Codec2 codec; private final URL url; @@ -51,7 +51,7 @@ final class MinaCodecAdapter implements ProtocolCodecFactory { private final int bufferSize; - public MinaCodecAdapter(ChannelCodec codec, URL url, ChannelHandler handler) { + public MinaCodecAdapter(Codec2 codec, URL url, ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; @@ -122,7 +122,7 @@ public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) buffer = ChannelBuffers.EMPTY_BUFFER; throw e; } - if (msg == ChannelCodec.DecodeResult.NEED_MORE_INPUT) { + if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) { frame.readerIndex(savedReadIndex); break; } else { diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java index 9155aa09eeec..9173ac370fd4 100644 --- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java +++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyCodecAdapter.java @@ -31,7 +31,7 @@ import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.buffer.DynamicChannelBuffer; /** @@ -45,7 +45,7 @@ final class NettyCodecAdapter { private final ChannelHandler decoder = new InternalDecoder(); - private final ChannelCodec codec; + private final Codec2 codec; private final URL url; @@ -53,7 +53,7 @@ final class NettyCodecAdapter { private final com.alibaba.dubbo.remoting.ChannelHandler handler; - public NettyCodecAdapter(ChannelCodec codec, URL url, com.alibaba.dubbo.remoting.ChannelHandler handler) { + public NettyCodecAdapter(Codec2 codec, URL url, com.alibaba.dubbo.remoting.ChannelHandler handler) { this.codec = codec; this.url = url; this.handler = handler; @@ -136,7 +136,7 @@ public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) throw buffer = com.alibaba.dubbo.remoting.buffer.ChannelBuffers.EMPTY_BUFFER; throw e; } - if (msg == ChannelCodec.DecodeResult.NEED_MORE_INPUT) { + if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) { message.readerIndex(saveReaderIndex); break; } else { diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index c501d447ec81..0e1a95dc7ea6 100644 --- a/dubbo-rpc/dubbo-rpc-default/pom.xml +++ b/dubbo-rpc/dubbo-rpc-default/pom.xml @@ -1,65 +1,71 @@ - - - 4.0.0 - - com.alibaba - dubbo-rpc - 2.5.3-SNAPSHOT - - dubbo-rpc-default - jar - ${project.artifactId} - The default rpc module of dubbo project - - true - - - - com.alibaba - dubbo-rpc-api - ${project.parent.version} - - - com.alibaba - dubbo-remoting-api - ${project.parent.version} - - - com.alibaba - dubbo-container-api - ${project.parent.version} - - - org.mortbay.jetty - jetty - - - - - com.alibaba - dubbo-remoting-netty - ${project.parent.version} - test - - - org.apache.mina - mina-core - test - - + + + 4.0.0 + + com.alibaba + dubbo-rpc + 2.5.3-SNAPSHOT + + dubbo-rpc-default + jar + ${project.artifactId} + The default rpc module of dubbo project + + true + + + + com.alibaba + dubbo-rpc-api + ${project.parent.version} + + + com.alibaba + dubbo-remoting-api + ${project.parent.version} + + + com.alibaba + dubbo-container-api + ${project.parent.version} + + + org.mortbay.jetty + jetty + + + + + com.alibaba + dubbo-remoting-netty + ${project.parent.version} + test + + + com.alibaba + dubbo-remoting-mina + ${project.parent.version} + test + + + org.apache.mina + mina-core + test + + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java index 881a14da742e..346c77d68a0c 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -31,7 +31,7 @@ import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; import com.alibaba.dubbo.remoting.exchange.codec.ExchangeCodec; @@ -48,7 +48,7 @@ * @author qianlei * @author chao.liuc */ -public class DubboCodec extends ExchangeCodec implements ChannelCodec { +public class DubboCodec extends ExchangeCodec implements Codec2 { private static final Logger log = LoggerFactory.getLogger(DubboCodec.class); diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java index 4c79344071f3..9c6b02cf2360 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCountCodec.java @@ -17,13 +17,10 @@ package com.alibaba.dubbo.rpc.protocol.dubbo; import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.exchange.Request; import com.alibaba.dubbo.remoting.exchange.Response; @@ -34,7 +31,7 @@ /** * @author kimi */ -public final class DubboCountCodec implements ChannelCodec { +public final class DubboCountCodec implements Codec2 { private DubboCodec codec = new DubboCodec(); @@ -47,7 +44,7 @@ public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { MultiMessage result = MultiMessage.create(); do { Object obj = codec.decode(channel, buffer); - if (ChannelCodec.DecodeResult.NEED_MORE_INPUT == obj) { + if (Codec2.DecodeResult.NEED_MORE_INPUT == obj) { buffer.readerIndex(save); break; } else { @@ -57,7 +54,7 @@ public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { } } while (true); if (result.isEmpty()) { - return ChannelCodec.DecodeResult.NEED_MORE_INPUT; + return Codec2.DecodeResult.NEED_MORE_INPUT; } if (result.size() == 1) { return result.get(0); diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec b/dubbo-rpc/dubbo-rpc-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 similarity index 100% rename from dubbo-rpc/dubbo-rpc-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec rename to dubbo-rpc/dubbo-rpc-default/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 diff --git a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java index 118517ad3b22..5183dadb4ade 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java +++ b/dubbo-rpc/dubbo-rpc-default/src/test/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboProtocolTest.java @@ -1,43 +1,44 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.protocol.dubbo; -import static junit.framework.Assert.assertEquals; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import junit.framework.Assert; - -import org.junit.Test; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.rpc.Protocol; -import com.alibaba.dubbo.rpc.ProxyFactory; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoService; -import com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; -import com.alibaba.dubbo.rpc.protocol.dubbo.support.NonSerialized; -import com.alibaba.dubbo.rpc.protocol.dubbo.support.RemoteService; -import com.alibaba.dubbo.rpc.protocol.dubbo.support.RemoteServiceImpl; -import com.alibaba.dubbo.rpc.protocol.dubbo.support.Type; -import com.alibaba.dubbo.rpc.service.EchoService; +import static junit.framework.Assert.assertEquals; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import junit.framework.Assert; + +import org.junit.Test; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.rpc.Protocol; +import com.alibaba.dubbo.rpc.ProxyFactory; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoService; +import com.alibaba.dubbo.rpc.protocol.dubbo.support.DemoServiceImpl; +import com.alibaba.dubbo.rpc.protocol.dubbo.support.NonSerialized; +import com.alibaba.dubbo.rpc.protocol.dubbo.support.RemoteService; +import com.alibaba.dubbo.rpc.protocol.dubbo.support.RemoteServiceImpl; +import com.alibaba.dubbo.rpc.protocol.dubbo.support.Type; +import com.alibaba.dubbo.rpc.service.EchoService; /** * ProxiesTest @@ -65,11 +66,11 @@ public void testDubboProtocol() throws Exception service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName()))); assertEquals(service.enumlength(new Type[]{}), Type.Lower); assertEquals(service.getSize(null), -1); - assertEquals(service.getSize(new String[]{"", "", ""}), 3); - Map map = new HashMap(); - map.put("aa", "bb"); - Set set = service.keys(map); - assertEquals(set.size(), 1); + assertEquals(service.getSize(new String[]{"", "", ""}), 3); + Map map = new HashMap(); + map.put("aa", "bb"); + Set set = service.keys(map); + assertEquals(set.size(), 1); assertEquals(set.iterator().next(), "aa"); service.invoke("dubbo://127.0.0.1:9010/" + DemoService.class.getName() + "", "invoke"); @@ -87,30 +88,66 @@ public void testDubboProtocol() throws Exception assertEquals(echo.$echo("abcdefg"), "abcdefg"); assertEquals(echo.$echo(1234), 1234); } - - @Test - public void testDubboProtocolMultiService() throws Exception - { - DemoService service = new DemoServiceImpl(); - protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName()))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName()))); - - RemoteService remote = new RemoteServiceImpl(); - protocol.export(proxy.getInvoker(remote, RemoteService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + RemoteService.class.getName()))); - remote = proxy.getProxy(protocol.refer(RemoteService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + RemoteService.class.getName()))); - - service.sayHello("world"); - - // test netty client - assertEquals("world", service.echo("world")); - assertEquals("hello world@" + RemoteServiceImpl.class.getName(), remote.sayHello("world")); - - EchoService serviceEcho = (EchoService)service; - assertEquals(serviceEcho.$echo("test"), "test"); - - EchoService remoteEecho = (EchoService)remote; - assertEquals(remoteEecho.$echo("ok"), "ok"); - } + + @Test + public void testDubboProtocolWithMina() throws Exception { + DemoService service = new DemoServiceImpl(); + protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName()).addParameter(Constants.SERVER_KEY, "mina"))); + service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName()).addParameter(Constants.CLIENT_KEY, "mina"))); + for (int i = 0; i < 10; i++) { + assertEquals(service.enumlength(new Type[]{}), Type.Lower); + assertEquals(service.getSize(null), -1); + assertEquals(service.getSize(new String[]{"", "", ""}), 3); + } + Map map = new HashMap(); + map.put("aa", "bb"); + for(int i = 0; i < 10; i++) { + Set set = service.keys(map); + assertEquals(set.size(), 1); + assertEquals(set.iterator().next(), "aa"); + service.invoke("dubbo://127.0.0.1:9010/" + DemoService.class.getName() + "", "invoke"); + } + + service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName() + "?client=mina"))); + // test netty client + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < 1024 * 32 + 32; i++) + buf.append('A'); + System.out.println(service.stringLength(buf.toString())); + + // cast to EchoService + EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName() + "?client=mina"))); + for (int i = 0; i < 10; i++) { + assertEquals(echo.$echo(buf.toString()), buf.toString()); + assertEquals(echo.$echo("test"), "test"); + assertEquals(echo.$echo("abcdefg"), "abcdefg"); + assertEquals(echo.$echo(1234), 1234); + } + } + + @Test + public void testDubboProtocolMultiService() throws Exception + { + DemoService service = new DemoServiceImpl(); + protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName()))); + service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.class.getName()))); + + RemoteService remote = new RemoteServiceImpl(); + protocol.export(proxy.getInvoker(remote, RemoteService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + RemoteService.class.getName()))); + remote = proxy.getProxy(protocol.refer(RemoteService.class, URL.valueOf("dubbo://127.0.0.1:9010/" + RemoteService.class.getName()))); + + service.sayHello("world"); + + // test netty client + assertEquals("world", service.echo("world")); + assertEquals("hello world@" + RemoteServiceImpl.class.getName(), remote.sayHello("world")); + + EchoService serviceEcho = (EchoService)service; + assertEquals(serviceEcho.$echo("test"), "test"); + + EchoService remoteEecho = (EchoService)remote; + assertEquals(remoteEecho.$echo("ok"), "ok"); + } @Test public void testPerm() throws Exception @@ -122,33 +159,33 @@ public void testPerm() throws Exception for(int i=0;i<1000;i++) service.getSize(new String[]{"", "", ""}); System.out.println("take:"+(System.currentTimeMillis()-start)); - } - - @Test - public void testNonSerializedParameter() throws Exception - { - DemoService service = new DemoServiceImpl(); - protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.class.getName() + "?codec=exchange"))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.class.getName() + "?codec=exchange"))); - try { - service.nonSerializedParameter(new NonSerialized()); - Assert.fail(); - } catch (RpcException e) { - Assert.assertTrue(e.getMessage().contains("com.alibaba.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); - } - } - - @Test - public void testReturnNonSerialized() throws Exception - { - DemoService service = new DemoServiceImpl(); - protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.class.getName() + "?codec=exchange"))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.class.getName() + "?codec=exchange"))); - try { - service.returnNonSerialized(); - Assert.fail(); - } catch (RpcException e) { - Assert.assertTrue(e.getMessage().contains("com.alibaba.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); - } + } + + @Test + public void testNonSerializedParameter() throws Exception + { + DemoService service = new DemoServiceImpl(); + protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.class.getName() + "?codec=exchange"))); + service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.class.getName() + "?codec=exchange"))); + try { + service.nonSerializedParameter(new NonSerialized()); + Assert.fail(); + } catch (RpcException e) { + Assert.assertTrue(e.getMessage().contains("com.alibaba.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); + } + } + + @Test + public void testReturnNonSerialized() throws Exception + { + DemoService service = new DemoServiceImpl(); + protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.class.getName() + "?codec=exchange"))); + service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.class.getName() + "?codec=exchange"))); + try { + service.returnNonSerialized(); + Assert.fail(); + } catch (RpcException e) { + Assert.assertTrue(e.getMessage().contains("com.alibaba.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable")); + } } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java index 9951e31a06d7..6c4dee9837f1 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java @@ -40,7 +40,7 @@ import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.utils.ClassHelper; import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBufferInputStream; import com.alibaba.dubbo.remoting.exchange.Request; @@ -71,7 +71,7 @@ * * @author gang.lvg */ -public class ThriftCodec implements ChannelCodec { +public class ThriftCodec implements Codec2 { private static final AtomicInteger THRIFT_SEQ_ID = new AtomicInteger( 0 ); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java index f0c11564d389..a02180e09f50 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java +++ b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java @@ -13,7 +13,7 @@ import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.ChannelCodec; +import com.alibaba.dubbo.remoting.Codec2; import com.alibaba.dubbo.remoting.buffer.ChannelBuffer; import com.alibaba.dubbo.remoting.buffer.ChannelBufferOutputStream; import com.alibaba.dubbo.remoting.exchange.Request; @@ -23,7 +23,7 @@ /** * @author kimi */ -public class ThriftNativeCodec implements ChannelCodec { +public class ThriftNativeCodec implements Codec2 { private final AtomicInteger thriftSeq = new AtomicInteger(0); diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec b/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 similarity index 100% rename from dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.ChannelCodec rename to dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 From 00a1d3045fdeb812902131e7179bbf2a40917cd6 Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 18 Oct 2012 17:30:19 +0800 Subject: [PATCH 073/200] =?UTF-8?q?DUBBO-166=20=E5=A2=9E=E5=BC=BA=20codec?= =?UTF-8?q?=20=E9=81=BF=E5=85=8D=E6=95=B0=E6=8D=AE=20copy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dubbo/pom.xml | 958 +++++++++++++++++++++++++------------------------- 1 file changed, 479 insertions(+), 479 deletions(-) diff --git a/dubbo/pom.xml b/dubbo/pom.xml index c7971e04f25c..04a943a9a67f 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -1,480 +1,480 @@ - - - 4.0.0 - - com.alibaba - dubbo-parent - 2.5.3-SNAPSHOT - - dubbo - jar - ${project.artifactId} - The all in one project of dubbo - - false - - - - com.alibaba - dubbo-config-api - ${project.parent.version} - - - org.mortbay.jetty - jetty - - - - - com.alibaba - dubbo-config-spring - ${project.parent.version} - - - com.alibaba - dubbo-remoting-netty - ${project.parent.version} - - - com.alibaba - dubbo-remoting-mina - ${project.parent.version} - - - org.apache.mina - mina-core - - - org.slf4j - slf4j-api - - - - - com.alibaba - dubbo-remoting-grizzly - ${project.parent.version} - - - org.glassfish.grizzly - grizzly-core - - - - - com.alibaba - dubbo-remoting-p2p - ${project.parent.version} - - - com.alibaba - dubbo-remoting-http - ${project.parent.version} - - - org.mortbay.jetty - jetty - - - org.apache.httpcomponents - httpclient - - - - - com.alibaba - dubbo-rpc-default - ${project.parent.version} - - - com.alibaba - dubbo-rpc-injvm - ${project.parent.version} - - - com.alibaba - dubbo-rpc-rmi - ${project.parent.version} - - - com.alibaba - dubbo-rpc-hessian - ${project.parent.version} - - - com.caucho - hessian - - - - - com.alibaba - dubbo-rpc-http - ${project.parent.version} - - - com.caucho - hessian - - - - - com.alibaba - dubbo-rpc-webservice - ${project.parent.version} - - - org.apache.cxf - cxf-rt-frontend-simple - - - org.apache.cxf - cxf-rt-transports-http - - - - - com.alibaba - dubbo-rpc-thrift - ${project.parent.version} - - - org.apache.thrift - libthrift - - - - - com.alibaba - dubbo-rpc-memcached - ${project.parent.version} - - - com.googlecode.xmemcached - xmemcached - - - - - com.alibaba - dubbo-rpc-redis - ${project.parent.version} - - - redis.clients - jedis - - - - - com.alibaba - dubbo-registry-default - ${project.parent.version} - - - com.alibaba - dubbo-registry-multicast - ${project.parent.version} - - - com.alibaba - dubbo-registry-zookeeper - ${project.parent.version} - - - org.apache.zookeeper - zookeeper - - - com.github.sgroschupf - zkclient - - - com.netflix.curator - curator-framework - - - - - com.alibaba - dubbo-registry-redis - ${project.parent.version} - - - redis.clients - jedis - - - - - com.alibaba - dubbo-monitor-default - ${project.parent.version} - - - com.alibaba - dubbo-container-spring - ${project.parent.version} - - - com.alibaba - dubbo-container-jetty - ${project.parent.version} - - - org.mortbay.jetty - jetty - - - - - com.alibaba - dubbo-container-log4j - ${project.parent.version} - - - com.alibaba - dubbo-container-logback - ${project.parent.version} - - - ch.qos.logback - logback-classic - - - - - - - - maven-source-plugin - - - attach-sources - none - - - - - maven-javadoc-plugin - - - attach-javadoc - deploy - - jar - - - - - public - UTF-8 - UTF-8 - UTF-8 - com.alibaba.com.* - - http://docs.oracle.com/javase/6/docs/api - - - - - org.apache.maven.plugins - maven-shade-plugin - 1.4 - - - package - - shade - - - true - true - - - com.alibaba:hessian-lite - com.alibaba:dubbo-common - com.alibaba:dubbo-remoting-api - com.alibaba:dubbo-remoting-netty - com.alibaba:dubbo-remoting-mina - com.alibaba:dubbo-remoting-grizzly - com.alibaba:dubbo-remoting-p2p - com.alibaba:dubbo-remoting-http - com.alibaba:dubbo-remoting-zookeeper - com.alibaba:dubbo-rpc-api - com.alibaba:dubbo-rpc-default - com.alibaba:dubbo-rpc-injvm - com.alibaba:dubbo-rpc-rmi - com.alibaba:dubbo-rpc-hessian - com.alibaba:dubbo-rpc-http - com.alibaba:dubbo-rpc-webservice - com.alibaba:dubbo-rpc-thrift - com.alibaba:dubbo-rpc-memcached - com.alibaba:dubbo-rpc-redis - com.alibaba:dubbo-filter-validation - com.alibaba:dubbo-filter-cache - com.alibaba:dubbo-cluster - com.alibaba:dubbo-registry-api - com.alibaba:dubbo-registry-default - com.alibaba:dubbo-registry-multicast - com.alibaba:dubbo-registry-zookeeper - com.alibaba:dubbo-registry-redis - com.alibaba:dubbo-monitor-api - com.alibaba:dubbo-monitor-default - com.alibaba:dubbo-config-api - com.alibaba:dubbo-config-spring - com.alibaba:dubbo-container-api - com.alibaba:dubbo-container-spring - com.alibaba:dubbo-container-jetty - com.alibaba:dubbo-container-log4j - com.alibaba:dubbo-container-logback - - - - - META-INF/dubbo/internal/com.alibaba.dubbo.common.compiler.Compiler - - - META-INF/dubbo/internal/com.alibaba.dubbo.common.extension.ExtensionFactory - - - META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization - - - META-INF/dubbo/internal/com.alibaba.dubbo.common.status.StatusChecker - - - META-INF/dubbo/internal/com.alibaba.dubbo.common.threadpool.ThreadPool - - - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher - - - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec - - - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter - - - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.exchange.Exchanger - - - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.http.HttpBinder - - - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.p2p.Networker - - - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.telnet.TelnetHandler - - - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.zookeeper.ZookeeperTransporter - - - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol - - - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter - - - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.InvokerListener - - - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ExporterListener - - - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory - - - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster - - - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.LoadBalance - - - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Merger - - - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.RouterFactory - - - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.ConfiguratorFactory - - - META-INF/dubbo/internal/com.alibaba.dubbo.container.Container - - - META-INF/dubbo/internal/com.alibaba.dubbo.container.page.PageHandler - - - META-INF/dubbo/internal/com.alibaba.dubbo.monitor.MonitorFactory - - - META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory - - - META-INF/dubbo/internal/com.alibaba.dubbo.validation.Validation - - - META-INF/dubbo/internal/com.alibaba.dubbo.cache.CacheFactory - - - META-INF/dubbo/internal/com.alibaba.dubbo.common.store.DataStore - - - META-INF/dubbo/internal/com.alibaba.dubbo.common.logger.LoggerAdapter - - - - - - - - + + + 4.0.0 + + com.alibaba + dubbo-parent + 2.5.3-SNAPSHOT + + dubbo + jar + ${project.artifactId} + The all in one project of dubbo + + false + + + + com.alibaba + dubbo-config-api + ${project.parent.version} + + + org.mortbay.jetty + jetty + + + + + com.alibaba + dubbo-config-spring + ${project.parent.version} + + + com.alibaba + dubbo-remoting-netty + ${project.parent.version} + + + com.alibaba + dubbo-remoting-mina + ${project.parent.version} + + + org.apache.mina + mina-core + + + org.slf4j + slf4j-api + + + + + com.alibaba + dubbo-remoting-grizzly + ${project.parent.version} + + + org.glassfish.grizzly + grizzly-core + + + + + com.alibaba + dubbo-remoting-p2p + ${project.parent.version} + + + com.alibaba + dubbo-remoting-http + ${project.parent.version} + + + org.mortbay.jetty + jetty + + + org.apache.httpcomponents + httpclient + + + + + com.alibaba + dubbo-rpc-default + ${project.parent.version} + + + com.alibaba + dubbo-rpc-injvm + ${project.parent.version} + + + com.alibaba + dubbo-rpc-rmi + ${project.parent.version} + + + com.alibaba + dubbo-rpc-hessian + ${project.parent.version} + + + com.caucho + hessian + + + + + com.alibaba + dubbo-rpc-http + ${project.parent.version} + + + com.caucho + hessian + + + + + com.alibaba + dubbo-rpc-webservice + ${project.parent.version} + + + org.apache.cxf + cxf-rt-frontend-simple + + + org.apache.cxf + cxf-rt-transports-http + + + + + com.alibaba + dubbo-rpc-thrift + ${project.parent.version} + + + org.apache.thrift + libthrift + + + + + com.alibaba + dubbo-rpc-memcached + ${project.parent.version} + + + com.googlecode.xmemcached + xmemcached + + + + + com.alibaba + dubbo-rpc-redis + ${project.parent.version} + + + redis.clients + jedis + + + + + com.alibaba + dubbo-registry-default + ${project.parent.version} + + + com.alibaba + dubbo-registry-multicast + ${project.parent.version} + + + com.alibaba + dubbo-registry-zookeeper + ${project.parent.version} + + + org.apache.zookeeper + zookeeper + + + com.github.sgroschupf + zkclient + + + com.netflix.curator + curator-framework + + + + + com.alibaba + dubbo-registry-redis + ${project.parent.version} + + + redis.clients + jedis + + + + + com.alibaba + dubbo-monitor-default + ${project.parent.version} + + + com.alibaba + dubbo-container-spring + ${project.parent.version} + + + com.alibaba + dubbo-container-jetty + ${project.parent.version} + + + org.mortbay.jetty + jetty + + + + + com.alibaba + dubbo-container-log4j + ${project.parent.version} + + + com.alibaba + dubbo-container-logback + ${project.parent.version} + + + ch.qos.logback + logback-classic + + + + + + + + maven-source-plugin + + + attach-sources + none + + + + + maven-javadoc-plugin + + + attach-javadoc + deploy + + jar + + + + + public + UTF-8 + UTF-8 + UTF-8 + com.alibaba.com.* + + http://docs.oracle.com/javase/6/docs/api + + + + + org.apache.maven.plugins + maven-shade-plugin + 1.4 + + + package + + shade + + + true + true + + + com.alibaba:hessian-lite + com.alibaba:dubbo-common + com.alibaba:dubbo-remoting-api + com.alibaba:dubbo-remoting-netty + com.alibaba:dubbo-remoting-mina + com.alibaba:dubbo-remoting-grizzly + com.alibaba:dubbo-remoting-p2p + com.alibaba:dubbo-remoting-http + com.alibaba:dubbo-remoting-zookeeper + com.alibaba:dubbo-rpc-api + com.alibaba:dubbo-rpc-default + com.alibaba:dubbo-rpc-injvm + com.alibaba:dubbo-rpc-rmi + com.alibaba:dubbo-rpc-hessian + com.alibaba:dubbo-rpc-http + com.alibaba:dubbo-rpc-webservice + com.alibaba:dubbo-rpc-thrift + com.alibaba:dubbo-rpc-memcached + com.alibaba:dubbo-rpc-redis + com.alibaba:dubbo-filter-validation + com.alibaba:dubbo-filter-cache + com.alibaba:dubbo-cluster + com.alibaba:dubbo-registry-api + com.alibaba:dubbo-registry-default + com.alibaba:dubbo-registry-multicast + com.alibaba:dubbo-registry-zookeeper + com.alibaba:dubbo-registry-redis + com.alibaba:dubbo-monitor-api + com.alibaba:dubbo-monitor-default + com.alibaba:dubbo-config-api + com.alibaba:dubbo-config-spring + com.alibaba:dubbo-container-api + com.alibaba:dubbo-container-spring + com.alibaba:dubbo-container-jetty + com.alibaba:dubbo-container-log4j + com.alibaba:dubbo-container-logback + + + + + META-INF/dubbo/internal/com.alibaba.dubbo.common.compiler.Compiler + + + META-INF/dubbo/internal/com.alibaba.dubbo.common.extension.ExtensionFactory + + + META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization + + + META-INF/dubbo/internal/com.alibaba.dubbo.common.status.StatusChecker + + + META-INF/dubbo/internal/com.alibaba.dubbo.common.threadpool.ThreadPool + + + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher + + + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 + + + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter + + + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.exchange.Exchanger + + + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.http.HttpBinder + + + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.p2p.Networker + + + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.telnet.TelnetHandler + + + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.zookeeper.ZookeeperTransporter + + + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol + + + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter + + + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.InvokerListener + + + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ExporterListener + + + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory + + + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster + + + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.LoadBalance + + + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Merger + + + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.RouterFactory + + + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.ConfiguratorFactory + + + META-INF/dubbo/internal/com.alibaba.dubbo.container.Container + + + META-INF/dubbo/internal/com.alibaba.dubbo.container.page.PageHandler + + + META-INF/dubbo/internal/com.alibaba.dubbo.monitor.MonitorFactory + + + META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory + + + META-INF/dubbo/internal/com.alibaba.dubbo.validation.Validation + + + META-INF/dubbo/internal/com.alibaba.dubbo.cache.CacheFactory + + + META-INF/dubbo/internal/com.alibaba.dubbo.common.store.DataStore + + + META-INF/dubbo/internal/com.alibaba.dubbo.common.logger.LoggerAdapter + + + + + + + + \ No newline at end of file From 9754b4decad728056268414ad9cd6fd50014ce00 Mon Sep 17 00:00:00 2001 From: oldrat Date: Fri, 19 Oct 2012 14:21:14 +0800 Subject: [PATCH 074/200] reopen http://code.alibabatech.com/jira/browse/DUBBO-600 --- .../remoting/transport/AbstractCodecTest.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/AbstractCodecTest.java diff --git a/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/AbstractCodecTest.java b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/AbstractCodecTest.java new file mode 100644 index 000000000000..e11070e0c6a6 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-api/src/test/java/com/alibaba/dubbo/remoting/transport/AbstractCodecTest.java @@ -0,0 +1,66 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.transport; + +import java.io.IOException; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.Channel; +import junit.framework.TestCase; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertThat; +import static org.junit.matchers.JUnitMatchers.*; +import static org.hamcrest.CoreMatchers.*; + +/** + * @author ding.lid + */ +public class AbstractCodecTest extends TestCase { + + public void test_checkPayload_default8M() throws Exception { + Channel channel = createMock(Channel.class); + expect(channel.getUrl()).andReturn(URL.valueOf("dubbo://1.1.1.1")).anyTimes(); + replay(channel); + + AbstractCodec.checkPayload(channel, 1 * 1024 * 1024); + + try { + AbstractCodec.checkPayload(channel, 15 * 1024 * 1024); + } + catch (IOException expected) { + assertThat(expected.getMessage(), allOf( + containsString("Data length too large: "), + containsString("max payload: " + 8 * 1024 * 1024) + )); + } + + verify(channel); + } + + public void test_checkPayload_minusPayloadNoLimit() throws Exception { + Channel channel = createMock(Channel.class); + expect(channel.getUrl()).andReturn(URL.valueOf("dubbo://1.1.1.1?payload=-1")).anyTimes(); + replay(channel); + + AbstractCodec.checkPayload(channel, 15 * 1024 * 1024); + + verify(channel); + } +} From 2fb8bd5f0126ce9a21741a45619a9065433bc949 Mon Sep 17 00:00:00 2001 From: oldrat Date: Fri, 19 Oct 2012 14:54:21 +0800 Subject: [PATCH 075/200] reopen http://code.alibabatech.com/jira/browse/DUBBO-600 --- .../com/alibaba/dubbo/remoting/transport/AbstractCodec.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java index d3026f6cc0c9..47f997f6e86e 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractCodec.java @@ -43,9 +43,9 @@ protected Serialization getSerialization(Channel channel) { protected static void checkPayload(Channel channel, long size) throws IOException { int payload = Constants.DEFAULT_PAYLOAD; if (channel != null && channel.getUrl() != null) { - payload = channel.getUrl().getPositiveParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); + payload = channel.getUrl().getParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD); } - if (size > payload) { + if (payload > 0 && size > payload) { IOException e = new IOException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel); logger.error(e); throw e; @@ -75,4 +75,4 @@ protected boolean isServerSide(Channel channel) { return !isClientSide(channel); } -} \ No newline at end of file +} From 5a98aa2e6710b8f6c4cacd023751abb75e539236 Mon Sep 17 00:00:00 2001 From: kimi Date: Thu, 22 Nov 2012 16:02:24 +0800 Subject: [PATCH 076/200] =?UTF-8?q?DUBBO-616=20javassist=20class=20loader?= =?UTF-8?q?=20=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/dubbo/common/bytecode/ClassGenerator.java | 5 ++--- .../main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java index 36a9443e58fc..efe08a006a6a 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java @@ -38,7 +38,6 @@ import javassist.LoaderClassPath; import javassist.NotFoundException; -import com.alibaba.dubbo.common.utils.ClassHelper; import com.alibaba.dubbo.common.utils.ReflectUtils; /** @@ -59,7 +58,7 @@ public static interface DC{} // dynamic class tag interface. public static ClassGenerator newInstance() { - return new ClassGenerator(getClassPool(ClassHelper.getCallerClassLoader(ClassGenerator.class))); + return new ClassGenerator(getClassPool(Thread.currentThread().getContextClassLoader())); } public static ClassGenerator newInstance(ClassLoader loader) @@ -335,7 +334,7 @@ public Class toClass() } } } - return mCtc.toClass(ClassHelper.getCallerClassLoader(getClass()), null); + return mCtc.toClass(); } catch(RuntimeException e) { diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java index 08dff750309e..653e30e6425a 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/Wrapper.java @@ -207,7 +207,7 @@ private static Wrapper makeWrapper(Class c) throw new IllegalArgumentException("Can not create wrapper for primitive type: " + c); String name = c.getName(); - ClassLoader cl = ClassHelper.getCallerClassLoader(Wrapper.class); + ClassLoader cl = ClassHelper.getClassLoader(c); StringBuilder c1 = new StringBuilder("public void setPropertyValue(Object o, String n, Object v){ "); StringBuilder c2 = new StringBuilder("public Object getPropertyValue(Object o, String n){ "); From efcb0f3b32366a32ede235219bec528a54db5f1a Mon Sep 17 00:00:00 2001 From: kimi Date: Tue, 25 Dec 2012 16:59:35 +0800 Subject: [PATCH 077/200] update version to 2.5.4-SNAPSHOT --- dubbo-admin/pom.xml | 2 +- dubbo-cluster/pom.xml | 2 +- dubbo-common/pom.xml | 2 +- dubbo-config/dubbo-config-api/pom.xml | 2 +- dubbo-config/dubbo-config-spring/pom.xml | 2 +- dubbo-config/pom.xml | 2 +- dubbo-container/dubbo-container-api/pom.xml | 2 +- dubbo-container/dubbo-container-jetty/pom.xml | 2 +- dubbo-container/dubbo-container-log4j/pom.xml | 2 +- .../dubbo-container-logback/pom.xml | 2 +- .../dubbo-container-spring/pom.xml | 2 +- dubbo-container/pom.xml | 2 +- dubbo-demo/dubbo-demo-api/pom.xml | 2 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 2 +- dubbo-demo/dubbo-demo-provider/pom.xml | 2 +- dubbo-demo/pom.xml | 2 +- dubbo-filter/dubbo-filter-cache/pom.xml | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 2 +- dubbo-filter/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +- dubbo-monitor/pom.xml | 2 +- dubbo-registry/dubbo-registry-api/pom.xml | 2 +- dubbo-registry/dubbo-registry-default/pom.xml | 2 +- .../dubbo-registry-multicast/pom.xml | 2 +- dubbo-registry/dubbo-registry-redis/pom.xml | 2 +- .../dubbo-registry-zookeeper/pom.xml | 2 +- dubbo-registry/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-nio/pom.xml | 41 ++++++++++ dubbo-remoting/dubbo-remoting-p2p/pom.xml | 2 +- .../dubbo-remoting-zookeeper/pom.xml | 2 +- dubbo-remoting/pom.xml | 80 +++++++++---------- dubbo-rpc/dubbo-rpc-api/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-default/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 2 +- dubbo-rpc/pom.xml | 2 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 2 +- dubbo-simple/dubbo-registry-simple/pom.xml | 2 +- dubbo-simple/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark/pom.xml | 2 +- dubbo-test/dubbo-test-compatibility/pom.xml | 2 +- dubbo-test/dubbo-test-examples/pom.xml | 2 +- dubbo-test/dubbo-test-integration/pom.xml | 2 +- dubbo-test/pom.xml | 2 +- dubbo/pom.xml | 2 +- pom.xml | 2 +- 58 files changed, 137 insertions(+), 96 deletions(-) create mode 100644 dubbo-remoting/dubbo-remoting-nio/pom.xml diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index d72e33daec26..44ce306a6943 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-admin war diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index fcb7c6e700de..1e9edf86e747 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-cluster jar diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index fb381c58c115..26e31c1e7c2e 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-common jar diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 786b29dc81ba..4affbcc72a91 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-config-api jar diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index c02089df87f0..274f7791bacf 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-config-spring jar diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index 9e2a66c1cf14..ed2a84959cc9 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index ae8b39da87bb..342964ed50a6 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-container-api jar diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index fd5e6b8e7795..31811b18ed2d 100644 --- a/dubbo-container/dubbo-container-jetty/pom.xml +++ b/dubbo-container/dubbo-container-jetty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index 8c6cbd2272a0..adea3aa7e96a 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index c873cfb084e3..20493bae530b 100644 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ b/dubbo-container/dubbo-container-logback/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index 83c13668ca0f..30a7a299d68b 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-container-spring jar diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index 0de335044872..b8738814cb5e 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-container pom diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index e755624a57b7..849c3e65326f 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-demo-api jar diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml index 37eae52db210..e518cff2c0d8 100644 --- a/dubbo-demo/dubbo-demo-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-demo-consumer jar diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml index c76d5807c408..c7970f1239e8 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-demo-provider jar diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index db063c2b1b65..05b065c72193 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-demo pom diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 362f8d582337..c5fb69531609 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index c5add7aaf69a..43af3825095a 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index 7fb80e708f17..8a50206a4dbe 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-filter pom diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index f4359b03b424..19df1ae264a0 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index c3d4c0d4249d..a4e398bcd3fd 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index 8f07a90dfdfa..a5c516f6aeea 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 776758ea8c55..21e51e1df39c 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index 1c46630e9ba5..616cd82a01a3 100644 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ b/dubbo-registry/dubbo-registry-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-registry-default jar diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index 9316731eedd0..31f9e46bf7c7 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index 3ac6c6d31b86..89480310c53c 100644 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ b/dubbo-registry/dubbo-registry-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-registry-redis jar diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index 762bba899ae3..b42217d30c73 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-registry-zookeeper jar diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index 2692390f29ed..47161e2cfca1 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-registry pom diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index ed94b1f11a25..3c3195105ef7 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-remoting-api jar diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml index 7ebd6db8b4a8..4aac70bd47b2 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml +++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-remoting-grizzly jar diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index a17b281c3413..8b30a08a74e4 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-remoting-http jar diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml index 50a90f59b4bb..7cd615a50e36 100644 --- a/dubbo-remoting/dubbo-remoting-mina/pom.xml +++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-remoting-mina jar diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index 1cafe96cdc56..125b9569fcb2 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-remoting-netty jar diff --git a/dubbo-remoting/dubbo-remoting-nio/pom.xml b/dubbo-remoting/dubbo-remoting-nio/pom.xml new file mode 100644 index 000000000000..2962b3dcaaa0 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-nio/pom.xml @@ -0,0 +1,41 @@ + + + + + + 4.0.0 + + dubbo-remoting + com.alibaba + 2.5.4-SNAPSHOT + + com.alibaba + dubbo-remoting-nio + dubbo-remoting-nio + + + com.alibaba + dubbo-remoting-api + ${project.parent.version} + + + junit + junit + + + diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml index be6179a49016..c6c51811f9b0 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml +++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-remoting-p2p jar diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index 120055e22be0..2564ffc125c8 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-remoting-zookeeper jar diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 92abba7b4077..e3bcaab869d0 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -1,40 +1,40 @@ - - - 4.0.0 - - com.alibaba - dubbo-parent - 2.5.3-SNAPSHOT - - dubbo-remoting - pom - ${project.artifactId} - The remoting module of dubbo project - - true - - - dubbo-remoting-api - dubbo-remoting-netty - dubbo-remoting-mina - dubbo-remoting-grizzly - dubbo-remoting-p2p - dubbo-remoting-http - dubbo-remoting-zookeeper - - + + + 4.0.0 + + com.alibaba + dubbo-parent + 2.5.4-SNAPSHOT + + dubbo-remoting + pom + ${project.artifactId} + The remoting module of dubbo project + + true + + + dubbo-remoting-api + dubbo-remoting-netty + dubbo-remoting-mina + dubbo-remoting-grizzly + dubbo-remoting-p2p + dubbo-remoting-http + dubbo-remoting-zookeeper + dubbo-remoting-nio + + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index f15fa164effa..6cf17775898f 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-rpc-api jar diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index 0e1a95dc7ea6..906ba76bd04a 100644 --- a/dubbo-rpc/dubbo-rpc-default/pom.xml +++ b/dubbo-rpc/dubbo-rpc-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-rpc-default jar diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index 4fe91df80916..5002898948a3 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-rpc-hessian jar diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index 239a289fcba6..9eb8901c8dbb 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-rpc-http jar diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index 93fdbe7d7279..cf4f50088874 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml +++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-rpc-injvm jar diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml index 0b18b013b3c4..dfcde46c0f03 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml +++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-rpc-memcached jar diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml index 51b0ba3ff2ef..86902eb96b55 100644 --- a/dubbo-rpc/dubbo-rpc-redis/pom.xml +++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-rpc-redis jar diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml index 81d1130b4dca..ef5e72215bb3 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-rpc-rmi jar diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml index 683574679c20..b632539beed0 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ b/dubbo-rpc/dubbo-rpc-thrift/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-rpc-thrift jar diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml index a0eccfb84753..2e38db44a684 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml +++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-rpc-webservice jar diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 50c0b20da5c3..f2ec70b5838c 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-rpc pom diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml index 6b5a45a402e3..ece10d421067 100644 --- a/dubbo-simple/dubbo-monitor-simple/pom.xml +++ b/dubbo-simple/dubbo-monitor-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-monitor-simple jar diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml index f645af1ef958..4de8766a1652 100644 --- a/dubbo-simple/dubbo-registry-simple/pom.xml +++ b/dubbo-simple/dubbo-registry-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-registry-simple jar diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml index 3b2dc07636e4..523164e39204 100644 --- a/dubbo-simple/pom.xml +++ b/dubbo-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-simple pom diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml index 775f370a4cfd..ae1ea1354826 100644 --- a/dubbo-test/dubbo-test-benchmark/pom.xml +++ b/dubbo-test/dubbo-test-benchmark/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-test-benchmark jar diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml index 116db9a0c707..7f7bfe113cd3 100644 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ b/dubbo-test/dubbo-test-compatibility/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-test-compatibility jar diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index 913063d5c07b..aa9639ec7647 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-test-examples jar diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml index 9aebf178f9f5..52258d76c2af 100644 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ b/dubbo-test/dubbo-test-integration/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-test-integration jar diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml index c3899ebf07d9..37189c188e1b 100644 --- a/dubbo-test/pom.xml +++ b/dubbo-test/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo-test pom diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 04a943a9a67f..52f38760de57 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT dubbo jar diff --git a/pom.xml b/pom.xml index cdd70cef29b0..c285a6e0eec7 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ 2.0 dubbo-parent - 2.5.3-SNAPSHOT + 2.5.4-SNAPSHOT pom ${project.artifactId} The parent project of dubbo From 570a0622116488ca814b831ce845de0040f79713 Mon Sep 17 00:00:00 2001 From: kimi Date: Tue, 25 Dec 2012 18:35:29 +0800 Subject: [PATCH 078/200] =?UTF-8?q?DUBBO-627=20=E6=89=A9=E5=B1=95=E6=B3=9B?= =?UTF-8?q?=E5=8C=96=E8=B0=83=E7=94=A8=E5=92=8C=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/beanutil/JavaBeanAccessor.java | 38 ++ .../common/beanutil/JavaBeanDescriptor.java | 177 +++++++ .../beanutil/JavaBeanSerializeUtil.java | 463 ++++++++++++++++++ .../dubbo/common/utils/ReflectUtils.java | 35 ++ .../beanutil/JavaBeanSerializeUtilTest.java | 292 +++++++++++ 5 files changed, 1005 insertions(+) create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanAccessor.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanAccessor.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanAccessor.java new file mode 100644 index 000000000000..f01442585c7a --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanAccessor.java @@ -0,0 +1,38 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.beanutil; + +/** + * @author kimi + */ +public enum JavaBeanAccessor { + + /** Field accessor. */ + FIELD, + /** Method accessor.*/ + METHOD, + /** Method prefer to field. */ + ALL; + + public static boolean isAccessByMethod(JavaBeanAccessor accessor) { + return METHOD.equals(accessor) || ALL.equals(accessor); + } + + public static boolean isAccessByField(JavaBeanAccessor accessor) { + return FIELD.equals(accessor) || ALL.equals(accessor); + } + +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java new file mode 100644 index 000000000000..d6a222929862 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java @@ -0,0 +1,177 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.dubbo.common.beanutil; + +import java.io.Serializable; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * @author kimi + */ +public final class JavaBeanDescriptor implements Serializable, Iterable> { + + private static final long serialVersionUID = -8505586483570518029L; + + public static final int TYPE_CLASS = 1; + + public static final int TYPE_ENUM = 2; + + public static final int TYPE_COLLECTION = 3; + + public static final int TYPE_MAP = 4; + + public static final int TYPE_ARRAY = 5; + + /** @see com.alibaba.dubbo.common.utils.ReflectUtils#isPrimitive(Class) */ + public static final int TYPE_PRIMITIVE = 6; + + public static final int TYPE_BEAN = 7; + + public static final String ENUM_PROPERTY_NAME = "name"; + + public static final String CLASS_PROPERTY_NAME = "name"; + + public static final String PRIMITIVE_PROPERTY_VALUE = "value"; + + /** + * Used to define a type is valid. + * @see #isValidType(int) + */ + private static final int TYPE_MAX = TYPE_BEAN; + + /** + * Used to define a type is valid. + * @see #isValidType(int) + */ + private static final int TYPE_MIN = TYPE_CLASS; + + private final String className; + + private final int type; + + private Map properties = new LinkedHashMap(); + + public JavaBeanDescriptor(String className, int type) { + notEmpty(className, "class name is empty"); + if (!isValidType(type)) { + throw new IllegalArgumentException( + new StringBuilder(16).append("type [ ") + .append(type).append(" ] is unsupported").toString()); + } + + this.className = className; + this.type = type; + } + + public boolean isClassType() { + return TYPE_CLASS == type; + } + + public boolean isEnumType() { + return TYPE_ENUM == type; + } + + public boolean isCollectionType() { + return TYPE_COLLECTION == type; + } + + public boolean isMapType() { + return TYPE_MAP == type; + } + + public boolean isArrayType() { + return TYPE_ARRAY == type; + } + + public boolean isPrimitiveType() { + return TYPE_PRIMITIVE == type; + } + + public boolean isBeanType() { + return TYPE_BEAN == type; + } + + public int getType() { + return type; + } + + public String getClassName() { + return className; + } + + public Object setProperty(Object propertyName, Object propertyValue) { + notNull(propertyName, "Property name is null"); + + Object oldValue = properties.put(propertyName, propertyValue); + return oldValue; + } + + public Object setPrimitive(Object primitiveValue) { + if (isPrimitiveType()) { + return setProperty(PRIMITIVE_PROPERTY_VALUE, primitiveValue); + } + throw new IllegalStateException("The instance is not a primitive type wrapper"); + } + + public Object getPrimitive() { + if (isPrimitiveType()) { + return getProperty(PRIMITIVE_PROPERTY_VALUE); + } + throw new IllegalStateException("The instance is not a primitive type wrapper"); + } + + public Object getProperty(Object propertyName) { + notNull(propertyName, "Property name is null"); + Object propertyValue = properties.get(propertyName); + return propertyValue; + } + + public boolean containsProperty(Object propertyName) { + notNull(propertyName, "Property name is null"); + return properties.containsKey(propertyName); + } + + public Iterator> iterator() { + return properties.entrySet().iterator(); + } + + public int propertySize() { + return properties.size(); + } + + private boolean isValidType(int type) { + return TYPE_MIN <= type && type <= TYPE_MAX; + } + + private void notNull(Object obj, String message) { + if (obj == null) { + throw new IllegalArgumentException(message); + } + } + + private void notEmpty(String string, String message) { + if (isEmpty(string)) { + throw new IllegalArgumentException(message); + } + } + + private boolean isEmpty(String string) { + return string == null || "".equals(string.trim()); + } +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java new file mode 100644 index 000000000000..dfacc571d84d --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java @@ -0,0 +1,463 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.beanutil; + +import java.lang.reflect.Array; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.Map; + +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.LogHelper; +import com.alibaba.dubbo.common.utils.ReflectUtils; + +/** + * @author kimi + */ +public final class JavaBeanSerializeUtil { + + private static final Logger logger = LoggerFactory.getLogger(JavaBeanSerializeUtil.class); + + public static JavaBeanDescriptor serialize(Object obj) { + JavaBeanDescriptor result = serialize(obj, JavaBeanAccessor.FIELD); + return result; + } + + public static JavaBeanDescriptor serialize(Object obj, JavaBeanAccessor accessor) { + if (obj == null) { + return null; + } + IdentityHashMap cache = new IdentityHashMap(); + JavaBeanDescriptor result = createDescriptorIfAbsent(obj, accessor, cache); + return result; + } + + private static JavaBeanDescriptor createDescriptorForSerialize(Class cl) { + if (cl.isEnum()) { + return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_ENUM); + } else if (cl.isArray()) { + return new JavaBeanDescriptor(cl.getComponentType().getName(), JavaBeanDescriptor.TYPE_ARRAY); + } else if (ReflectUtils.isPrimitive(cl)) { + return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); + } else if (Class.class.equals(cl)) { + return new JavaBeanDescriptor(Class.class.getName(), JavaBeanDescriptor.TYPE_CLASS); + } else if (Collection.class.isAssignableFrom(cl)) { + return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_COLLECTION); + } else if (Map.class.isAssignableFrom(cl)) { + return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_MAP); + } else { + return new JavaBeanDescriptor(cl.getName(), JavaBeanDescriptor.TYPE_BEAN); + } + } + + private static JavaBeanDescriptor createDescriptorIfAbsent(Object obj, JavaBeanAccessor accessor, IdentityHashMap cache) { + if (cache.containsKey(obj)) { + return cache.get(obj); + } else { + JavaBeanDescriptor result = createDescriptorForSerialize(obj.getClass()); + cache.put(obj, result); + serializeInternal(result, obj, accessor, cache); + return result; + } + } + + private static void serializeInternal(JavaBeanDescriptor descriptor, Object obj, JavaBeanAccessor accessor, IdentityHashMap cache) { + if (obj == null || descriptor == null) { + return; + } + + if (obj.getClass().isEnum()) { + descriptor.setProperty(JavaBeanDescriptor.ENUM_PROPERTY_NAME, ((Enum) obj).name()); + } else if (ReflectUtils.isPrimitive(obj.getClass())) { + descriptor.setProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE, obj); + } else if (Class.class.equals(obj.getClass())) { + descriptor.setProperty(JavaBeanDescriptor.CLASS_PROPERTY_NAME, ((Class) obj).getName()); + } else if (obj.getClass().isArray()) { + int len = Array.getLength(obj); + for (int i = 0; i < len; i++) { + Object item = Array.get(obj, i); + if (item == null) { + descriptor.setProperty(i++, null); + } else { + JavaBeanDescriptor itemDescriptor = createDescriptorIfAbsent(item, accessor, cache); + descriptor.setProperty(i, itemDescriptor); + } + } + } else if (obj instanceof Collection) { + Collection collection = (Collection) obj; + int index = 0; + for (Object item : collection) { + if (item == null) { + descriptor.setProperty(index++, null); + } else { + JavaBeanDescriptor itemDescriptor = createDescriptorIfAbsent(item, accessor, cache); + descriptor.setProperty(index++, itemDescriptor); + } + } + } else if (obj instanceof Map) { + Map map = (Map) obj; + for (Object key : map.keySet()) { + Object value = map.get(key); + Object keyDescriptor = key == null ? null : createDescriptorIfAbsent(key, accessor, cache); + Object valueDescriptor = value == null ? null : createDescriptorIfAbsent(value, accessor, cache); + descriptor.setProperty(keyDescriptor, valueDescriptor); + } // ~ end of loop map + } else { + if (JavaBeanAccessor.isAccessByMethod(accessor)) { + Map methods = ReflectUtils.getBeanPropertyReadMethods(obj.getClass()); + for (Map.Entry entry : methods.entrySet()) { + try { + Object value = entry.getValue().invoke(obj); + if (value == null) { + continue; + } + JavaBeanDescriptor valueDescriptor = createDescriptorIfAbsent(value, accessor, cache); + descriptor.setProperty(entry.getKey(), valueDescriptor); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } // ~ end of loop method map + } // ~ end of if (JavaBeanAccessor.isAccessByMethod(accessor)) + + if (JavaBeanAccessor.isAccessByField(accessor)) { + Map fields = ReflectUtils.getBeanPropertyFields(obj.getClass()); + for (Map.Entry entry : fields.entrySet()) { + if (!descriptor.containsProperty(entry.getKey())) { + try { + Object value = entry.getValue().get(obj); + if (value == null) { + continue; + } + JavaBeanDescriptor valueDescriptor = createDescriptorIfAbsent(value, accessor, cache); + descriptor.setProperty(entry.getKey(), valueDescriptor); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } + } // ~ end of loop field map + } // ~ end of if (JavaBeanAccessor.isAccessByField(accessor)) + + } // ~ end of else + + } // ~ end of method serializeInternal + + public static Object deserialize(JavaBeanDescriptor beanDescriptor) { + Object result = deserialize( + beanDescriptor, + Thread.currentThread().getContextClassLoader()); + return result; + } + + public static Object deserialize(JavaBeanDescriptor beanDescriptor, ClassLoader loader) { + if (beanDescriptor == null) { + return null; + } + IdentityHashMap cache = new IdentityHashMap(); + Object result = instantiateForDeserialize(beanDescriptor, loader, cache); + deserializeInternal(result, beanDescriptor, loader, cache); + return result; + } + + private static void deserializeInternal(Object result, JavaBeanDescriptor beanDescriptor, ClassLoader loader, IdentityHashMap cache) { + if (beanDescriptor.isEnumType() || beanDescriptor.isClassType() || beanDescriptor.isPrimitiveType()) { + return; + } + + if (beanDescriptor.isArrayType()) { + int index = 0; + for (Map.Entry entry : beanDescriptor) { + Object item = entry.getValue(); + if (item instanceof JavaBeanDescriptor) { + JavaBeanDescriptor itemDescriptor = (JavaBeanDescriptor) entry.getValue(); + item = instantiateForDeserialize(itemDescriptor, loader, cache); + deserializeInternal(item, itemDescriptor, loader, cache); + } + Array.set(result, index++, item); + } + } else if (beanDescriptor.isCollectionType()) { + Collection collection = (Collection) result; + for (Map.Entry entry : beanDescriptor) { + Object item = entry.getValue(); + if (item instanceof JavaBeanDescriptor) { + JavaBeanDescriptor itemDescriptor = (JavaBeanDescriptor) entry.getValue(); + item = instantiateForDeserialize(itemDescriptor, loader, cache); + deserializeInternal(item, itemDescriptor, loader, cache); + } + collection.add(item); + } + } else if (beanDescriptor.isMapType()) { + Map map = (Map) result; + for (Map.Entry entry : beanDescriptor) { + Object key = entry.getKey(); + Object value = entry.getValue(); + if (key != null && key instanceof JavaBeanDescriptor) { + JavaBeanDescriptor keyDescriptor = (JavaBeanDescriptor) entry.getKey(); + key = instantiateForDeserialize(keyDescriptor, loader, cache); + deserializeInternal(key, keyDescriptor, loader, cache); + } + if (value != null && value instanceof JavaBeanDescriptor) { + JavaBeanDescriptor valueDescriptor = (JavaBeanDescriptor) entry.getValue(); + value = instantiateForDeserialize(valueDescriptor, loader, cache); + deserializeInternal(value, valueDescriptor, loader, cache); + } + map.put(key, value); + } + } else if (beanDescriptor.isBeanType()) { + for (Map.Entry entry : beanDescriptor) { + String property = entry.getKey().toString(); + Object value = entry.getValue(); + if (value == null) { + continue; + } + + if (value instanceof JavaBeanDescriptor) { + JavaBeanDescriptor valueDescriptor = (JavaBeanDescriptor) entry.getValue(); + value = instantiateForDeserialize(valueDescriptor, loader, cache); + deserializeInternal(value, valueDescriptor, loader, cache); + } + + Method method = getSetterMethod(result.getClass(), property, value.getClass()); + boolean setByMethod = false; + try { + if (method != null) { + method.invoke(result, value); + setByMethod = true; + } + } catch (Exception e) { + LogHelper.warn(logger, "Failed to set property through method " + method, e); + } + + if (!setByMethod) { + try { + Field field = result.getClass().getField(property); + if (field != null) { + field.set(result, value); + } + } catch (NoSuchFieldException e1) { + LogHelper.warn(logger, "Failed to set field value", e1); + } catch (IllegalAccessException e1) { + LogHelper.warn(logger, "Failed to set field value", e1); + } + } + } + } else { + throw new IllegalArgumentException("Unsupported type " + beanDescriptor.getClassName() + ":" + beanDescriptor.getType()); + } + } + + private static Method getSetterMethod(Class cls, String property, Class valueCls) { + String name = "set" + property.substring(0, 1).toUpperCase() + property.substring(1); + Method method = null; + try { + method = cls.getMethod(name, valueCls); + } catch (NoSuchMethodException e) { + for (Method m : cls.getMethods()) { + if (ReflectUtils.isBeanPropertyWriteMethod(m) + && m.getName().equals(name)) { + method = m; + } + } + } + if (method != null) { + method.setAccessible(true); + } + return method; + } + + private static Object instantiate(Class cl) throws Exception { + Constructor[] constructors = cl.getDeclaredConstructors(); + Constructor constructor = null; + int argc = Integer.MAX_VALUE; + for (Constructor c : constructors) { + if (c.getParameterTypes().length < argc) { + argc = c.getParameterTypes().length; + constructor = c; + } + } + + if (constructor != null) { + Class[] paramTypes = constructor.getParameterTypes(); + Object[] constructorArgs = new Object[paramTypes.length]; + for (int i = 0; i < constructorArgs.length; i++) { + constructorArgs[i] = getConstructorArg(paramTypes[i]); + } + try { + constructor.setAccessible(true); + return constructor.newInstance(constructorArgs); + } catch (InstantiationException e) { + LogHelper.warn(logger, e.getMessage(), e); + } catch (IllegalAccessException e) { + LogHelper.warn(logger, e.getMessage(), e); + } catch (InvocationTargetException e) { + LogHelper.warn(logger, e.getMessage(), e); + } + } + + return cl.newInstance(); + } + + private static Object getConstructorArg(Class cl) { + if (boolean.class.equals(cl) || Boolean.class.equals(cl)) { + return Boolean.FALSE; + } else if (byte.class.equals(cl) || Byte.class.equals(cl)) { + return Byte.valueOf((byte) 0); + } else if (short.class.equals(cl) || Short.class.equals(cl)) { + return Short.valueOf((short) 0); + } else if (int.class.equals(cl) || Integer.class.equals(cl)) { + return Integer.valueOf(0); + } else if (long.class.equals(cl) || Long.class.equals(cl)) { + return Long.valueOf(0L); + } else if (float.class.equals(cl) || Float.class.equals(cl)) { + return Float.valueOf((float) 0); + } else if (double.class.equals(cl) || Double.class.equals(cl)) { + return Double.valueOf((double) 0); + } else if (char.class.equals(cl) || Character.class.equals(cl)) { + return new Character((char) 0); + } else { + return null; + } + } + + private static Object instantiateForDeserialize(JavaBeanDescriptor beanDescriptor, ClassLoader loader, IdentityHashMap cache) { + if (cache.containsKey(beanDescriptor)) { + return cache.get(beanDescriptor); + } + Object result = null; + if (beanDescriptor.isClassType()) { + try { + result = name2Class(loader, + beanDescriptor.getProperty(JavaBeanDescriptor.CLASS_PROPERTY_NAME).toString()); + return result; + } catch (ClassNotFoundException e) { + throw new RuntimeException(e.getMessage(), e); + } + } else if (beanDescriptor.isEnumType()) { + try { + Class enumType = name2Class(loader, beanDescriptor.getClassName()); + Method method = getEnumValueOfMethod(enumType); + result = method.invoke(null, enumType, beanDescriptor.getProperty(JavaBeanDescriptor.ENUM_PROPERTY_NAME)); + return result; + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } else if (beanDescriptor.isPrimitiveType()) { + result = beanDescriptor.getProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE); + return result; + } else if (beanDescriptor.isArrayType()) { + Class conponentType = null; + try { + conponentType = name2Class(loader, beanDescriptor.getClassName()); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e.getMessage(), e); + } + result = Array.newInstance(conponentType, beanDescriptor.propertySize()); + cache.put(beanDescriptor, result); + } else try { + Class cl = name2Class(loader, beanDescriptor.getClassName()); + result = instantiate(cl); + cache.put(beanDescriptor, result); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e.getMessage(), e); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + + return result; + } + + private static final Map> TYPES = new HashMap>(); + + static { + TYPES.put(boolean.class.getName(), boolean.class); + TYPES.put(byte.class.getName(), byte.class); + TYPES.put(short.class.getName(), short.class); + TYPES.put(int.class.getName(), int.class); + TYPES.put(long.class.getName(), long.class); + TYPES.put(float.class.getName(), float.class); + TYPES.put(double.class.getName(), double.class); + TYPES.put(void.class.getName(), void.class); + TYPES.put("Z", boolean.class); + TYPES.put("B", byte.class); + TYPES.put("C", char.class); + TYPES.put("D", double.class); + TYPES.put("F", float.class); + TYPES.put("I", int.class); + TYPES.put("J", long.class); + TYPES.put("S", short.class); + } + + private static final String ARRAY_PREFIX = "["; + + private static final String REFERENCE_TYPE_PREFIX = "L"; + + private static final String REFERENCE_TYPE_SUFFIX = ";"; + + /** + * 鎶 Class.forName 鐨勮繑鍥炲艰浆鎹负 Class. + * + * @param name Class.getName() + * + * @return Class + * + * @throws ClassNotFoundException Class.forName + */ + public static Class name2Class(ClassLoader loader, String name) throws ClassNotFoundException { + if (TYPES.containsKey(name)) { + return TYPES.get(name); + } + if (isArray(name)) { + int dimension = 0; + while (isArray(name)) { + ++dimension; + name = name.substring(1); + } + Class type = name2Class(loader, name); + int[] dimensions = new int[dimension]; + for (int i = 0; i < dimension; i++) { + dimensions[i] = 0; + } + return Array.newInstance(type, dimensions).getClass(); + } + if (isReferenceType(name)) { + name = name.substring(1, name.length() - 1); + } + return Class.forName(name, false, loader); + } + + private static boolean isArray(String type) { + return type != null && type.startsWith(ARRAY_PREFIX); + } + + private static boolean isReferenceType(String type) { + return type != null + && type.startsWith(REFERENCE_TYPE_PREFIX) + && type.endsWith(REFERENCE_TYPE_SUFFIX); + } + + private static Method getEnumValueOfMethod(Class cl) throws NoSuchMethodException { + return cl.getMethod("valueOf", Class.class, String.class); + } + + private JavaBeanSerializeUtil() { + } + +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ReflectUtils.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ReflectUtils.java index 8fad47576b83..ccd6aa7b9653 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ReflectUtils.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/ReflectUtils.java @@ -988,5 +988,40 @@ public static boolean isPublicInstanceField(Field field) { && !field.isSynthetic(); } + public static Map getBeanPropertyFields(Class cl) { + Map properties = new HashMap(); + for(; cl != null; cl = cl.getSuperclass()) { + Field[] fields = cl.getDeclaredFields(); + for(Field field : fields) { + if (Modifier.isTransient(field.getModifiers()) + || Modifier.isStatic(field.getModifiers())) { + continue; + } + + field.setAccessible(true); + + properties.put(field.getName(), field); + } + } + + return properties; + } + + public static Map getBeanPropertyReadMethods(Class cl) { + Map properties = new HashMap(); + for(; cl != null; cl = cl.getSuperclass()) { + Method[] methods = cl.getDeclaredMethods(); + for(Method method : methods) { + if (isBeanPropertyReadMethod(method)) { + method.setAccessible(true); + String property = getPropertyNameFromBeanReadMethod(method); + properties.put(property, method); + } + } + } + + return properties; + } + private ReflectUtils(){} } \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java new file mode 100644 index 000000000000..610595399496 --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java @@ -0,0 +1,292 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.beanutil; + +import java.lang.reflect.Array; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.UUID; + +import org.junit.Test; + +import org.junit.Assert; + +import com.alibaba.dubbo.common.model.person.BigPerson; +import com.alibaba.dubbo.common.model.person.FullAddress; +import com.alibaba.dubbo.common.model.person.PersonInfo; +import com.alibaba.dubbo.common.model.person.PersonStatus; +import com.alibaba.dubbo.common.model.person.Phone; +import com.alibaba.dubbo.common.utils.PojoUtilsTest; + +/** + * @author kimi + */ +public class JavaBeanSerializeUtilTest { + + @Test + public void testSerialize_Primitive() throws Exception { + JavaBeanDescriptor descriptor; + descriptor = JavaBeanSerializeUtil.serialize(Integer.MAX_VALUE); + Assert.assertTrue(descriptor.isPrimitiveType()); + Assert.assertEquals(Integer.MAX_VALUE, descriptor.getProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE)); + + Date now = new Date(); + descriptor = JavaBeanSerializeUtil.serialize(now); + Assert.assertTrue(descriptor.isPrimitiveType()); + Assert.assertEquals(now, descriptor.getProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE)); + } + + @Test + public void testDeserialize_Primitive() throws Exception { + JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); + descriptor.setProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE, Long.MAX_VALUE); + Assert.assertEquals(Long.MAX_VALUE, JavaBeanSerializeUtil.deserialize(descriptor)); + + BigDecimal decimal = BigDecimal.TEN; + Assert.assertEquals(Long.MAX_VALUE, descriptor.setProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE, decimal)); + Assert.assertEquals(decimal, JavaBeanSerializeUtil.deserialize(descriptor)); + + String string = UUID.randomUUID().toString(); + Assert.assertEquals(decimal, descriptor.setProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE, string)); + Assert.assertEquals(string, JavaBeanSerializeUtil.deserialize(descriptor)); + } + + @Test + public void testSerialize_Array() throws Exception { + int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + JavaBeanDescriptor descriptor = JavaBeanSerializeUtil.serialize(array, JavaBeanAccessor.METHOD); + Assert.assertTrue(descriptor.isArrayType()); + Assert.assertEquals(int.class.getName(), descriptor.getClassName()); + for (int i = 0; i < array.length; i++) { + Assert.assertEquals(array[i], + ((JavaBeanDescriptor) descriptor.getProperty(i)).getProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE)); + } + + int[][] second = {{1, 2}, {3, 4}}; + descriptor = JavaBeanSerializeUtil.serialize(second, JavaBeanAccessor.METHOD); + Assert.assertTrue(descriptor.isArrayType()); + Assert.assertEquals(int[].class.getName(), descriptor.getClassName()); + for(int i = 0; i < second.length; i++) { + for(int j = 0; j < second[i].length; j++) { + JavaBeanDescriptor item = (((JavaBeanDescriptor)descriptor.getProperty(i))); + Assert.assertTrue(item.isArrayType()); + Assert.assertEquals(int.class.getName(), item.getClassName()); + Assert.assertEquals(second[i][j], ((JavaBeanDescriptor)item.getProperty(j)).getPrimitive()); + } + } + + BigPerson[] persons = new BigPerson[] {createBigPerson(), createBigPerson()}; + descriptor = JavaBeanSerializeUtil.serialize(persons); + Assert.assertTrue(descriptor.isArrayType()); + Assert.assertEquals(BigPerson.class.getName(), descriptor.getClassName()); + for(int i = 0; i < persons.length; i++) { + assertEqualsBigPerson(persons[i], descriptor.getProperty(i)); + } + } + + @Test + public void testDeserialize_Array() throws Exception { + final int len = 10; + JavaBeanDescriptor descriptor = new JavaBeanDescriptor(int.class.getName(), JavaBeanDescriptor.TYPE_ARRAY); + for(int i = 0; i < len; i++) { + descriptor.setProperty(i, i); + } + + Object obj = JavaBeanSerializeUtil.deserialize(descriptor); + Assert.assertTrue(obj.getClass().isArray()); + Assert.assertTrue(int.class == obj.getClass().getComponentType()); + for(int i = 0; i < len; i++) { + Assert.assertEquals(i, Array.get(obj, i)); + } + + descriptor = new JavaBeanDescriptor(int[].class.getName(), JavaBeanDescriptor.TYPE_ARRAY); + for(int i = 0; i < len; i++) { + JavaBeanDescriptor innerItem = new JavaBeanDescriptor(int.class.getName(), JavaBeanDescriptor.TYPE_ARRAY); + for (int j = 0; j < len; j++) { + innerItem.setProperty(j, j); + } + descriptor.setProperty(i, innerItem); + } + obj = JavaBeanSerializeUtil.deserialize(descriptor); + Assert.assertTrue(obj.getClass().isArray()); + Assert.assertEquals(int[].class, obj.getClass().getComponentType()); + for(int i = 0; i < len; i++) { + Object innerItem = Array.get(obj, i); + Assert.assertTrue(innerItem.getClass().isArray()); + Assert.assertEquals(int.class, innerItem.getClass().getComponentType()); + for (int j = 0; j < len; j++) { + Assert.assertEquals(j, Array.get(innerItem, j)); + } + } + + descriptor = new JavaBeanDescriptor(BigPerson[].class.getName(), JavaBeanDescriptor.TYPE_ARRAY); + JavaBeanDescriptor innerDescriptor = new JavaBeanDescriptor(BigPerson.class.getName(), JavaBeanDescriptor.TYPE_ARRAY); + innerDescriptor.setProperty(0, JavaBeanSerializeUtil.serialize(createBigPerson(), JavaBeanAccessor.METHOD)); + descriptor.setProperty(0, innerDescriptor); + + obj = JavaBeanSerializeUtil.deserialize(descriptor); + Assert.assertTrue(obj.getClass().isArray()); + Assert.assertEquals(BigPerson[].class, obj.getClass().getComponentType()); + Assert.assertEquals(1, Array.getLength(obj)); + obj = Array.get(obj, 0); + Assert.assertTrue(obj.getClass().isArray()); + Assert.assertEquals(BigPerson.class, obj.getClass().getComponentType()); + Assert.assertEquals(1, Array.getLength(obj)); + Assert.assertEquals(createBigPerson(), Array.get(obj, 0)); + } + + @Test + public void test_Circular_Reference() throws Exception { + PojoUtilsTest.Parent parent = new PojoUtilsTest.Parent(); + parent.setAge(Integer.MAX_VALUE); + parent.setEmail("a@b"); + parent.setName("zhangsan"); + + PojoUtilsTest.Child child = new PojoUtilsTest.Child(); + child.setAge(100); + child.setName("lisi"); + child.setParent(parent); + + parent.setChild(child); + + JavaBeanDescriptor descriptor = JavaBeanSerializeUtil.serialize(parent, JavaBeanAccessor.METHOD); + Assert.assertTrue(descriptor.isBeanType()); + assertEqualsPrimitive(parent.getAge(), descriptor.getProperty("age")); + assertEqualsPrimitive(parent.getName(), descriptor.getProperty("name")); + assertEqualsPrimitive(parent.getEmail(), descriptor.getProperty("email")); + + JavaBeanDescriptor childDescriptor = (JavaBeanDescriptor) descriptor.getProperty("child"); + Assert.assertTrue(descriptor == childDescriptor.getProperty("parent")); + assertEqualsPrimitive(child.getName(), childDescriptor.getProperty("name")); + assertEqualsPrimitive(child.getAge(), childDescriptor.getProperty("age")); + } + + static void assertEqualsEnum(Enum expected, Object obj) { + JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; + Assert.assertTrue(descriptor.isEnumType()); + Assert.assertEquals(expected.getClass().getName(), descriptor.getClassName()); + Assert.assertEquals(expected.name(), descriptor.getProperty(JavaBeanDescriptor.ENUM_PROPERTY_NAME)); + } + + static void assertEqualsPrimitive(Object expected, Object obj) { + if (expected == null) { return; } + JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; + Assert.assertTrue(descriptor.isPrimitiveType()); + Assert.assertEquals(expected, descriptor.getPrimitive()); + } + + static void assertEqualsBigPerson(BigPerson person, Object obj) { + JavaBeanDescriptor descriptor = (JavaBeanDescriptor)obj; + Assert.assertTrue(descriptor.isBeanType()); + assertEqualsPrimitive(person.getPersonId(), descriptor.getProperty("personId")); + assertEqualsPrimitive(person.getLoginName(), descriptor.getProperty("loginName")); + assertEqualsEnum(person.getStatus(), descriptor.getProperty("status")); + assertEqualsPrimitive(person.getEmail(), descriptor.getProperty("email")); + assertEqualsPrimitive(person.getPenName(), descriptor.getProperty("penName")); + + JavaBeanDescriptor infoProfile = (JavaBeanDescriptor)descriptor.getProperty("infoProfile"); + Assert.assertTrue(infoProfile.isBeanType()); + JavaBeanDescriptor phones = (JavaBeanDescriptor) infoProfile.getProperty("phones"); + Assert.assertTrue(phones.isCollectionType()); + assertEqualsPhone(person.getInfoProfile().getPhones().get(0), phones.getProperty(0)); + assertEqualsPhone(person.getInfoProfile().getPhones().get(1), phones.getProperty(1)); + assertEqualsPhone(person.getInfoProfile().getFax(), infoProfile.getProperty("fax")); + assertEqualsFullAddress(person.getInfoProfile().getFullAddress(), infoProfile.getProperty("fullAddress")); + assertEqualsPrimitive(person.getInfoProfile().getMobileNo(), infoProfile.getProperty("mobileNo")); + assertEqualsPrimitive(person.getInfoProfile().getName(), infoProfile.getProperty("name")); + assertEqualsPrimitive(person.getInfoProfile().getDepartment(), infoProfile.getProperty("department")); + assertEqualsPrimitive(person.getInfoProfile().getJobTitle(), infoProfile.getProperty("jobTitle")); + assertEqualsPrimitive(person.getInfoProfile().getHomepageUrl(), infoProfile.getProperty("homepageUrl")); + assertEqualsPrimitive(person.getInfoProfile().isFemale(), infoProfile.getProperty("female")); + assertEqualsPrimitive(person.getInfoProfile().isMale(), infoProfile.getProperty("male")); + } + + static void assertEqualsPhone(Phone excpected, Object obj) { + JavaBeanDescriptor descriptor = (JavaBeanDescriptor)obj; + Assert.assertTrue(descriptor.isBeanType()); + if (excpected.getArea() != null) { + assertEqualsPrimitive(excpected.getArea(), descriptor.getProperty("area")); + } + if (excpected.getCountry() != null) { + assertEqualsPrimitive(excpected.getCountry(), descriptor.getProperty("country")); + } + if (excpected.getExtensionNumber()!= null) { + assertEqualsPrimitive(excpected.getExtensionNumber(), descriptor.getProperty("extensionNumber")); + } + if (excpected.getNumber() != null) { + assertEqualsPrimitive(excpected.getNumber(), descriptor.getProperty("number")); + } + } + + static void assertEqualsFullAddress(FullAddress expected, Object obj) { + JavaBeanDescriptor descriptor = (JavaBeanDescriptor)obj; + Assert.assertTrue(descriptor.isBeanType()); + if (expected.getCityId() != null) { + assertEqualsPrimitive(expected.getCityId(), descriptor.getProperty("cityId")); + } + if (expected.getCityName() != null) { + assertEqualsPrimitive(expected.getCityName(), descriptor.getProperty("cityName")); + } + if (expected.getCountryId() != null) { + assertEqualsPrimitive(expected.getCountryId(), descriptor.getProperty("countryId")); + } + if (expected.getCountryName() != null) { + assertEqualsPrimitive(expected.getCountryName(), descriptor.getProperty("countryName")); + } + if (expected.getProvinceName() != null) { + assertEqualsPrimitive(expected.getProvinceName(), descriptor.getProperty("provinceName")); + } + if (expected.getStreetAddress() != null) { + assertEqualsPrimitive(expected.getStreetAddress(), descriptor.getProperty("streetAddress")); + } + if (expected.getZipCode() != null) { + assertEqualsPrimitive(expected.getZipCode(), descriptor.getProperty("zipCode")); + } + } + + static BigPerson createBigPerson() { + BigPerson bigPerson; + bigPerson = new BigPerson(); + bigPerson.setPersonId("superman111"); + bigPerson.setLoginName("superman"); + bigPerson.setStatus(PersonStatus.ENABLED); + bigPerson.setEmail("sm@1.com"); + bigPerson.setPenName("pname"); + + ArrayList phones = new ArrayList(); + Phone phone1 = new Phone("86", "0571", "87654321", "001"); + Phone phone2 = new Phone("86", "0571", "87654322", "002"); + phones.add(phone1); + phones.add(phone2); + + PersonInfo pi = new PersonInfo(); + pi.setPhones(phones); + Phone fax = new Phone("86", "0571", "87654321", null); + pi.setFax(fax); + FullAddress addr = new FullAddress("CN", "zj", "3480", "wensanlu", "315000"); + pi.setFullAddress(addr); + pi.setMobileNo("13584652131"); + pi.setMale(true); + pi.setDepartment("b2b"); + pi.setHomepageUrl("www.capcom.com"); + pi.setJobTitle("qa"); + pi.setName("superman"); + + bigPerson.setInfoProfile(pi); + return bigPerson; + } +} From 737dc2446822faf5c16c4baf4827de4885c4c96b Mon Sep 17 00:00:00 2001 From: kimi Date: Wed, 26 Dec 2012 10:48:38 +0800 Subject: [PATCH 079/200] =?UTF-8?q?DUBBO-627=20=E9=87=8D=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/beanutil/JavaBeanDescriptor.java | 42 ++++++++++++++++--- .../beanutil/JavaBeanSerializeUtil.java | 19 ++++----- .../beanutil/JavaBeanSerializeUtilTest.java | 18 ++++---- 3 files changed, 55 insertions(+), 24 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java index d6a222929862..28fe8a64ab35 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java @@ -43,11 +43,11 @@ public final class JavaBeanDescriptor implements Serializable, Iterable) obj).name()); + descriptor.setEnumNameProperty(((Enum) obj).name()); } else if (ReflectUtils.isPrimitive(obj.getClass())) { - descriptor.setProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE, obj); + descriptor.setPrimitiveProperty(obj); } else if (Class.class.equals(obj.getClass())) { - descriptor.setProperty(JavaBeanDescriptor.CLASS_PROPERTY_NAME, ((Class) obj).getName()); + descriptor.setClassNameProperty(((Class) obj).getName()); } else if (obj.getClass().isArray()) { int len = Array.getLength(obj); for (int i = 0; i < len; i++) { @@ -344,8 +344,7 @@ private static Object instantiateForDeserialize(JavaBeanDescriptor beanDescripto Object result = null; if (beanDescriptor.isClassType()) { try { - result = name2Class(loader, - beanDescriptor.getProperty(JavaBeanDescriptor.CLASS_PROPERTY_NAME).toString()); + result = name2Class(loader, beanDescriptor.getClassNameProperty()); return result; } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); @@ -354,22 +353,22 @@ private static Object instantiateForDeserialize(JavaBeanDescriptor beanDescripto try { Class enumType = name2Class(loader, beanDescriptor.getClassName()); Method method = getEnumValueOfMethod(enumType); - result = method.invoke(null, enumType, beanDescriptor.getProperty(JavaBeanDescriptor.ENUM_PROPERTY_NAME)); + result = method.invoke(null, enumType, beanDescriptor.getEnumPropertyName()); return result; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } else if (beanDescriptor.isPrimitiveType()) { - result = beanDescriptor.getProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE); + result = beanDescriptor.getPrimitiveProperty(); return result; } else if (beanDescriptor.isArrayType()) { - Class conponentType = null; + Class componentType; try { - conponentType = name2Class(loader, beanDescriptor.getClassName()); + componentType = name2Class(loader, beanDescriptor.getClassName()); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } - result = Array.newInstance(conponentType, beanDescriptor.propertySize()); + result = Array.newInstance(componentType, beanDescriptor.propertySize()); cache.put(beanDescriptor, result); } else try { Class cl = name2Class(loader, beanDescriptor.getClassName()); diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java index 610595399496..9c11c1aa2394 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java @@ -42,26 +42,26 @@ public void testSerialize_Primitive() throws Exception { JavaBeanDescriptor descriptor; descriptor = JavaBeanSerializeUtil.serialize(Integer.MAX_VALUE); Assert.assertTrue(descriptor.isPrimitiveType()); - Assert.assertEquals(Integer.MAX_VALUE, descriptor.getProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE)); + Assert.assertEquals(Integer.MAX_VALUE, descriptor.getPrimitiveProperty()); Date now = new Date(); descriptor = JavaBeanSerializeUtil.serialize(now); Assert.assertTrue(descriptor.isPrimitiveType()); - Assert.assertEquals(now, descriptor.getProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE)); + Assert.assertEquals(now, descriptor.getPrimitiveProperty()); } @Test public void testDeserialize_Primitive() throws Exception { JavaBeanDescriptor descriptor = new JavaBeanDescriptor(long.class.getName(), JavaBeanDescriptor.TYPE_PRIMITIVE); - descriptor.setProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE, Long.MAX_VALUE); + descriptor.setPrimitiveProperty(Long.MAX_VALUE); Assert.assertEquals(Long.MAX_VALUE, JavaBeanSerializeUtil.deserialize(descriptor)); BigDecimal decimal = BigDecimal.TEN; - Assert.assertEquals(Long.MAX_VALUE, descriptor.setProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE, decimal)); + Assert.assertEquals(Long.MAX_VALUE, descriptor.setPrimitiveProperty(decimal)); Assert.assertEquals(decimal, JavaBeanSerializeUtil.deserialize(descriptor)); String string = UUID.randomUUID().toString(); - Assert.assertEquals(decimal, descriptor.setProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE, string)); + Assert.assertEquals(decimal, descriptor.setPrimitiveProperty(string)); Assert.assertEquals(string, JavaBeanSerializeUtil.deserialize(descriptor)); } @@ -73,7 +73,7 @@ public void testSerialize_Array() throws Exception { Assert.assertEquals(int.class.getName(), descriptor.getClassName()); for (int i = 0; i < array.length; i++) { Assert.assertEquals(array[i], - ((JavaBeanDescriptor) descriptor.getProperty(i)).getProperty(JavaBeanDescriptor.PRIMITIVE_PROPERTY_VALUE)); + ((JavaBeanDescriptor) descriptor.getProperty(i)).getPrimitiveProperty()); } int[][] second = {{1, 2}, {3, 4}}; @@ -85,7 +85,7 @@ public void testSerialize_Array() throws Exception { JavaBeanDescriptor item = (((JavaBeanDescriptor)descriptor.getProperty(i))); Assert.assertTrue(item.isArrayType()); Assert.assertEquals(int.class.getName(), item.getClassName()); - Assert.assertEquals(second[i][j], ((JavaBeanDescriptor)item.getProperty(j)).getPrimitive()); + Assert.assertEquals(second[i][j], ((JavaBeanDescriptor)item.getProperty(j)).getPrimitiveProperty()); } } @@ -179,14 +179,14 @@ static void assertEqualsEnum(Enum expected, Object obj) { JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; Assert.assertTrue(descriptor.isEnumType()); Assert.assertEquals(expected.getClass().getName(), descriptor.getClassName()); - Assert.assertEquals(expected.name(), descriptor.getProperty(JavaBeanDescriptor.ENUM_PROPERTY_NAME)); + Assert.assertEquals(expected.name(), descriptor.getEnumPropertyName()); } static void assertEqualsPrimitive(Object expected, Object obj) { if (expected == null) { return; } JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; Assert.assertTrue(descriptor.isPrimitiveType()); - Assert.assertEquals(expected, descriptor.getPrimitive()); + Assert.assertEquals(expected, descriptor.getPrimitiveProperty()); } static void assertEqualsBigPerson(BigPerson person, Object obj) { From 0e3b0073886c46c6899302b1927054c052900889 Mon Sep 17 00:00:00 2001 From: kimi Date: Wed, 26 Dec 2012 14:02:48 +0800 Subject: [PATCH 080/200] =?UTF-8?q?DUBBO-627=20=E8=A1=A5=E5=85=85=E5=8D=95?= =?UTF-8?q?=E5=85=83=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/common/beanutil/Bean.java | 75 ++++++++++++++++ .../beanutil/JavaBeanSerializeUtilTest.java | 88 +++++++++++++++++++ 2 files changed, 163 insertions(+) create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/Bean.java diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/Bean.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/Bean.java new file mode 100644 index 000000000000..acc896b3394e --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/Bean.java @@ -0,0 +1,75 @@ +package com.alibaba.dubbo.common.beanutil; + +import java.util.Collection; +import java.util.Date; +import java.util.Map; + +import com.alibaba.dubbo.common.model.person.FullAddress; +import com.alibaba.dubbo.common.model.person.PersonStatus; +import com.alibaba.dubbo.common.model.person.Phone; + +/** + * @author kimi + */ +public class Bean { + + private Class type; + + private PersonStatus status; + + private Date date; + + private Phone[] array; + + private Collection collection; + + private Map addresses; + + public Class getType() { + return type; + } + + public void setType(Class type) { + this.type = type; + } + + public PersonStatus getStatus() { + return status; + } + + public void setStatus(PersonStatus status) { + this.status = status; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public Phone[] getArray() { + return array; + } + + public void setArray(Phone[] array) { + this.array = array; + } + + public Collection getCollection() { + return collection; + } + + public void setCollection(Collection collection) { + this.collection = collection; + } + + public Map getAddresses() { + return addresses; + } + + public void setAddresses(Map addresses) { + this.addresses = addresses; + } +} diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java index 9c11c1aa2394..6f80b6ba14be 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java @@ -18,7 +18,10 @@ import java.lang.reflect.Array; import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Collection; import java.util.Date; +import java.util.HashMap; +import java.util.Map; import java.util.UUID; import org.junit.Test; @@ -175,6 +178,91 @@ public void test_Circular_Reference() throws Exception { assertEqualsPrimitive(child.getAge(), childDescriptor.getProperty("age")); } + @Test + public void testBeanSerialize() throws Exception { + Bean bean = new Bean(); + bean.setDate(new Date()); + bean.setStatus(PersonStatus.ENABLED); + bean.setType(Bean.class); + bean.setArray(new Phone[]{}); + + Collection collection = new ArrayList(); + bean.setCollection(collection); + Phone phone = new Phone(); + collection.add(phone); + + Map map = new HashMap(); + FullAddress address = new FullAddress(); + map.put("first", address); + bean.setAddresses(map); + + JavaBeanDescriptor descriptor = JavaBeanSerializeUtil.serialize(bean, JavaBeanAccessor.METHOD); + Assert.assertTrue(descriptor.isBeanType()); + assertEqualsPrimitive(bean.getDate(), descriptor.getProperty("date")); + assertEqualsEnum(bean.getStatus(), descriptor.getProperty("status")); + Assert.assertTrue(((JavaBeanDescriptor)descriptor.getProperty("type")).isClassType()); + Assert.assertEquals(Bean.class.getName(), ((JavaBeanDescriptor)descriptor.getProperty("type")).getClassNameProperty()); + Assert.assertTrue(((JavaBeanDescriptor)descriptor.getProperty("array")).isArrayType()); + Assert.assertEquals(0, ((JavaBeanDescriptor)descriptor.getProperty("array")).propertySize()); + + JavaBeanDescriptor property = (JavaBeanDescriptor)descriptor.getProperty("collection"); + Assert.assertTrue(property.isCollectionType()); + Assert.assertEquals(1, property.propertySize()); + property = (JavaBeanDescriptor)property.getProperty(0); + Assert.assertTrue(property.isBeanType()); + Assert.assertEquals(Phone.class.getName(), property.getClassName()); + Assert.assertEquals(0, property.propertySize()); + + property = (JavaBeanDescriptor)descriptor.getProperty("addresses"); + Assert.assertTrue(property.isMapType()); + Assert.assertEquals(bean.getAddresses().getClass().getName(), property.getClassName()); + Assert.assertEquals(1, property.propertySize()); + + + Map.Entry entry = property.iterator().next(); + Assert.assertTrue(((JavaBeanDescriptor)entry.getKey()).isPrimitiveType()); + Assert.assertEquals("first", ((JavaBeanDescriptor)entry.getKey()).getPrimitiveProperty()); + + Assert.assertTrue(((JavaBeanDescriptor)entry.getValue()).isBeanType()); + Assert.assertEquals(FullAddress.class.getName(), ((JavaBeanDescriptor)entry.getValue()).getClassName()); + Assert.assertEquals(0, ((JavaBeanDescriptor)entry.getValue()).propertySize()); + } + + @Test + public void testDeserializeBean() throws Exception { + Bean bean = new Bean(); + bean.setDate(new Date()); + bean.setStatus(PersonStatus.ENABLED); + bean.setType(Bean.class); + bean.setArray(new Phone[]{}); + + Collection collection = new ArrayList(); + bean.setCollection(collection); + Phone phone = new Phone(); + collection.add(phone); + + Map map = new HashMap(); + FullAddress address = new FullAddress(); + map.put("first", address); + bean.setAddresses(map); + + JavaBeanDescriptor beanDescriptor = JavaBeanSerializeUtil.serialize(bean, JavaBeanAccessor.METHOD); + Object deser = JavaBeanSerializeUtil.deserialize(beanDescriptor); + Assert.assertTrue(deser instanceof Bean); + Bean deserBean = (Bean)deser; + Assert.assertEquals(bean.getDate(), deserBean.getDate()); + Assert.assertEquals(bean.getStatus(), deserBean.getStatus()); + Assert.assertEquals(bean.getType(), deserBean.getType()); + Assert.assertEquals(bean.getCollection().size(), deserBean.getCollection().size()); + Assert.assertEquals(bean.getCollection().iterator().next().getClass(), + deserBean.getCollection().iterator().next().getClass()); + Assert.assertEquals(bean.getAddresses().size(), deserBean.getAddresses().size()); + Assert.assertEquals(bean.getAddresses().entrySet().iterator().next().getKey(), + deserBean.getAddresses().entrySet().iterator().next().getKey()); + Assert.assertEquals(bean.getAddresses().entrySet().iterator().next().getValue().getClass(), + deserBean.getAddresses().entrySet().iterator().next().getValue().getClass()); + } + static void assertEqualsEnum(Enum expected, Object obj) { JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; Assert.assertTrue(descriptor.isEnumType()); From 645152af6f574ebc053becb4e11d1a946fa7899c Mon Sep 17 00:00:00 2001 From: kimi Date: Wed, 26 Dec 2012 16:40:08 +0800 Subject: [PATCH 081/200] =?UTF-8?q?DUBBO-627=20=E4=BD=BF=E7=94=A8=20JavaBe?= =?UTF-8?q?anSerializationUtil=20=E5=AE=9E=E7=8E=B0=E6=B3=9B=E5=8C=96?= =?UTF-8?q?=E8=B0=83=E7=94=A8=E6=88=96=E6=B3=9B=E5=8C=96=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/alibaba/dubbo/common/Constants.java | 2 + .../common/beanutil/JavaBeanDescriptor.java | 14 +- .../dubbo/config/GenericServiceTest.java | 121 +++++++++++++++++- .../dubbo/rpc/filter/GenericFilter.java | 20 +++ .../dubbo/rpc/filter/GenericImplFilter.java | 47 ++++++- .../dubbo/rpc/support/ProtocolUtils.java | 7 +- 6 files changed, 197 insertions(+), 14 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java index 5cdccf1f713a..7909a7e59e2e 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -577,6 +577,8 @@ public class Constants { public static final String GENERIC_SERIALIZATION_DEFAULT = "true"; + public static final String GENERIC_SERIALIZATION_BEAN = "bean"; + /* * private Constants(){ } */ diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java index 28fe8a64ab35..376ebb43ff49 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanDescriptor.java @@ -61,12 +61,14 @@ public final class JavaBeanDescriptor implements Serializable, Iterable properties = new LinkedHashMap(); + public JavaBeanDescriptor() {} + public JavaBeanDescriptor(String className, int type) { notEmpty(className, "class name is empty"); if (!isValidType(type)) { @@ -79,6 +81,14 @@ public JavaBeanDescriptor(String className, int type) { this.type = type; } + public void setClassName(String className) { + this.className = className; + } + + public void setType(int type) { + this.type = type; + } + public boolean isClassType() { return TYPE_CLASS == type; } diff --git a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/GenericServiceTest.java b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/GenericServiceTest.java index c17c93a93c7a..6fced8541ca8 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/GenericServiceTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/GenericServiceTest.java @@ -21,13 +21,18 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; import org.junit.Assert; import org.junit.Test; import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.beanutil.JavaBeanAccessor; +import com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor; +import com.alibaba.dubbo.common.beanutil.JavaBeanSerializeUtil; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.serialize.Serialization; +import com.alibaba.dubbo.common.utils.ReflectUtils; import com.alibaba.dubbo.config.api.DemoException; import com.alibaba.dubbo.config.api.DemoService; import com.alibaba.dubbo.config.api.User; @@ -37,11 +42,11 @@ /** * GenericServiceTest - * + * * @author william.liangf */ public class GenericServiceTest { - + @Test public void testGenericServiceException() { ServiceConfig service = new ServiceConfig(); @@ -50,8 +55,9 @@ public void testGenericServiceException() { service.setProtocol(new ProtocolConfig("dubbo", 29581)); service.setInterface(DemoService.class.getName()); service.setRef(new GenericService() { + public Object $invoke(String method, String[] parameterTypes, Object[] args) - throws GenericException { + throws GenericException { if ("sayName".equals(method)) { return "Generic " + args[0]; } @@ -117,7 +123,7 @@ public void testGenericReferenceException() { user.put("class", "com.alibaba.dubbo.config.api.User"); user.put("name", "actual.provider"); users.add(user); - users = (List>) genericService.$invoke("getUsers", new String[] {List.class.getName()}, new Object[] {users}); + users = (List>) genericService.$invoke("getUsers", new String[]{List.class.getName()}, new Object[]{users}); Assert.assertEquals(1, users.size()); Assert.assertEquals("actual.provider", users.get(0).get("name")); } finally { @@ -196,4 +202,111 @@ public void testGenericSerializationJava() throws Exception { } } + @Test + public void testGenericInvokeWithBeanSerialization() throws Exception { + ServiceConfig service = new ServiceConfig(); + service.setApplication(new ApplicationConfig("bean-provider")); + service.setInterface(DemoService.class); + service.setRegistry(new RegistryConfig("N/A")); + DemoServiceImpl impl = new DemoServiceImpl(); + service.setRef(impl); + service.setProtocol(new ProtocolConfig("dubbo", 29581)); + service.export(); + ReferenceConfig reference = null; + try { + reference = new ReferenceConfig(); + reference.setApplication(new ApplicationConfig("bean-consumer")); + reference.setInterface(DemoService.class); + reference.setUrl("dubbo://127.0.0.1:29581?scope=remote"); + reference.setGeneric(Constants.GENERIC_SERIALIZATION_BEAN); + GenericService genericService = reference.get(); + User user = new User(); + user.setName("zhangsan"); + List users = new ArrayList(); + users.add(user); + Object result = genericService.$invoke("getUsers", new String[]{ReflectUtils.getName(List.class)}, new Object[]{JavaBeanSerializeUtil.serialize(users, JavaBeanAccessor.METHOD)}); + Assert.assertTrue(result instanceof JavaBeanDescriptor); + JavaBeanDescriptor descriptor = (JavaBeanDescriptor) result; + Assert.assertTrue(descriptor.isCollectionType()); + Assert.assertEquals(1, descriptor.propertySize()); + descriptor = (JavaBeanDescriptor) descriptor.getProperty(0); + Assert.assertTrue(descriptor.isBeanType()); + Assert.assertEquals(user.getName(), ((JavaBeanDescriptor) descriptor.getProperty("name")).getPrimitiveProperty()); + } finally { + if (reference != null) { + reference.destroy(); + } + service.unexport(); + } + } + + protected static class GenericParameter { + + String method; + + String[] parameterTypes; + + Object[] arguments; + } + + @Test + public void testGenericImplementationWithBeanSerialization() throws Exception { + final AtomicReference reference = new AtomicReference(); + ServiceConfig service = new ServiceConfig(); + service.setApplication(new ApplicationConfig("bean-provider")); + service.setRegistry(new RegistryConfig("N/A")); + service.setProtocol(new ProtocolConfig("dubbo", 29581)); + service.setInterface(DemoService.class.getName()); + service.setRef(new GenericService() { + + public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException { + if ("getUsers".equals(method)) { + GenericParameter arg = new GenericParameter(); + arg.method = method; + arg.parameterTypes = parameterTypes; + arg.arguments = args; + reference.set(arg); + return args[0]; + } + return args; + } + }); + service.export(); + ReferenceConfig ref = null; + try { + ref = new ReferenceConfig(); + ref.setApplication(new ApplicationConfig("bean-consumer")); + ref.setInterface(DemoService.class); + ref.setUrl("dubbo://127.0.0.1:29581?scope=remote&generic=bean"); + DemoService demoService = ref.get(); + User user = new User(); + user.setName("zhangsan"); + List users = new ArrayList(); + users.add(user); + List result = demoService.getUsers(users); + Assert.assertEquals(users.size(), result.size()); + Assert.assertEquals(user.getName(), result.get(0).getName()); + + GenericParameter gp = (GenericParameter)reference.get(); + Assert.assertEquals("getUsers", gp.method); + Assert.assertEquals(1, gp.parameterTypes.length); + Assert.assertEquals(ReflectUtils.getName(List.class), gp.parameterTypes[0]); + Assert.assertEquals(1, gp.arguments.length); + Assert.assertTrue(gp.arguments[0] instanceof JavaBeanDescriptor); + JavaBeanDescriptor descriptor = (JavaBeanDescriptor)gp.arguments[0]; + Assert.assertTrue(descriptor.isCollectionType()); + Assert.assertEquals(ArrayList.class.getName(), descriptor.getClassName()); + Assert.assertEquals(1, descriptor.propertySize()); + descriptor = (JavaBeanDescriptor)descriptor.getProperty(0); + Assert.assertTrue(descriptor.isBeanType()); + Assert.assertEquals(User.class.getName(), descriptor.getClassName()); + Assert.assertEquals(user.getName(), ((JavaBeanDescriptor)descriptor.getProperty("name")).getPrimitiveProperty()); + } finally { + if (ref != null) { + ref.destroy(); + } + service.unexport(); + } + } + } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericFilter.java index b2aedb048cc0..0ee986aa5bbf 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericFilter.java @@ -19,6 +19,9 @@ import java.lang.reflect.Method; import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.beanutil.JavaBeanAccessor; +import com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor; +import com.alibaba.dubbo.common.beanutil.JavaBeanSerializeUtil; import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; @@ -84,6 +87,21 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { .append(args[i].getClass()).toString()); } } + } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { + for(int i = 0; i < args.length; i++) { + if (args[i] instanceof JavaBeanDescriptor) { + args[i] = JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor)args[i]); + } else { + throw new RpcException( + new StringBuilder(32) + .append("Generic serialization [") + .append(Constants.GENERIC_SERIALIZATION_BEAN) + .append("] only support message type ") + .append(JavaBeanDescriptor.class.getName()) + .append(" and your message type is ") + .append(args[i].getClass().getName()).toString()); + } + } } Result result = invoker.invoke(new RpcInvocation(method, args, inv.getAttachments())); if (result.hasException() @@ -100,6 +118,8 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { } catch (IOException e) { throw new RpcException("Serialize result failed.", e); } + } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { + return new RpcResult(JavaBeanSerializeUtil.serialize(result.getValue(), JavaBeanAccessor.METHOD)); } else { return new RpcResult(PojoUtils.generalize(result.getValue())); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java index 44015dba5a95..50553c31edac 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java @@ -20,6 +20,9 @@ import java.lang.reflect.Method; import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.beanutil.JavaBeanAccessor; +import com.alibaba.dubbo.common.beanutil.JavaBeanDescriptor; +import com.alibaba.dubbo.common.beanutil.JavaBeanSerializeUtil; import com.alibaba.dubbo.common.extension.Activate; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; @@ -61,7 +64,16 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept for (int i = 0; i < parameterTypes.length; i ++) { types[i] = ReflectUtils.getName(parameterTypes[i]); } - Object[] args = PojoUtils.generalize(arguments); + + Object[] args; + if (ProtocolUtils.isBeanGenericSerialization(generic)) { + args = new Object[arguments.length]; + for(int i = 0; i < arguments.length; i++) { + args[i] = JavaBeanSerializeUtil.serialize(arguments[i], JavaBeanAccessor.METHOD); + } + } else { + args = PojoUtils.generalize(arguments); + } invocation2.setMethodName(Constants.$INVOKE); invocation2.setParameterTypes(GENERIC_PARAMETER_TYPES); @@ -72,7 +84,22 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept Object value = result.getValue(); try { Method method = invoker.getInterface().getMethod(methodName, parameterTypes); - return new RpcResult(PojoUtils.realize(value, method.getReturnType(), method.getGenericReturnType())); + if (ProtocolUtils.isBeanGenericSerialization(generic)) { + if (value instanceof JavaBeanDescriptor) { + return new RpcResult(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor)value)); + } else { + throw new RpcException( + new StringBuilder(64) + .append("The type of result value is ") + .append(value.getClass().getName()) + .append(" other than ") + .append(JavaBeanDescriptor.class.getName()) + .append(", and the result is ") + .append(value).toString()); + } + } else { + return new RpcResult(PojoUtils.realize(value, method.getReturnType(), method.getGenericReturnType())); + } } catch (NoSuchMethodException e) { throw new RpcException(e.getMessage(), e); } @@ -122,12 +149,18 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept && invocation.getArguments().length == 3 && ProtocolUtils.isGeneric(generic)) { + Object[] args = (Object[]) invocation.getArguments()[2]; if (ProtocolUtils.isJavaGenericSerialization(generic)) { - Object[] args = (Object[]) invocation.getArguments()[2]; for (Object arg : args) { if (!(byte[].class == arg.getClass())) { - error(arg.getClass().getName()); + error(byte[].class.getName(), arg.getClass().getName()); + } + } + } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { + for(Object arg : args) { + if (!(arg instanceof JavaBeanDescriptor)) { + error(JavaBeanDescriptor.class.getName(), arg.getClass().getName()); } } } @@ -138,15 +171,15 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept return invoker.invoke(invocation); } - private void error(String type) throws RpcException { + private void error(String expected, String actual) throws RpcException { throw new RpcException( new StringBuilder(32) .append("Generic serialization [") .append(Constants.GENERIC_SERIALIZATION_NATIVE_JAVA) .append("] only support message type ") - .append(byte[].class) + .append(expected) .append(" and your message type is ") - .append(type).toString()); + .append(actual).toString()); } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/support/ProtocolUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/support/ProtocolUtils.java index f0440f02c029..837af632da87 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/support/ProtocolUtils.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/support/ProtocolUtils.java @@ -36,7 +36,8 @@ public static boolean isGeneric(String generic) { return generic != null && !"".equals(generic) && (Constants.GENERIC_SERIALIZATION_DEFAULT.equalsIgnoreCase(generic) /* 姝e父鐨勬硾鍖栬皟鐢 */ - || Constants.GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic)); /* 鏀寔java搴忓垪鍖栫殑娴佸紡娉涘寲璋冪敤 */ + || Constants.GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic) /* 鏀寔java搴忓垪鍖栫殑娴佸紡娉涘寲璋冪敤 */ + || Constants.GENERIC_SERIALIZATION_BEAN.equalsIgnoreCase(generic)); } public static boolean isDefaultGenericSerialization(String generic) { @@ -48,4 +49,8 @@ public static boolean isJavaGenericSerialization(String generic) { return isGeneric(generic) && Constants.GENERIC_SERIALIZATION_NATIVE_JAVA.equalsIgnoreCase(generic); } + + public static boolean isBeanGenericSerialization(String generic) { + return isGeneric(generic) && Constants.GENERIC_SERIALIZATION_BEAN.equals(generic); + } } From 4f8ed015f9919be2f102218225b602fde99d3113 Mon Sep 17 00:00:00 2001 From: kimi Date: Sun, 6 Jan 2013 14:36:19 +0800 Subject: [PATCH 082/200] =?UTF-8?q?DUBBO-627=20=E5=A4=84=E7=90=86=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E5=80=BC=E4=B8=BA=20null=20=E7=9A=84=E6=83=85?= =?UTF-8?q?=E5=86=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/dubbo/config/GenericServiceTest.java | 4 ++++ .../java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/GenericServiceTest.java b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/GenericServiceTest.java index 6fced8541ca8..f408f69bc85a 100644 --- a/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/GenericServiceTest.java +++ b/dubbo-config/dubbo-config-api/src/test/java/com/alibaba/dubbo/config/GenericServiceTest.java @@ -268,6 +268,9 @@ public void testGenericImplementationWithBeanSerialization() throws Exception { reference.set(arg); return args[0]; } + if ("sayName".equals(method)) { + return null; + } return args; } }); @@ -301,6 +304,7 @@ public void testGenericImplementationWithBeanSerialization() throws Exception { Assert.assertTrue(descriptor.isBeanType()); Assert.assertEquals(User.class.getName(), descriptor.getClassName()); Assert.assertEquals(user.getName(), ((JavaBeanDescriptor)descriptor.getProperty("name")).getPrimitiveProperty()); + Assert.assertNull(demoService.sayName("zhangsan")); } finally { if (ref != null) { ref.destroy(); diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java index 50553c31edac..31df520c2d1d 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericImplFilter.java @@ -85,7 +85,9 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept try { Method method = invoker.getInterface().getMethod(methodName, parameterTypes); if (ProtocolUtils.isBeanGenericSerialization(generic)) { - if (value instanceof JavaBeanDescriptor) { + if (value == null) { + return new RpcResult(value); + } else if (value instanceof JavaBeanDescriptor) { return new RpcResult(JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor)value)); } else { throw new RpcException( From f489972d43a44aa5dc3edf1c5d4f0c1c38ec05de Mon Sep 17 00:00:00 2001 From: kimi Date: Tue, 8 Jan 2013 13:26:51 +0800 Subject: [PATCH 083/200] =?UTF-8?q?DUBBO-627=20=E5=BA=8F=E5=88=97=E5=8C=96?= =?UTF-8?q?=E6=97=B6=EF=BC=8C=E5=A6=82=E6=9E=9C=E4=B8=BA=20JavaBeanDescrip?= =?UTF-8?q?tor=20=E5=88=99=E7=9B=B4=E6=8E=A5=E8=BF=94=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../beanutil/JavaBeanSerializeUtil.java | 5 +++++ .../beanutil/JavaBeanSerializeUtilTest.java | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java index 14f2deb3526e..42a3b7a9fd89 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java @@ -46,6 +46,9 @@ public static JavaBeanDescriptor serialize(Object obj, JavaBeanAccessor accessor if (obj == null) { return null; } + if (obj instanceof JavaBeanDescriptor) { + return (JavaBeanDescriptor)obj; + } IdentityHashMap cache = new IdentityHashMap(); JavaBeanDescriptor result = createDescriptorIfAbsent(obj, accessor, cache); return result; @@ -72,6 +75,8 @@ private static JavaBeanDescriptor createDescriptorForSerialize(Class cl) { private static JavaBeanDescriptor createDescriptorIfAbsent(Object obj, JavaBeanAccessor accessor, IdentityHashMap cache) { if (cache.containsKey(obj)) { return cache.get(obj); + } else if (obj instanceof JavaBeanDescriptor) { + return (JavaBeanDescriptor)obj; } else { JavaBeanDescriptor result = createDescriptorForSerialize(obj.getClass()); cache.put(obj, result); diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java index 6f80b6ba14be..d033138e5331 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java @@ -263,6 +263,25 @@ public void testDeserializeBean() throws Exception { deserBean.getAddresses().entrySet().iterator().next().getValue().getClass()); } + @Test + @SuppressWarnings("unchecked") + public void testSerializeJavaBeanDescriptor() throws Exception { + JavaBeanDescriptor descriptor = new JavaBeanDescriptor(); + JavaBeanDescriptor result = JavaBeanSerializeUtil.serialize(descriptor); + Assert.assertTrue(descriptor == result); + + Map map = new HashMap(); + map.put("first", descriptor); + result = JavaBeanSerializeUtil.serialize(map); + Assert.assertTrue(result.isMapType()); + Assert.assertEquals(HashMap.class.getName(), result.getClassName()); + Assert.assertEquals(map.size(), result.propertySize()); + Object object = result.iterator().next().getValue(); + Assert.assertTrue(object instanceof JavaBeanDescriptor); + JavaBeanDescriptor actual = (JavaBeanDescriptor)object; + Assert.assertEquals(map.get("first"), actual); + } + static void assertEqualsEnum(Enum expected, Object obj) { JavaBeanDescriptor descriptor = (JavaBeanDescriptor) obj; Assert.assertTrue(descriptor.isEnumType()); From 3dccbc6f5b53bf666ede8a2c7afe1efe93e0922e Mon Sep 17 00:00:00 2001 From: kimi Date: Tue, 8 Jan 2013 13:56:08 +0800 Subject: [PATCH 084/200] =?UTF-8?q?DUBBO-627=20ServiceConfig=20=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E9=85=8D=E7=BD=AE=20generic?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/config/ServiceConfig.java | 26 +++++++++++++++---- .../src/main/resources/META-INF/dubbo.xsd | 5 ++++ .../dubbo/config/spring/ConfigTest.java | 23 ++++++++++++++++ 3 files changed, 49 insertions(+), 5 deletions(-) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java index 77486f4c8cf3..2d420fdd60d9 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java @@ -46,6 +46,7 @@ import com.alibaba.dubbo.rpc.ProxyFactory; import com.alibaba.dubbo.rpc.cluster.ConfiguratorFactory; import com.alibaba.dubbo.rpc.service.GenericService; +import com.alibaba.dubbo.rpc.support.ProtocolUtils; /** * ServiceConfig @@ -87,7 +88,7 @@ public class ServiceConfig extends AbstractServiceConfig { private transient volatile boolean unexported; - private transient volatile boolean generic; + private volatile String generic; public ServiceConfig() { } @@ -191,7 +192,9 @@ protected synchronized void doExport() { } if (ref instanceof GenericService) { interfaceClass = GenericService.class; - generic = true; + if (StringUtils.isEmpty(generic)) { + generic = Boolean.TRUE.toString(); + } } else { try { interfaceClass = Class.forName(interfaceName, true, Thread.currentThread() @@ -201,7 +204,7 @@ protected synchronized void doExport() { } checkInterfaceAndMethods(interfaceClass, methods); checkRef(); - generic = false; + generic = Boolean.FALSE.toString(); } if(local !=null){ if(local=="true"){ @@ -414,8 +417,8 @@ private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List r } // end of methods for } - if (generic) { - map.put("generic", String.valueOf(true)); + if (ProtocolUtils.isGeneric(generic)) { + map.put("generic", generic); map.put("methods", Constants.ANY_VALUE); } else { String revision = Version.getVersion(interfaceClass, version); @@ -612,6 +615,19 @@ public ProviderConfig getProvider() { return provider; } + public void setGeneric(String generic) { + if (StringUtils.isEmpty(generic)) { return; } + if (ProtocolUtils.isGeneric(generic)) { + this.generic = generic; + } else { + throw new IllegalArgumentException("Unsupported generic type " + generic); + } + } + + public String getGeneric() { + return generic; + } + public void setProvider(ProviderConfig provider) { this.provider = provider; } diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index 633046bd5d52..94809fd480f9 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -1051,6 +1051,11 @@ + + + + + diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java index 18110a15a173..a5dfa1bc1787 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java @@ -30,6 +30,7 @@ import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.support.ClassPathXmlApplicationContext; +import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.extension.ExtensionLoader; import com.alibaba.dubbo.common.utils.NetUtils; @@ -939,6 +940,28 @@ public void testReferGenericExport() throws Exception { } } + @Test + public void testGenericServiceConfig() throws Exception { + ServiceConfig service = new ServiceConfig(); + service.setApplication(new ApplicationConfig("test")); + service.setRegistry(new RegistryConfig("N/A")); + service.setInterface(DemoService.class.getName()); + service.setGeneric(Constants.GENERIC_SERIALIZATION_BEAN); + service.setRef(new GenericService(){ + + public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException { + return null; + } + }); + try { + service.export(); + URL url = service.getExportedUrls().get(0); + Assert.assertEquals(Constants.GENERIC_SERIALIZATION_BEAN, url.getParameter(Constants.GENERIC_KEY)); + } finally { + service.unexport(); + } + } + private static void unexportService(ServiceConfig config) { if (config != null) { config.unexport(); From e8970a0e7421f1166847b69a06ba094971ddce10 Mon Sep 17 00:00:00 2001 From: kimi Date: Wed, 9 Jan 2013 10:12:47 +0800 Subject: [PATCH 085/200] =?UTF-8?q?DUBBO-627=20=E4=B8=BAServiceConfig=20?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E9=85=8D=E7=BD=AE=20generic=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95=EF=BC=8C=E8=A6=86?= =?UTF-8?q?=E7=9B=96=E4=BD=BF=E7=94=A8=20xml=20=E9=85=8D=E7=BD=AE=E6=97=B6?= =?UTF-8?q?=20url=20=E4=B8=AD=E6=98=AF=E5=90=A6=E5=B8=A6=E4=B8=8A=E4=BA=86?= =?UTF-8?q?=20=E6=AD=A3=E7=A1=AE=E7=9A=84=20generic=20=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/config/spring/ConfigTest.java | 14 ++++++- .../config/spring/GenericDemoService.java | 14 +++++++ .../dubbo/config/spring/generic-export.xml | 37 +++++++++++++++++++ 3 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/GenericDemoService.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/resources/com/alibaba/dubbo/config/spring/generic-export.xml diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java index a5dfa1bc1787..fc50faa0ec40 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java @@ -917,7 +917,6 @@ public void testReferGenericExport() throws Exception { sc.setInterface(DemoService.class.getName()); sc.setRef(new GenericService() { - @Override public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException { return null; } @@ -962,6 +961,19 @@ public void testGenericServiceConfig() throws Exception { } } + @Test + public void testGenericServiceConfigThroughSpring() throws Exception { + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/generic-export.xml"); + try { + ctx.start(); + ServiceConfig serviceConfig = (ServiceConfig) ctx.getBean("dubboDemoService"); + URL url = (URL)serviceConfig.getExportedUrls().get(0); + Assert.assertEquals(Constants.GENERIC_SERIALIZATION_BEAN, url.getParameter(Constants.GENERIC_KEY)); + } finally { + ctx.destroy(); + } + } + private static void unexportService(ServiceConfig config) { if (config != null) { config.unexport(); diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/GenericDemoService.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/GenericDemoService.java new file mode 100644 index 000000000000..6fa81cda2d38 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/GenericDemoService.java @@ -0,0 +1,14 @@ +package com.alibaba.dubbo.config.spring; + +import com.alibaba.dubbo.rpc.service.GenericException; +import com.alibaba.dubbo.rpc.service.GenericService; + +/** + * @author kimi + */ +public class GenericDemoService implements GenericService { + + public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException { + return null; + } +} diff --git a/dubbo-config/dubbo-config-spring/src/test/resources/com/alibaba/dubbo/config/spring/generic-export.xml b/dubbo-config/dubbo-config-spring/src/test/resources/com/alibaba/dubbo/config/spring/generic-export.xml new file mode 100644 index 000000000000..7126cf5d4c3a --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/resources/com/alibaba/dubbo/config/spring/generic-export.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file From e3f8af756d3de9e5ed00c453e804cec548a33571 Mon Sep 17 00:00:00 2001 From: kimi Date: Wed, 9 Jan 2013 10:47:33 +0800 Subject: [PATCH 086/200] DUBBO-627 fix bug --- .../common/beanutil/JavaBeanSerializeUtil.java | 2 +- .../common/beanutil/JavaBeanSerializeUtilTest.java | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java index 42a3b7a9fd89..0052d74a27ae 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtil.java @@ -101,7 +101,7 @@ private static void serializeInternal(JavaBeanDescriptor descriptor, Object obj, for (int i = 0; i < len; i++) { Object item = Array.get(obj, i); if (item == null) { - descriptor.setProperty(i++, null); + descriptor.setProperty(i, null); } else { JavaBeanDescriptor itemDescriptor = createDescriptorIfAbsent(item, accessor, cache); descriptor.setProperty(i, itemDescriptor); diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java index d033138e5331..99557e502a16 100644 --- a/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/beanutil/JavaBeanSerializeUtilTest.java @@ -79,6 +79,19 @@ public void testSerialize_Array() throws Exception { ((JavaBeanDescriptor) descriptor.getProperty(i)).getPrimitiveProperty()); } + Integer[] integers = new Integer[]{1, 2, 3, 4, null, null, null}; + descriptor = JavaBeanSerializeUtil.serialize(integers, JavaBeanAccessor.METHOD); + Assert.assertTrue(descriptor.isArrayType()); + Assert.assertEquals(Integer.class.getName(), descriptor.getClassName()); + Assert.assertEquals(integers.length, descriptor.propertySize()); + for(int i = 0; i < integers.length; i++) { + if (integers[i] == null) { + Assert.assertTrue(integers[i] == descriptor.getProperty(i)); + } else { + Assert.assertEquals(integers[i], ((JavaBeanDescriptor)descriptor.getProperty(i)).getPrimitiveProperty()); + } + } + int[][] second = {{1, 2}, {3, 4}}; descriptor = JavaBeanSerializeUtil.serialize(second, JavaBeanAccessor.METHOD); Assert.assertTrue(descriptor.isArrayType()); From b90c3b393ab7f57e371383da83ccbc49fe2cde02 Mon Sep 17 00:00:00 2001 From: kimi Date: Fri, 11 Jan 2013 11:22:08 +0800 Subject: [PATCH 087/200] DUBBO-627 fix bug --- .../main/java/com/alibaba/dubbo/rpc/filter/GenericFilter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericFilter.java index 0ee986aa5bbf..efd324197f45 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/GenericFilter.java @@ -52,7 +52,7 @@ public Result invoke(Invoker invoker, Invocation inv) throws RpcException { if (inv.getMethodName().equals(Constants.$INVOKE) && inv.getArguments() != null && inv.getArguments().length == 3 - && ! invoker.getUrl().getParameter(Constants.GENERIC_KEY, false)) { + && ! ProtocolUtils.isGeneric(invoker.getUrl().getParameter(Constants.GENERIC_KEY))) { String name = ((String) inv.getArguments()[0]).trim(); String[] types = (String[]) inv.getArguments()[1]; Object[] args = (Object[]) inv.getArguments()[2]; From 3416402ab5734e120489718b0a873c32125ef38c Mon Sep 17 00:00:00 2001 From: kimi Date: Fri, 11 Jan 2013 15:08:54 +0800 Subject: [PATCH 088/200] =?UTF-8?q?DUBBO-627=20=E6=B7=BB=E5=8A=A0=E5=8D=95?= =?UTF-8?q?=E5=85=83=E6=B5=8B=E8=AF=95=EF=BC=8C=E8=A6=86=E7=9B=96=20export?= =?UTF-8?q?=20=E6=97=B6=E6=98=AF=E5=90=A6=E8=83=BD=E6=8A=8A=20generic=20?= =?UTF-8?q?=E7=9A=84=E9=85=8D=E7=BD=AE=E5=8F=91=E5=B8=83=E5=88=B0=20regist?= =?UTF-8?q?ry=20=E4=B8=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/config/spring/ConfigTest.java | 12 +++- .../config/spring/registry/MockRegistry.java | 67 +++++++++++++++++++ .../spring/registry/MockRegistryFactory.java | 31 +++++++++ ...com.alibaba.dubbo.registry.RegistryFactory | 1 + 4 files changed, 109 insertions(+), 2 deletions(-) create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/registry/MockRegistry.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/registry/MockRegistryFactory.java create mode 100644 dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java index fc50faa0ec40..71d81d3d7af7 100644 --- a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/ConfigTest.java @@ -23,6 +23,7 @@ import static org.junit.Assert.fail; import static org.junit.matchers.JUnitMatchers.containsString; +import java.util.Collection; import java.util.List; import org.junit.Test; @@ -50,6 +51,10 @@ import com.alibaba.dubbo.config.spring.filter.MockFilter; import com.alibaba.dubbo.config.spring.impl.DemoServiceImpl; import com.alibaba.dubbo.config.spring.impl.HelloServiceImpl; +import com.alibaba.dubbo.config.spring.registry.MockRegistry; +import com.alibaba.dubbo.config.spring.registry.MockRegistryFactory; +import com.alibaba.dubbo.registry.Registry; +import com.alibaba.dubbo.registry.RegistryFactory; import com.alibaba.dubbo.registry.RegistryService; import com.alibaba.dubbo.rpc.Exporter; import com.alibaba.dubbo.rpc.Filter; @@ -943,7 +948,7 @@ public void testReferGenericExport() throws Exception { public void testGenericServiceConfig() throws Exception { ServiceConfig service = new ServiceConfig(); service.setApplication(new ApplicationConfig("test")); - service.setRegistry(new RegistryConfig("N/A")); + service.setRegistry(new RegistryConfig("mock://localhost")); service.setInterface(DemoService.class.getName()); service.setGeneric(Constants.GENERIC_SERIALIZATION_BEAN); service.setRef(new GenericService(){ @@ -954,9 +959,12 @@ public void testGenericServiceConfig() throws Exception { }); try { service.export(); - URL url = service.getExportedUrls().get(0); + Collection collection = MockRegistryFactory.getCachedRegistry(); + MockRegistry registry = (MockRegistry)collection.iterator().next(); + URL url = registry.getRegistered().get(0); Assert.assertEquals(Constants.GENERIC_SERIALIZATION_BEAN, url.getParameter(Constants.GENERIC_KEY)); } finally { + MockRegistryFactory.cleanCachedRegistry(); service.unexport(); } } diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/registry/MockRegistry.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/registry/MockRegistry.java new file mode 100644 index 000000000000..5ac78b31d68e --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/registry/MockRegistry.java @@ -0,0 +1,67 @@ +package com.alibaba.dubbo.config.spring.registry; + +import java.util.ArrayList; +import java.util.List; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.registry.NotifyListener; +import com.alibaba.dubbo.registry.Registry; + +/** + * @author kimi + */ +public class MockRegistry implements Registry { + + private URL url; + + private List registered = new ArrayList(); + + private List subscribered = new ArrayList(); + + public List getRegistered() { + return registered; + } + + public List getSubscribered() { + return subscribered; + } + + public MockRegistry(URL url) { + if (url == null) { + throw new NullPointerException(); + } + this.url = url; + } + + public URL getUrl() { + return url; + } + + public boolean isAvailable() { + return true; + } + + public void destroy() { + + } + + public void register(URL url) { + registered.add(url); + } + + public void unregister(URL url) { + registered.remove(url); + } + + public void subscribe(URL url, NotifyListener listener) { + subscribered.add(url); + } + + public void unsubscribe(URL url, NotifyListener listener) { + subscribered.remove(url); + } + + public List lookup(URL url) { + return null; + } +} diff --git a/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/registry/MockRegistryFactory.java b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/registry/MockRegistryFactory.java new file mode 100644 index 000000000000..d7178fcde392 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/java/com/alibaba/dubbo/config/spring/registry/MockRegistryFactory.java @@ -0,0 +1,31 @@ +package com.alibaba.dubbo.config.spring.registry; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.registry.Registry; +import com.alibaba.dubbo.registry.RegistryFactory; + +/** + * @author kimi + */ +public class MockRegistryFactory implements RegistryFactory { + + private static final Map registries = new HashMap(); + + public Registry getRegistry(URL url) { + MockRegistry registry = new MockRegistry(url); + registries.put(url, registry); + return registry; + } + + public static Collection getCachedRegistry() { + return registries.values(); + } + + public static void cleanCachedRegistry() { + registries.clear(); + } +} diff --git a/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory b/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory new file mode 100644 index 000000000000..a6fed7ef8106 --- /dev/null +++ b/dubbo-config/dubbo-config-spring/src/test/resources/META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory @@ -0,0 +1 @@ +mock=com.alibaba.dubbo.config.spring.registry.MockRegistryFactory \ No newline at end of file From 95528332b51381aaa90d6e44fad384ec3cb697b7 Mon Sep 17 00:00:00 2001 From: wangchangbing Date: Fri, 11 Jan 2013 15:42:40 +0800 Subject: [PATCH 089/200] bugfix:DUBBO-628 --- .../alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java index 2aad947ab4d0..2c13a761ab4d 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java @@ -125,6 +125,7 @@ protected void doSubscribe(final URL url, final NotifyListener listener) { listeners.putIfAbsent(listener, new ChildListener() { public void childChanged(String parentPath, List currentChilds) { for (String child : currentChilds) { + child = URL.decode(child); if (! anyServices.contains(child)) { anyServices.add(child); subscribe(url.setPath(child).addParameters(Constants.INTERFACE_KEY, child, @@ -138,8 +139,9 @@ public void childChanged(String parentPath, List currentChilds) { zkClient.create(root, false); List services = zkClient.addChildListener(root, zkListener); if (services != null && services.size() > 0) { - anyServices.addAll(services); for (String service : services) { + service = URL.decode(service); + anyServices.add(service); subscribe(url.setPath(service).addParameters(Constants.INTERFACE_KEY, service, Constants.CHECK_KEY, String.valueOf(false)), listener); } From 6ebd62462cfa5980739e68c7c4790f163f16e11d Mon Sep 17 00:00:00 2001 From: JoeCao Date: Tue, 26 Feb 2013 17:42:11 +0800 Subject: [PATCH 090/200] =?UTF-8?q?=E4=BF=AE=E6=94=B9Redis=E6=B3=A8?= =?UTF-8?q?=E5=86=8C=E4=B8=AD=E5=BF=83=E5=AE=95=E6=9C=BA=E6=97=B6=EF=BC=8C?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=8D=A0=E7=94=A8cpu=E9=AB=98=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/dubbo/registry/redis/RedisRegistry.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java b/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java index efa9c33e35b3..b754d9533050 100644 --- a/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java +++ b/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java @@ -604,6 +604,8 @@ public void run() { } } catch (Throwable t) { // 閲嶈瘯鍙︿竴鍙 logger.warn("Failed to subscribe service from redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t); + // 濡傛灉鍦ㄥ崟鍙皉edis鐨勬儏鍐典笅锛岄渶瑕佷紤鎭竴浼氾紝閬垮厤绌鸿浆鍗犵敤杩囧cpu璧勬簮 + sleep(reconnectPeriod); } } } catch (Throwable t) { From 935fe309267dab0b555d7308263f59fe88222434 Mon Sep 17 00:00:00 2001 From: JoeCao Date: Tue, 26 Feb 2013 20:53:08 +0800 Subject: [PATCH 091/200] =?UTF-8?q?=E8=A7=A3=E5=86=B3method=E7=9A=84?= =?UTF-8?q?=E9=85=8D=E7=BD=AEexecutes=E5=8F=82=E6=95=B0=E7=9A=84xsd?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/resources/META-INF/dubbo.xsd | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index 94809fd480f9..65df01c96ff9 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -589,6 +589,11 @@ + + + + + From 841f6c2612d049ac0aa8bcbb6a00dad8d77a6fca Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 11 Mar 2013 21:02:08 +0800 Subject: [PATCH 092/200] add ProtectionDomain for dynamicly created class --- .../dubbo/common/compiler/support/JavassistCompiler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/compiler/support/JavassistCompiler.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/compiler/support/JavassistCompiler.java index ff666e262666..cc8f59a656f7 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/compiler/support/JavassistCompiler.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/compiler/support/JavassistCompiler.java @@ -120,7 +120,7 @@ public Class doCompile(String name, String source) throws Throwable { } } } - return cls.toClass(ClassHelper.getCallerClassLoader(getClass()), null); + return cls.toClass(ClassHelper.getCallerClassLoader(getClass()), JavassistCompiler.class.getProtectionDomain()); } } From e4dea029546efe9e7a6184ad528560e62303ce02 Mon Sep 17 00:00:00 2001 From: oldratlee Date: Tue, 5 Mar 2013 20:13:27 +0800 Subject: [PATCH 093/200] =?UTF-8?q?DUBBO-635=20JValidator=E5=9C=A8?= =?UTF-8?q?=E7=B1=BB=E5=90=8D=E7=94=9F=E6=88=90=E7=9A=84=E7=B1=BB=E5=90=8D?= =?UTF-8?q?=E6=9C=89$=EF=BC=8C=E6=9C=89frozen=20class=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/validation/support/jvalidation/JValidator.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/com/alibaba/dubbo/validation/support/jvalidation/JValidator.java b/dubbo-filter/dubbo-filter-validation/src/main/java/com/alibaba/dubbo/validation/support/jvalidation/JValidator.java index 1c84bd17fb80..d0ec6615d357 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/com/alibaba/dubbo/validation/support/jvalidation/JValidator.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/com/alibaba/dubbo/validation/support/jvalidation/JValidator.java @@ -89,7 +89,7 @@ public JValidator(URL url) { } public void validate(String methodName, Class[] parameterTypes, Object[] arguments) throws Exception { - String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName); + String methodClassName = clazz.getName() + "_" + toUpperMethoName(methodName); Class methodClass = null; try { methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); @@ -157,7 +157,7 @@ private static Object getMethodParameterBean(Class clazz, Method method, Obje try { String upperName = toUpperMethoName(method.getName()); String parameterSimpleName = upperName + "Parameter"; - String parameterClassName = clazz.getName() + "$" + parameterSimpleName; + String parameterClassName = clazz.getName() + "_" + parameterSimpleName; Class parameterClass; try { parameterClass = (Class) Class.forName(parameterClassName, true, clazz.getClassLoader()); From 7ddef5ab61dfb868e9d0c683b44f2effaca24df0 Mon Sep 17 00:00:00 2001 From: Jerry Lee Date: Sun, 17 Mar 2013 17:43:29 +0800 Subject: [PATCH 094/200] =?UTF-8?q?DUBBO-625=20=E4=B8=9A=E5=8A=A1=E5=AF=B9?= =?UTF-8?q?=E8=B1=A1=E7=9A=84toString=E6=96=B9=E6=B3=95=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E4=BC=9A=E5=AF=BC=E8=87=B4RemotingInvocationTimeoutScan?= =?UTF-8?q?=E5=A4=B1=E6=95=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/remoting/exchange/Request.java | 101 ++++++++++-------- 1 file changed, 57 insertions(+), 44 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java index 062d0db6c167..33c0072f2876 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/exchange/Request.java @@ -1,42 +1,44 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.remoting.exchange; import java.util.concurrent.atomic.AtomicLong; +import com.alibaba.dubbo.common.utils.StringUtils; + /** * Request. * * @author qian.lei * @author william.liangf */ -public class Request { - - public static final String HEARTBEAT_EVENT = null; - - public static final String READONLY_EVENT = "R"; - +public class Request { + + public static final String HEARTBEAT_EVENT = null; + + public static final String READONLY_EVENT = "R"; + private static final AtomicLong INVOKE_ID = new AtomicLong(0); private final long mId; private String mVersion; - private boolean mTwoWay = true; - + private boolean mTwoWay = true; + private boolean mEvent = false; private boolean mBroken = false; @@ -70,15 +72,15 @@ public boolean isTwoWay() { public void setTwoWay(boolean twoWay) { mTwoWay = twoWay; } - - public boolean isEvent() { - return mEvent; - } - - public void setEvent(String event) { - mEvent = true; - mData = event; - } + + public boolean isEvent() { + return mEvent; + } + + public void setEvent(String event) { + mEvent = true; + mData = event; + } public boolean isBroken() { return mBroken; @@ -95,16 +97,16 @@ public Object getData() { public void setData(Object msg) { mData = msg; } - - public boolean isHeartbeat() { - return mEvent && HEARTBEAT_EVENT == mData; - } - - public void setHeartbeat(boolean isHeartbeat) { - if (isHeartbeat) { - setEvent(HEARTBEAT_EVENT); - } - } + + public boolean isHeartbeat() { + return mEvent && HEARTBEAT_EVENT == mData; + } + + public void setHeartbeat(boolean isHeartbeat) { + if (isHeartbeat) { + setEvent(HEARTBEAT_EVENT); + } + } private static long newId() { // getAndIncrement()澧為暱鍒癕AX_VALUE鏃讹紝鍐嶅闀夸細鍙樹负MIN_VALUE锛岃礋鏁颁篃鍙互鍋氫负ID @@ -114,7 +116,18 @@ private static long newId() { @Override public String toString() { return "Request [id=" + mId + ", version=" + mVersion + ", twoway=" + mTwoWay + ", event=" + mEvent - + ", broken=" + mBroken + ", data=" + (mData == this ? "this" : mData) + "]"; + + ", broken=" + mBroken + ", data=" + (mData == this ? "this" : safeToString(mData)) + "]"; } -} \ No newline at end of file + private static String safeToString(Object data) { + if (data == null) return null; + String dataStr; + try { + dataStr = data.toString(); + } catch (Throwable e) { + dataStr = ""; + } + return dataStr; + } +} From 105a0c7d11d6e96f6ba692751b805a4a522dbd32 Mon Sep 17 00:00:00 2001 From: houqianming Date: Wed, 20 Mar 2013 11:13:59 +0800 Subject: [PATCH 095/200] set ProtectionDomain for newly generated Class --- .../com/alibaba/dubbo/common/bytecode/ClassGenerator.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java index efe08a006a6a..1f1a4cd91e56 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java @@ -18,6 +18,7 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; @@ -288,7 +289,10 @@ public ClassPool getClassPool() { return mPool; } - public Class toClass() + public Class toClass(){ + return toClass(getClass().getClassLoader(), getClass().getProtectionDomain()); + } + public Class toClass(ClassLoader loader, ProtectionDomain pd) { if( mCtc != null ) mCtc.detach(); @@ -334,7 +338,7 @@ public Class toClass() } } } - return mCtc.toClass(); + return mCtc.toClass(loader, pd); } catch(RuntimeException e) { From 5ad73574bdf0f4bbf38ce151a521b3368be48256 Mon Sep 17 00:00:00 2001 From: houqianming Date: Wed, 20 Mar 2013 11:23:30 +0800 Subject: [PATCH 096/200] DUBBO-636 --- .../java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java | 1 + 1 file changed, 1 insertion(+) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java index 1f1a4cd91e56..84b78e50d017 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/bytecode/ClassGenerator.java @@ -292,6 +292,7 @@ public ClassPool getClassPool() { public Class toClass(){ return toClass(getClass().getClassLoader(), getClass().getProtectionDomain()); } + public Class toClass(ClassLoader loader, ProtectionDomain pd) { if( mCtc != null ) From 8bdeb544c199f752fc9c8700eef48675230603e9 Mon Sep 17 00:00:00 2001 From: kiminotes Date: Sat, 10 Aug 2013 11:26:17 +0800 Subject: [PATCH 097/200] =?UTF-8?q?DUBBO-649=20=E8=AE=BF=E9=97=AE=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E6=9C=89=E4=B8=A2=E6=97=A5=E5=BF=97=E7=9A=84=E5=8F=AF?= =?UTF-8?q?=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/rpc/filter/AccessLogFilter.java | 94 ++++++++++--------- 1 file changed, 48 insertions(+), 46 deletions(-) diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/AccessLogFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/AccessLogFilter.java index 49e4ce9635de..2ed19aaf316b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/AccessLogFilter.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/AccessLogFilter.java @@ -1,47 +1,48 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.alibaba.dubbo.rpc.filter; -import java.io.File; -import java.io.FileWriter; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.extension.Activate; -import com.alibaba.dubbo.common.json.JSON; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.common.utils.ConcurrentHashSet; -import com.alibaba.dubbo.common.utils.ConfigUtils; -import com.alibaba.dubbo.common.utils.NamedThreadFactory; -import com.alibaba.dubbo.rpc.Filter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; +import java.io.File; +import java.io.FileWriter; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.extension.Activate; +import com.alibaba.dubbo.common.json.JSON; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.ConcurrentHashSet; +import com.alibaba.dubbo.common.utils.ConfigUtils; +import com.alibaba.dubbo.common.utils.NamedThreadFactory; +import com.alibaba.dubbo.rpc.Filter; +import com.alibaba.dubbo.rpc.Invocation; +import com.alibaba.dubbo.rpc.Invoker; +import com.alibaba.dubbo.rpc.Result; +import com.alibaba.dubbo.rpc.RpcContext; +import com.alibaba.dubbo.rpc.RpcException; /** * 璁板綍Service鐨凙ccess Log銆 @@ -57,7 +58,7 @@ * * * @author ding.lid - */ + */ @Activate(group = Constants.PROVIDER, value = Constants.ACCESS_LOG_KEY) public class AccessLogFilter implements Filter { @@ -105,15 +106,16 @@ public void run() { } FileWriter writer = new FileWriter(file, true); try { - for (String msg : logSet) { - writer.write(msg); + for(Iterator iterator = logSet.iterator(); + iterator.hasNext(); + iterator.remove()) { + writer.write(iterator.next()); writer.write("\r\n"); } writer.flush(); } finally { writer.close(); } - logSet.clear(); } catch (Exception e) { logger.error(e.getMessage(), e); } From 9109e9183349884018abd15e5d15b4d5b70c8190 Mon Sep 17 00:00:00 2001 From: bohr Date: Fri, 13 Sep 2013 18:35:50 +0800 Subject: [PATCH 098/200] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=B3=A8=E5=86=8C?= =?UTF-8?q?=E4=B8=AD=E5=BF=83=E4=B8=BAzookeeper=EF=BC=8C=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E6=8E=A7=E5=88=B6=E5=8F=B0=E5=88=A0=E9=99=A4=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 杩欎釜闂鏄洜涓猴紝鍦ㄥ惎鐢ㄨ矾鐢辫鍒欐椂锛屽幓鎺変簡enabled鍙傛暟銆傚湪鍒犻櫎璺敱瑙勫垯鏃禦oute.toUrl鏂规硶浼氬缁堝姞涓奺nabled鍙傛暟锛岃繖鏍峰鑷村垹闄ゆ椂zookeeper 涓璸ath涓嶅瓨鍦紝鍒犻櫎澶辫触銆 --- .../dubbo/governance/service/impl/RouteServiceImpl.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/RouteServiceImpl.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/RouteServiceImpl.java index 8907888938c0..152b3d569573 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/RouteServiceImpl.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/RouteServiceImpl.java @@ -72,8 +72,8 @@ public void enableRoute(Long id) { return; } - URL newRoute = oldRoute.removeParameter("enabled"); - registryService.unregister(oldRoute); + registryService.unregister(oldRoute); + URL newRoute= oldRoute.addParameter("enabled", true); registryService.register(newRoute); } From fcb1ca6ace7e317fc8c7d58768ceab723c7ba47d Mon Sep 17 00:00:00 2001 From: bohr Date: Thu, 26 Sep 2013 15:58:37 +0800 Subject: [PATCH 099/200] =?UTF-8?q?=E5=8E=BB=E6=8E=89ZookeeperRegistry=20?= =?UTF-8?q?=E4=B8=AD=E5=AF=B9zkclient=E7=9A=84=E6=98=BE=E7=A4=BA=E4=BE=9D?= =?UTF-8?q?=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java index 2c13a761ab4d..3f62da20805f 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java +++ b/dubbo-registry/dubbo-registry-zookeeper/src/main/java/com/alibaba/dubbo/registry/zookeeper/ZookeeperRegistry.java @@ -21,8 +21,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import org.I0Itec.zkclient.exception.ZkNoNodeException; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -193,14 +191,10 @@ public List lookup(URL url) { try { List providers = new ArrayList(); for (String path : toCategoriesPath(url)) { - try { List children = zkClient.getChildren(path); if (children != null) { providers.addAll(children); } - } catch (ZkNoNodeException e) { - // ignore - } } return toUrlsWithoutEmpty(url, providers); } catch (Throwable e) { From bd76ba04e2faeac79a36e88f600a311a2324b491 Mon Sep 17 00:00:00 2001 From: bladehd Date: Mon, 10 Feb 2014 11:30:42 +0800 Subject: [PATCH 100/200] update opensesame compile failure warning --- README | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README b/README index f332c949e29c..252f652c2619 100644 --- a/README +++ b/README @@ -1,3 +1,8 @@ +鐢变簬寮婧愮珯鐐瑰洜涓哄畨鍏ㄩ棶棰樿涓嬫帀锛屽鏋滅紪璇戞椂鍑虹幇鎵句笉鍒皁pensesame渚濊禆鎯呭喌鐨勶紝璇峰厛鎵嬪姩涓嬭浇https://github.com/alibaba/opensesame +鏈湴install锛岃繖鍑犲ぉ鎴戜滑浼氭妸opensesame鍙戝埌mavan涓ぎ浠撳簱銆 + +================================================================ + Dubbo is a distributed service framework enpowers applications with service import/export capability with high performance RPC. It's composed of three kernel parts: From 041a94348c205bee132ba291707b32818075bdb5 Mon Sep 17 00:00:00 2001 From: bladehd Date: Tue, 4 Mar 2014 15:30:41 +0800 Subject: [PATCH 101/200] Update README --- README | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README b/README index 252f652c2619..2f9152b04d28 100644 --- a/README +++ b/README @@ -1,6 +1,8 @@ 鐢变簬寮婧愮珯鐐瑰洜涓哄畨鍏ㄩ棶棰樿涓嬫帀锛屽鏋滅紪璇戞椂鍑虹幇鎵句笉鍒皁pensesame渚濊禆鎯呭喌鐨勶紝璇峰厛鎵嬪姩涓嬭浇https://github.com/alibaba/opensesame 鏈湴install锛岃繖鍑犲ぉ鎴戜滑浼氭妸opensesame鍙戝埌mavan涓ぎ浠撳簱銆 +涓存椂鏂囨。鍦板潃锛歨ttp://alibaba.github.io/dubbo-doc-static/Developer+Guide-zh.htm + ================================================================ Dubbo is a distributed service framework enpowers applications with service import/export capability with high performance RPC. From 50c7e584e4fcc4488cd78bec736aac7fce431e04 Mon Sep 17 00:00:00 2001 From: beyondyuefei <33909391@qq.com> Date: Sun, 16 Mar 2014 20:00:35 +0800 Subject: [PATCH 102/200] Update AbstractClient.java MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 褰撻厤缃甤heck=false鏃讹紝濡傛灉connect鏈嶅姟绔け璐ワ紝鏃ュ織绾у埆璋冩暣涓簑arn锛屼笉闇瑕佷负error --- .../com/alibaba/dubbo/remoting/transport/AbstractClient.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java index 8bbd54662d9f..f4d9ddb0c768 100644 --- a/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java +++ b/dubbo-remoting/dubbo-remoting-api/src/main/java/com/alibaba/dubbo/remoting/transport/AbstractClient.java @@ -109,7 +109,7 @@ public AbstractClient(URL url, ChannelHandler handler) throws RemotingException close(); throw t; } else { - logger.error("Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + logger.warn("Failed to start " + getClass().getSimpleName() + " " + NetUtils.getLocalAddress() + " connect to the server " + getRemoteAddress() + " (check == false, ignore and retry later!), cause: " + t.getMessage(), t); } } catch (Throwable t){ @@ -399,4 +399,4 @@ public String toString() { */ protected abstract Channel getChannel(); -} \ No newline at end of file +} From 17becc2d6676be84b01c0d15a81c5f33f85d21d6 Mon Sep 17 00:00:00 2001 From: Jerry Lee Date: Sun, 13 Apr 2014 23:41:20 +0800 Subject: [PATCH 103/200] update fastjson to 1.1.39 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index c285a6e0eec7..308901ddcfa4 100644 --- a/pom.xml +++ b/pom.xml @@ -92,7 +92,7 @@ 4.1.2 3.2.1-fixed-2 1.4.1 - 1.1.8 + 1.1.39 3.1 0.8 3.3.3 From 977bd905c306d3ce08994eec616b391432275d4d Mon Sep 17 00:00:00 2001 From: kimi Date: Wed, 14 May 2014 00:14:23 +0800 Subject: [PATCH 104/200] =?UTF-8?q?=E9=87=8D=E6=9E=84=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dubbo-remoting/dubbo-remoting-nio/pom.xml | 41 - dubbo-remoting/pom.xml | 3 +- hessian-lite/pom.xml | 15 + .../com/caucho/hessian/HessianException.java | 85 + .../hessian/io/AbstractDeserializer.java | 118 + .../hessian/io/AbstractHessianInput.java | 442 +++ .../hessian/io/AbstractHessianOutput.java | 531 ++++ .../hessian/io/AbstractHessianResolver.java | 65 + .../hessian/io/AbstractListDeserializer.java | 67 + .../hessian/io/AbstractMapDeserializer.java | 74 + .../caucho/hessian/io/AbstractSerializer.java | 63 + .../hessian/io/AbstractSerializerFactory.java | 74 + .../caucho/hessian/io/ArrayDeserializer.java | 164 + .../caucho/hessian/io/ArraySerializer.java | 94 + .../caucho/hessian/io/BasicDeserializer.java | 608 ++++ .../caucho/hessian/io/BasicSerializer.java | 285 ++ .../caucho/hessian/io/BeanDeserializer.java | 295 ++ .../com/caucho/hessian/io/BeanSerializer.java | 315 ++ .../hessian/io/BeanSerializerFactory.java | 82 + .../hessian/io/BigIntegerDeserializer.java | 18 + .../com/caucho/hessian/io/CalendarHandle.java | 93 + .../caucho/hessian/io/CalendarSerializer.java | 77 + .../caucho/hessian/io/ClassDeserializer.java | 160 + .../caucho/hessian/io/ClassSerializer.java | 87 + .../hessian/io/CollectionDeserializer.java | 134 + .../hessian/io/CollectionSerializer.java | 108 + .../com/caucho/hessian/io/Deflation.java | 205 ++ .../com/caucho/hessian/io/Deserializer.java | 73 + .../caucho/hessian/io/EnumDeserializer.java | 138 + .../com/caucho/hessian/io/EnumSerializer.java | 108 + .../hessian/io/EnumerationDeserializer.java | 84 + .../hessian/io/EnumerationSerializer.java | 84 + .../caucho/hessian/io/EnvelopeFactory.java | 57 + .../hessian/io/ExtSerializerFactory.java | 107 + .../caucho/hessian/io/Hessian2Constants.java | 146 + .../com/caucho/hessian/io/Hessian2Input.java | 2798 +++++++++++++++++ .../com/caucho/hessian/io/Hessian2Output.java | 1605 ++++++++++ .../hessian/io/Hessian2StreamingInput.java | 165 + .../hessian/io/Hessian2StreamingOutput.java | 109 + .../hessian/io/HessianDebugInputStream.java | 174 + .../hessian/io/HessianDebugOutputStream.java | 168 + .../caucho/hessian/io/HessianDebugState.java | 2090 ++++++++++++ .../caucho/hessian/io/HessianEnvelope.java | 78 + .../hessian/io/HessianFieldException.java | 87 + .../com/caucho/hessian/io/HessianHandle.java | 55 + .../com/caucho/hessian/io/HessianInput.java | 1700 ++++++++++ .../hessian/io/HessianInputFactory.java | 99 + .../com/caucho/hessian/io/HessianOutput.java | 949 ++++++ .../hessian/io/HessianProtocolException.java | 110 + .../com/caucho/hessian/io/HessianRemote.java | 130 + .../hessian/io/HessianRemoteObject.java | 57 + .../hessian/io/HessianRemoteResolver.java | 62 + .../hessian/io/HessianSerializerInput.java | 183 ++ .../hessian/io/HessianSerializerOutput.java | 146 + .../hessian/io/HessianServiceException.java | 91 + .../caucho/hessian/io/IOExceptionWrapper.java | 77 + .../hessian/io/InputStreamDeserializer.java | 67 + .../hessian/io/InputStreamSerializer.java | 80 + .../caucho/hessian/io/IteratorSerializer.java | 84 + .../caucho/hessian/io/JavaDeserializer.java | 679 ++++ .../com/caucho/hessian/io/JavaSerializer.java | 434 +++ .../com/caucho/hessian/io/LocaleHandle.java | 119 + .../caucho/hessian/io/LocaleSerializer.java | 76 + .../caucho/hessian/io/MapDeserializer.java | 158 + .../com/caucho/hessian/io/MapSerializer.java | 104 + .../caucho/hessian/io/ObjectDeserializer.java | 100 + .../caucho/hessian/io/RemoteSerializer.java | 63 + .../com/caucho/hessian/io/Serializer.java | 59 + .../caucho/hessian/io/SerializerFactory.java | 649 ++++ .../hessian/io/SqlDateDeserializer.java | 133 + .../caucho/hessian/io/SqlDateSerializer.java | 88 + .../io/StackTraceElementDeserializer.java | 69 + .../hessian/io/StringValueDeserializer.java | 130 + .../hessian/io/StringValueSerializer.java | 86 + .../hessian/io/ThrowableSerializer.java | 71 + .../caucho/hessian/io/ValueDeserializer.java | 93 + .../hessian/security/X509Encryption.java | 380 +++ .../hessian/security/X509Signature.java | 397 +++ .../caucho/hessian/util/IdentityIntMap.java | 252 ++ .../com/caucho/hessian/util/IntMap.java | 252 ++ pom.xml | 67 +- 81 files changed, 20666 insertions(+), 57 deletions(-) delete mode 100644 dubbo-remoting/dubbo-remoting-nio/pom.xml create mode 100644 hessian-lite/pom.xml create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/HessianException.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianInput.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianOutput.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianResolver.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractListDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractMapDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractSerializerFactory.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ArrayDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ArraySerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BasicDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BasicSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanSerializerFactory.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BigIntegerDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CalendarHandle.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CalendarSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ClassDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ClassSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CollectionDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CollectionSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Deflation.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Deserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumerationDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumerationSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnvelopeFactory.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ExtSerializerFactory.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Constants.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Input.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Output.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2StreamingInput.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2StreamingOutput.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugInputStream.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugOutputStream.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugState.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianEnvelope.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianFieldException.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianHandle.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianInput.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianInputFactory.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianOutput.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianProtocolException.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemote.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemoteObject.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemoteResolver.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianSerializerInput.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianSerializerOutput.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianServiceException.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/IOExceptionWrapper.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/InputStreamDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/InputStreamSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/IteratorSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/JavaDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/JavaSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/LocaleHandle.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/LocaleSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/MapDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/MapSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ObjectDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/RemoteSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Serializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SerializerFactory.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SqlDateDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SqlDateSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StackTraceElementDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StringValueDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StringValueSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ThrowableSerializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ValueDeserializer.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/security/X509Encryption.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/security/X509Signature.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/util/IdentityIntMap.java create mode 100644 hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/util/IntMap.java diff --git a/dubbo-remoting/dubbo-remoting-nio/pom.xml b/dubbo-remoting/dubbo-remoting-nio/pom.xml deleted file mode 100644 index 2962b3dcaaa0..000000000000 --- a/dubbo-remoting/dubbo-remoting-nio/pom.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - 4.0.0 - - dubbo-remoting - com.alibaba - 2.5.4-SNAPSHOT - - com.alibaba - dubbo-remoting-nio - dubbo-remoting-nio - - - com.alibaba - dubbo-remoting-api - ${project.parent.version} - - - junit - junit - - - diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index e3bcaab869d0..3b2b630a8eaf 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -35,6 +35,5 @@ dubbo-remoting-p2p dubbo-remoting-http dubbo-remoting-zookeeper - dubbo-remoting-nio - + \ No newline at end of file diff --git a/hessian-lite/pom.xml b/hessian-lite/pom.xml new file mode 100644 index 000000000000..24af1c78311b --- /dev/null +++ b/hessian-lite/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + + com.alibaba + dubbo-parent + 2.5.4-SNAPSHOT + + hessian-lite + jar + 3.2.1-fixed-2 + Hessian Lite(Alibaba embed version) + diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/HessianException.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/HessianException.java new file mode 100644 index 000000000000..8b08c3de46e3 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/HessianException.java @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian; + +/** + * Base runtime exception for Hessian exceptions. + */ +public class HessianException extends RuntimeException { + /** + * Zero-arg constructor. + */ + public HessianException() + { + } + + /** + * Create the exception. + */ + public HessianException(String message) + { + super(message); + } + + /** + * Create the exception. + */ + public HessianException(String message, Throwable rootCause) + { + super(message, rootCause); + } + + /** + * Create the exception. + */ + public HessianException(Throwable rootCause) + { + super(rootCause); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractDeserializer.java new file mode 100644 index 000000000000..802b2ca37b96 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractDeserializer.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Deserializing an object. + */ +abstract public class AbstractDeserializer implements Deserializer { + public Class getType() + { + return Object.class; + } + + public Object readObject(AbstractHessianInput in) + throws IOException + { + Object obj = in.readObject(); + + String className = getClass().getName(); + + if (obj != null) + throw error(className + ": unexpected object " + obj.getClass().getName() + " (" + obj + ")"); + else + throw error(className + ": unexpected null value"); + } + + public Object readList(AbstractHessianInput in, int length) + throws IOException + { + throw new UnsupportedOperationException(String.valueOf(this)); + } + + public Object readLengthList(AbstractHessianInput in, int length) + throws IOException + { + throw new UnsupportedOperationException(String.valueOf(this)); + } + + public Object readMap(AbstractHessianInput in) + throws IOException + { + Object obj = in.readObject(); + + String className = getClass().getName(); + + if (obj != null) + throw error(className + ": unexpected object " + obj.getClass().getName() + " (" + obj + ")"); + else + throw error(className + ": unexpected null value"); + } + + public Object readObject(AbstractHessianInput in, String []fieldNames) + throws IOException + { + throw new UnsupportedOperationException(String.valueOf(this)); + } + + protected HessianProtocolException error(String msg) + { + return new HessianProtocolException(msg); + } + + protected String codeName(int ch) + { + if (ch < 0) + return "end of file"; + else + return "0x" + Integer.toHexString(ch & 0xff); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianInput.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianInput.java new file mode 100644 index 000000000000..6e1548f8aeda --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianInput.java @@ -0,0 +1,442 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; + +/** + * Abstract base class for Hessian requests. Hessian users should only + * need to use the methods in this class. + * + *
+ * AbstractHessianInput in = ...; // get input
+ * String value;
+ *
+ * in.startReply();         // read reply header
+ * value = in.readString(); // read string value
+ * in.completeReply();      // read reply footer
+ * 
+ */ +abstract public class AbstractHessianInput { + private HessianRemoteResolver resolver; + + /** + * Initialize the Hessian stream with the underlying input stream. + */ + public void init(InputStream is) + { + } + + /** + * Returns the call's method + */ + abstract public String getMethod(); + + /** + * Sets the resolver used to lookup remote objects. + */ + public void setRemoteResolver(HessianRemoteResolver resolver) + { + this.resolver = resolver; + } + + /** + * Sets the resolver used to lookup remote objects. + */ + public HessianRemoteResolver getRemoteResolver() + { + return resolver; + } + + /** + * Sets the serializer factory. + */ + public void setSerializerFactory(SerializerFactory ser) + { + } + + /** + * Reads the call + * + *
+   * c major minor
+   * 
+ */ + abstract public int readCall() + throws IOException; + + /** + * For backward compatibility with HessianSkeleton + */ + public void skipOptionalCall() + throws IOException + { + } + + /** + * Reads a header, returning null if there are no headers. + * + *
+   * H b16 b8 value
+   * 
+ */ + abstract public String readHeader() + throws IOException; + + /** + * Starts reading the call + * + *

A successful completion will have a single value: + * + *

+   * m b16 b8 method
+   * 
+ */ + abstract public String readMethod() + throws IOException; + + /** + * Reads the number of method arguments + * + * @return -1 for a variable length (hessian 1.0) + */ + public int readMethodArgLength() + throws IOException + { + return -1; + } + + /** + * Starts reading the call, including the headers. + * + *

The call expects the following protocol data + * + *

+   * c major minor
+   * m b16 b8 method
+   * 
+ */ + abstract public void startCall() + throws IOException; + + /** + * Completes reading the call + * + *

The call expects the following protocol data + * + *

+   * Z
+   * 
+ */ + abstract public void completeCall() + throws IOException; + + /** + * Reads a reply as an object. + * If the reply has a fault, throws the exception. + */ + abstract public Object readReply(Class expectedClass) + throws Throwable; + + /** + * Starts reading the reply + * + *

A successful completion will have a single value: + * + *

+   * r
+   * v
+   * 
+ */ + abstract public void startReply() + throws Throwable; + + /** + * Completes reading the call + * + *

A successful completion will have a single value: + * + *

+   * z
+   * 
+ */ + abstract public void completeReply() + throws IOException; + + /** + * Reads a boolean + * + *
+   * T
+   * F
+   * 
+ */ + abstract public boolean readBoolean() + throws IOException; + + /** + * Reads a null + * + *
+   * N
+   * 
+ */ + abstract public void readNull() + throws IOException; + + /** + * Reads an integer + * + *
+   * I b32 b24 b16 b8
+   * 
+ */ + abstract public int readInt() + throws IOException; + + /** + * Reads a long + * + *
+   * L b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + abstract public long readLong() + throws IOException; + + /** + * Reads a double. + * + *
+   * D b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + abstract public double readDouble() + throws IOException; + + /** + * Reads a date. + * + *
+   * T b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + abstract public long readUTCDate() + throws IOException; + + /** + * Reads a string encoded in UTF-8 + * + *
+   * s b16 b8 non-final string chunk
+   * S b16 b8 final string chunk
+   * 
+ */ + abstract public String readString() + throws IOException; + + /** + * Reads an XML node encoded in UTF-8 + * + *
+   * x b16 b8 non-final xml chunk
+   * X b16 b8 final xml chunk
+   * 
+ */ + public org.w3c.dom.Node readNode() + throws IOException + { + throw new UnsupportedOperationException(getClass().getSimpleName()); + } + + /** + * Starts reading a string. All the characters must be read before + * calling the next method. The actual characters will be read with + * the reader's read() or read(char [], int, int). + * + *
+   * s b16 b8 non-final string chunk
+   * S b16 b8 final string chunk
+   * 
+ */ + abstract public Reader getReader() + throws IOException; + + /** + * Starts reading a byte array using an input stream. All the bytes + * must be read before calling the following method. + * + *
+   * b b16 b8 non-final binary chunk
+   * B b16 b8 final binary chunk
+   * 
+ */ + abstract public InputStream readInputStream() + throws IOException; + + /** + * Reads a byte array. + * + *
+   * b b16 b8 non-final binary chunk
+   * B b16 b8 final binary chunk
+   * 
+ */ + abstract public byte []readBytes() + throws IOException; + + /** + * Reads an arbitrary object from the input stream. + * + * @param expectedClass the expected class if the protocol doesn't supply it. + */ + abstract public Object readObject(Class expectedClass) + throws IOException; + + /** + * Reads an arbitrary object from the input stream. + */ + abstract public Object readObject() + throws IOException; + + /** + * Reads a remote object reference to the stream. The type is the + * type of the remote interface. + * + *
+   * 'r' 't' b16 b8 type url
+   * 
+ */ + abstract public Object readRemote() + throws IOException; + + /** + * Reads a reference + * + *
+   * R b32 b24 b16 b8
+   * 
+ */ + abstract public Object readRef() + throws IOException; + + /** + * Adds an object reference. + */ + abstract public int addRef(Object obj) + throws IOException; + + /** + * Sets an object reference. + */ + abstract public void setRef(int i, Object obj) + throws IOException; + + /** + * Resets the references for streaming. + */ + public void resetReferences() + { + } + + /** + * Reads the start of a list + */ + abstract public int readListStart() + throws IOException; + + /** + * Reads the length of a list. + */ + abstract public int readLength() + throws IOException; + + /** + * Reads the start of a map + */ + abstract public int readMapStart() + throws IOException; + + /** + * Reads an object type. + */ + abstract public String readType() + throws IOException; + + /** + * Returns true if the data has ended. + */ + abstract public boolean isEnd() + throws IOException; + + /** + * Read the end byte + */ + abstract public void readEnd() + throws IOException; + + /** + * Read the end byte + */ + abstract public void readMapEnd() + throws IOException; + + /** + * Read the end byte + */ + abstract public void readListEnd() + throws IOException; + + public void close() + throws IOException + { + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianOutput.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianOutput.java new file mode 100644 index 000000000000..f61732f54df2 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianOutput.java @@ -0,0 +1,531 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * Abstract output stream for Hessian requests. + * + *
+ * OutputStream os = ...; // from http connection
+ * AbstractOutput out = new HessianSerializerOutput(os);
+ * String value;
+ *
+ * out.startCall("hello");  // start hello call
+ * out.writeString("arg1"); // write a string argument
+ * out.completeCall();      // complete the call
+ * 
+ */ +abstract public class AbstractHessianOutput { + // serializer factory + protected SerializerFactory _serializerFactory; + + /** + * Sets the serializer factory. + */ + public void setSerializerFactory(SerializerFactory factory) + { + _serializerFactory = factory; + } + + /** + * Gets the serializer factory. + */ + public SerializerFactory getSerializerFactory() + { + return _serializerFactory; + } + + /** + * Gets the serializer factory. + */ + public final SerializerFactory findSerializerFactory() + { + SerializerFactory factory = _serializerFactory; + + if (factory == null) + _serializerFactory = factory = new SerializerFactory(); + + return factory; + } + + /** + * Initialize the output with a new underlying stream. + */ + public void init(OutputStream os) + { + } + + /** + * Writes a complete method call. + */ + public void call(String method, Object []args) + throws IOException + { + int length = args != null ? args.length : 0; + + startCall(method, length); + + for (int i = 0; i < length; i++) + writeObject(args[i]); + + completeCall(); + } + + /** + * Starts the method call: + * + *
+   * C
+   * 
+ * + * @param method the method name to call. + */ + abstract public void startCall() + throws IOException; + + /** + * Starts the method call: + * + *
+   * C string int
+   * 
+ * + * @param method the method name to call. + */ + abstract public void startCall(String method, int length) + throws IOException; + + /** + * For Hessian 2.0, use the Header envelope instead + * + * @deprecated + */ + public void writeHeader(String name) + throws IOException + { + throw new UnsupportedOperationException(getClass().getSimpleName()); + } + + /** + * Writes the method tag. + * + *
+   * string
+   * 
+ * + * @param method the method name to call. + */ + abstract public void writeMethod(String method) + throws IOException; + + /** + * Completes the method call: + * + *
+   * 
+ */ + abstract public void completeCall() + throws IOException; + + /** + * Writes a boolean value to the stream. The boolean will be written + * with the following syntax: + * + *
+   * T
+   * F
+   * 
+ * + * @param value the boolean value to write. + */ + abstract public void writeBoolean(boolean value) + throws IOException; + + /** + * Writes an integer value to the stream. The integer will be written + * with the following syntax: + * + *
+   * I b32 b24 b16 b8
+   * 
+ * + * @param value the integer value to write. + */ + abstract public void writeInt(int value) + throws IOException; + + /** + * Writes a long value to the stream. The long will be written + * with the following syntax: + * + *
+   * L b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ * + * @param value the long value to write. + */ + abstract public void writeLong(long value) + throws IOException; + + /** + * Writes a double value to the stream. The double will be written + * with the following syntax: + * + *
+   * D b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ * + * @param value the double value to write. + */ + abstract public void writeDouble(double value) + throws IOException; + + /** + * Writes a date to the stream. + * + *
+   * T  b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ * + * @param time the date in milliseconds from the epoch in UTC + */ + abstract public void writeUTCDate(long time) + throws IOException; + + /** + * Writes a null value to the stream. + * The null will be written with the following syntax + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + abstract public void writeNull() + throws IOException; + + /** + * Writes a string value to the stream using UTF-8 encoding. + * The string will be written with the following syntax: + * + *
+   * S b16 b8 string-value
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + abstract public void writeString(String value) + throws IOException; + + /** + * Writes a string value to the stream using UTF-8 encoding. + * The string will be written with the following syntax: + * + *
+   * S b16 b8 string-value
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + abstract public void writeString(char []buffer, int offset, int length) + throws IOException; + + /** + * Writes a byte array to the stream. + * The array will be written with the following syntax: + * + *
+   * B b16 b18 bytes
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + abstract public void writeBytes(byte []buffer) + throws IOException; + /** + * Writes a byte array to the stream. + * The array will be written with the following syntax: + * + *
+   * B b16 b18 bytes
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + abstract public void writeBytes(byte []buffer, int offset, int length) + throws IOException; + + /** + * Writes a byte buffer to the stream. + */ + abstract public void writeByteBufferStart() + throws IOException; + + /** + * Writes a byte buffer to the stream. + * + *
+   * b b16 b18 bytes
+   * 
+ * + * @param value the string value to write. + */ + abstract public void writeByteBufferPart(byte []buffer, + int offset, + int length) + throws IOException; + + /** + * Writes the last chunk of a byte buffer to the stream. + * + *
+   * b b16 b18 bytes
+   * 
+ * + * @param value the string value to write. + */ + abstract public void writeByteBufferEnd(byte []buffer, + int offset, + int length) + throws IOException; + + /** + * Writes a reference. + * + *
+   * Q int
+   * 
+ * + * @param value the integer value to write. + */ + abstract protected void writeRef(int value) + throws IOException; + + /** + * Removes a reference. + */ + abstract public boolean removeRef(Object obj) + throws IOException; + + /** + * Replaces a reference from one object to another. + */ + abstract public boolean replaceRef(Object oldRef, Object newRef) + throws IOException; + + /** + * Adds an object to the reference list. If the object already exists, + * writes the reference, otherwise, the caller is responsible for + * the serialization. + * + *
+   * R b32 b24 b16 b8
+   * 
+ * + * @param object the object to add as a reference. + * + * @return true if the object has already been written. + */ + abstract public boolean addRef(Object object) + throws IOException; + + /** + * Resets the references for streaming. + */ + public void resetReferences() + { + } + + /** + * Writes a generic object to the output stream. + */ + abstract public void writeObject(Object object) + throws IOException; + + /** + * Writes the list header to the stream. List writers will call + * writeListBegin followed by the list contents and then + * call writeListEnd. + * + *
+   * V
+   *   x13 java.util.ArrayList   # type
+   *   x93                       # length=3
+   *   x91                       # 1
+   *   x92                       # 2
+   *   x93                       # 3
+   * </list>
+   * 
+ */ + abstract public boolean writeListBegin(int length, String type) + throws IOException; + + /** + * Writes the tail of the list to the stream. + */ + abstract public void writeListEnd() + throws IOException; + + /** + * Writes the map header to the stream. Map writers will call + * writeMapBegin followed by the map contents and then + * call writeMapEnd. + * + *
+   * M type ( )* Z
+   * 
+ */ + abstract public void writeMapBegin(String type) + throws IOException; + + /** + * Writes the tail of the map to the stream. + */ + abstract public void writeMapEnd() + throws IOException; + + /** + * Writes the object header to the stream (for Hessian 2.0), or a + * Map for Hessian 1.0. Object writers will call + * writeObjectBegin followed by the map contents and then + * call writeObjectEnd. + * + *
+   * C type int *
+   * C int *
+   * 
+ * + * @return true if the object has already been defined. + */ + public int writeObjectBegin(String type) + throws IOException + { + writeMapBegin(type); + + return -2; + } + + /** + * Writes the end of the class. + */ + public void writeClassFieldLength(int len) + throws IOException + { + } + + /** + * Writes the tail of the object to the stream. + */ + public void writeObjectEnd() + throws IOException + { + } + + public void writeReply(Object o) + throws IOException + { + startReply(); + writeObject(o); + completeReply(); + } + + + public void startReply() + throws IOException + { + } + + public void completeReply() + throws IOException + { + } + + public void writeFault(String code, String message, Object detail) + throws IOException + { + } + + public void flush() + throws IOException + { + } + + public void close() + throws IOException + { + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianResolver.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianResolver.java new file mode 100644 index 000000000000..ae42285c9838 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractHessianResolver.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Looks up remote objects. The default just returns a HessianRemote object. + */ +public class AbstractHessianResolver implements HessianRemoteResolver { + /** + * Looks up a proxy object. + */ + public Object lookup(String type, String url) + throws IOException + { + return new HessianRemote(type, url); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractListDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractListDeserializer.java new file mode 100644 index 000000000000..20318b9d6599 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractListDeserializer.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Deserializing a JDK 1.2 Collection. + */ +public class AbstractListDeserializer extends AbstractDeserializer { + public Object readObject(AbstractHessianInput in) + throws IOException + { + Object obj = in.readObject(); + + if (obj != null) + throw error("expected list at " + obj.getClass().getName() + " (" + obj + ")"); + else + throw error("expected list at null"); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractMapDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractMapDeserializer.java new file mode 100644 index 000000000000..7a90a7912ac5 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractMapDeserializer.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.HashMap; + +/** + * Serializing an object for known object types. + */ +public class AbstractMapDeserializer extends AbstractDeserializer { + + public Class getType() + { + return HashMap.class; + } + + public Object readObject(AbstractHessianInput in) + throws IOException + { + Object obj = in.readObject(); + + if (obj != null) + throw error("expected map/object at " + obj.getClass().getName() + " (" + obj + ")"); + else + throw error("expected map/object at null"); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractSerializer.java new file mode 100644 index 000000000000..df450cf340a2 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractSerializer.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.logging.*; + +/** + * Serializing an object. + */ +abstract public class AbstractSerializer implements Serializer { + protected static final Logger log + = Logger.getLogger(AbstractSerializer.class.getName()); + + abstract public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException; +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractSerializerFactory.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractSerializerFactory.java new file mode 100644 index 000000000000..cc66de7ce866 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/AbstractSerializerFactory.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +/** + * Factory for returning serialization methods. + */ +abstract public class AbstractSerializerFactory { + /** + * Returns the serializer for a class. + * + * @param cl the class of the object that needs to be serialized. + * + * @return a serializer object for the serialization. + */ + abstract public Serializer getSerializer(Class cl) + throws HessianProtocolException; + + /** + * Returns the deserializer for a class. + * + * @param cl the class of the object that needs to be deserialized. + * + * @return a deserializer object for the serialization. + */ + abstract public Deserializer getDeserializer(Class cl) + throws HessianProtocolException; +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ArrayDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ArrayDeserializer.java new file mode 100644 index 000000000000..cf8fc6e7e20e --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ArrayDeserializer.java @@ -0,0 +1,164 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.lang.reflect.Array; +import java.util.ArrayList; + +/** + * Deserializing a Java array + */ +public class ArrayDeserializer extends AbstractListDeserializer { + private Class _componentType; + private Class _type; + + public ArrayDeserializer(Class componentType) + { + _componentType = componentType; + + if (_componentType != null) { + try { + _type = Array.newInstance(_componentType, 0).getClass(); + } catch (Exception e) { + } + } + + if (_type == null) + _type = Object[].class; + } + + public Class getType() + { + return _type; + } + + /** + * Reads the array. + */ + public Object readList(AbstractHessianInput in, int length) + throws IOException + { + if (length >= 0) { + Object []data = createArray(length); + + in.addRef(data); + + if (_componentType != null) { + for (int i = 0; i < data.length; i++) + data[i] = in.readObject(_componentType); + } + else { + for (int i = 0; i < data.length; i++) + data[i] = in.readObject(); + } + + in.readListEnd(); + + return data; + } + else { + ArrayList list = new ArrayList(); + + in.addRef(list); + + if (_componentType != null) { + while (! in.isEnd()) + list.add(in.readObject(_componentType)); + } + else { + while (! in.isEnd()) + list.add(in.readObject()); + } + + in.readListEnd(); + + Object []data = createArray(list.size()); + for (int i = 0; i < data.length; i++) + data[i] = list.get(i); + + return data; + } + } + + /** + * Reads the array. + */ + public Object readLengthList(AbstractHessianInput in, int length) + throws IOException + { + Object []data = createArray(length); + + in.addRef(data); + + if (_componentType != null) { + for (int i = 0; i < data.length; i++) + data[i] = in.readObject(_componentType); + } + else { + for (int i = 0; i < data.length; i++) + data[i] = in.readObject(); + } + + return data; + } + + protected Object []createArray(int length) + { + if (_componentType != null) + return (Object []) Array.newInstance(_componentType, length); + else + return new Object[length]; + } + + public String toString() + { + return "ArrayDeserializer[" + _componentType + "]"; + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ArraySerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ArraySerializer.java new file mode 100644 index 000000000000..7bcfe90f84a0 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ArraySerializer.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Serializing a Java array. + */ +public class ArraySerializer extends AbstractSerializer { + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + if (out.addRef(obj)) + return; + + Object []array = (Object []) obj; + + boolean hasEnd = out.writeListBegin(array.length, + getArrayType(obj.getClass())); + + for (int i = 0; i < array.length; i++) + out.writeObject(array[i]); + + if (hasEnd) + out.writeListEnd(); + } + + /** + * Returns the <type> name for a <list>. + */ + private String getArrayType(Class cl) + { + if (cl.isArray()) + return '[' + getArrayType(cl.getComponentType()); + + String name = cl.getName(); + + if (name.equals("java.lang.String")) + return "string"; + else if (name.equals("java.lang.Object")) + return "object"; + else if (name.equals("java.util.Date")) + return "date"; + else + return name; + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BasicDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BasicDeserializer.java new file mode 100644 index 000000000000..a0e860f69818 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BasicDeserializer.java @@ -0,0 +1,608 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; + +/** + * Serializing an object for known object types. + */ +public class BasicDeserializer extends AbstractDeserializer { + public static final int NULL = BasicSerializer.NULL; + public static final int BOOLEAN = BasicSerializer.BOOLEAN; + public static final int BYTE = BasicSerializer.BYTE; + public static final int SHORT = BasicSerializer.SHORT; + public static final int INTEGER = BasicSerializer.INTEGER; + public static final int LONG = BasicSerializer.LONG; + public static final int FLOAT = BasicSerializer.FLOAT; + public static final int DOUBLE = BasicSerializer.DOUBLE; + public static final int CHARACTER = BasicSerializer.CHARACTER; + public static final int CHARACTER_OBJECT = BasicSerializer.CHARACTER_OBJECT; + public static final int STRING = BasicSerializer.STRING; + public static final int DATE = BasicSerializer.DATE; + public static final int NUMBER = BasicSerializer.NUMBER; + public static final int OBJECT = BasicSerializer.OBJECT; + + public static final int BOOLEAN_ARRAY = BasicSerializer.BOOLEAN_ARRAY; + public static final int BYTE_ARRAY = BasicSerializer.BYTE_ARRAY; + public static final int SHORT_ARRAY = BasicSerializer.SHORT_ARRAY; + public static final int INTEGER_ARRAY = BasicSerializer.INTEGER_ARRAY; + public static final int LONG_ARRAY = BasicSerializer.LONG_ARRAY; + public static final int FLOAT_ARRAY = BasicSerializer.FLOAT_ARRAY; + public static final int DOUBLE_ARRAY = BasicSerializer.DOUBLE_ARRAY; + public static final int CHARACTER_ARRAY = BasicSerializer.CHARACTER_ARRAY; + public static final int STRING_ARRAY = BasicSerializer.STRING_ARRAY; + public static final int OBJECT_ARRAY = BasicSerializer.OBJECT_ARRAY; + + private int _code; + + public BasicDeserializer(int code) + { + _code = code; + } + + public Class getType() + { + switch (_code) { + case NULL: + return void.class; + case BOOLEAN: + return Boolean.class; + case BYTE: + return Byte.class; + case SHORT: + return Short.class; + case INTEGER: + return Integer.class; + case LONG: + return Long.class; + case FLOAT: + return Float.class; + case DOUBLE: + return Double.class; + case CHARACTER: + return Character.class; + case CHARACTER_OBJECT: + return Character.class; + case STRING: + return String.class; + case DATE: + return Date.class; + case NUMBER: + return Number.class; + case OBJECT: + return Object.class; + + case BOOLEAN_ARRAY: + return boolean[].class; + case BYTE_ARRAY: + return byte[].class; + case SHORT_ARRAY: + return short[].class; + case INTEGER_ARRAY: + return int[].class; + case LONG_ARRAY: + return long[].class; + case FLOAT_ARRAY: + return float[].class; + case DOUBLE_ARRAY: + return double[].class; + case CHARACTER_ARRAY: + return char[].class; + case STRING_ARRAY: + return String[].class; + case OBJECT_ARRAY: + return Object[].class; + default: + throw new UnsupportedOperationException(); + } + } + + public Object readObject(AbstractHessianInput in) + throws IOException + { + switch (_code) { + case NULL: + // hessian/3490 + in.readObject(); + + return null; + + case BOOLEAN: + return Boolean.valueOf(in.readBoolean()); + + case BYTE: + return Byte.valueOf((byte) in.readInt()); + + case SHORT: + return Short.valueOf((short) in.readInt()); + + case INTEGER: + return Integer.valueOf(in.readInt()); + + case LONG: + return Long.valueOf(in.readLong()); + + case FLOAT: + return Float.valueOf((float) in.readDouble()); + + case DOUBLE: + return Double.valueOf(in.readDouble()); + + case STRING: + return in.readString(); + + case OBJECT: + return in.readObject(); + + case CHARACTER: + { + String s = in.readString(); + if (s == null || s.equals("")) + return Character.valueOf((char) 0); + else + return Character.valueOf(s.charAt(0)); + } + + case CHARACTER_OBJECT: + { + String s = in.readString(); + if (s == null || s.equals("")) + return null; + else + return Character.valueOf(s.charAt(0)); + } + + case DATE: + return new Date(in.readUTCDate()); + + case NUMBER: + return in.readObject(); + + case BYTE_ARRAY: + return in.readBytes(); + + case CHARACTER_ARRAY: + { + String s = in.readString(); + + if (s == null) + return null; + else { + int len = s.length(); + char []chars = new char[len]; + s.getChars(0, len, chars, 0); + return chars; + } + } + + case BOOLEAN_ARRAY: + case SHORT_ARRAY: + case INTEGER_ARRAY: + case LONG_ARRAY: + case FLOAT_ARRAY: + case DOUBLE_ARRAY: + case STRING_ARRAY: + { + int code = in.readListStart(); + + switch (code) { + case 'N': + return null; + + case 0x10: case 0x11: case 0x12: case 0x13: + case 0x14: case 0x15: case 0x16: case 0x17: + case 0x18: case 0x19: case 0x1a: case 0x1b: + case 0x1c: case 0x1d: case 0x1e: case 0x1f: + int length = code - 0x10; + in.readInt(); + + return readLengthList(in, length); + + default: + String type = in.readType(); + length = in.readLength(); + + return readList(in, length); + } + } + + default: + throw new UnsupportedOperationException(); + } + } + + public Object readList(AbstractHessianInput in, int length) + throws IOException + { + switch (_code) { + case BOOLEAN_ARRAY: { + if (length >= 0) { + boolean []data = new boolean[length]; + + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readBoolean(); + + in.readEnd(); + + return data; + } + else { + ArrayList list = new ArrayList(); + + while (! in.isEnd()) + list.add(Boolean.valueOf(in.readBoolean())); + + in.readEnd(); + + boolean []data = new boolean[list.size()]; + + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = ((Boolean) list.get(i)).booleanValue(); + + return data; + } + } + + case SHORT_ARRAY: { + if (length >= 0) { + short []data = new short[length]; + + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = (short) in.readInt(); + + in.readEnd(); + + return data; + } + else { + ArrayList list = new ArrayList(); + + while (! in.isEnd()) + list.add(Short.valueOf((short) in.readInt())); + + in.readEnd(); + + short []data = new short[list.size()]; + for (int i = 0; i < data.length; i++) + data[i] = ((Short) list.get(i)).shortValue(); + + in.addRef(data); + + return data; + } + } + + case INTEGER_ARRAY: { + if (length >= 0) { + int []data = new int[length]; + + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readInt(); + + in.readEnd(); + + return data; + } + else { + ArrayList list = new ArrayList(); + + while (! in.isEnd()) + list.add(Integer.valueOf(in.readInt())); + + + in.readEnd(); + + int []data = new int[list.size()]; + for (int i = 0; i < data.length; i++) + data[i] = ((Integer) list.get(i)).intValue(); + + in.addRef(data); + + return data; + } + } + + case LONG_ARRAY: { + if (length >= 0) { + long []data = new long[length]; + + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readLong(); + + in.readEnd(); + + return data; + } + else { + ArrayList list = new ArrayList(); + + while (! in.isEnd()) + list.add(Long.valueOf(in.readLong())); + + in.readEnd(); + + long []data = new long[list.size()]; + for (int i = 0; i < data.length; i++) + data[i] = ((Long) list.get(i)).longValue(); + + in.addRef(data); + + return data; + } + } + + case FLOAT_ARRAY: { + if (length >= 0) { + float []data = new float[length]; + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = (float) in.readDouble(); + + in.readEnd(); + + return data; + } + else { + ArrayList list = new ArrayList(); + + while (! in.isEnd()) + list.add(new Float(in.readDouble())); + + in.readEnd(); + + float []data = new float[list.size()]; + for (int i = 0; i < data.length; i++) + data[i] = ((Float) list.get(i)).floatValue(); + + in.addRef(data); + + return data; + } + } + + case DOUBLE_ARRAY: { + if (length >= 0) { + double []data = new double[length]; + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readDouble(); + + in.readEnd(); + + return data; + } + else { + ArrayList list = new ArrayList(); + + while (! in.isEnd()) + list.add(new Double(in.readDouble())); + + in.readEnd(); + + double []data = new double[list.size()]; + in.addRef(data); + for (int i = 0; i < data.length; i++) + data[i] = ((Double) list.get(i)).doubleValue(); + + return data; + } + } + + case STRING_ARRAY: { + if (length >= 0) { + String []data = new String[length]; + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readString(); + + in.readEnd(); + + return data; + } + else { + ArrayList list = new ArrayList(); + + while (! in.isEnd()) + list.add(in.readString()); + + in.readEnd(); + + String []data = new String[list.size()]; + in.addRef(data); + for (int i = 0; i < data.length; i++) + data[i] = (String) list.get(i); + + return data; + } + } + + case OBJECT_ARRAY: { + if (length >= 0) { + Object []data = new Object[length]; + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readObject(); + + in.readEnd(); + + return data; + } + else { + ArrayList list = new ArrayList(); + + in.addRef(list); // XXX: potential issues here + + while (! in.isEnd()) + list.add(in.readObject()); + + in.readEnd(); + + Object []data = new Object[list.size()]; + for (int i = 0; i < data.length; i++) + data[i] = (Object) list.get(i); + + return data; + } + } + + default: + throw new UnsupportedOperationException(String.valueOf(this)); + } + } + + public Object readLengthList(AbstractHessianInput in, int length) + throws IOException + { + switch (_code) { + case BOOLEAN_ARRAY: { + boolean []data = new boolean[length]; + + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readBoolean(); + + return data; + } + + case SHORT_ARRAY: { + short []data = new short[length]; + + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = (short) in.readInt(); + + return data; + } + + case INTEGER_ARRAY: { + int []data = new int[length]; + + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readInt(); + + return data; + } + + case LONG_ARRAY: { + long []data = new long[length]; + + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readLong(); + + return data; + } + + case FLOAT_ARRAY: { + float []data = new float[length]; + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = (float) in.readDouble(); + + return data; + } + + case DOUBLE_ARRAY: { + double []data = new double[length]; + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readDouble(); + + return data; + } + + case STRING_ARRAY: { + String []data = new String[length]; + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readString(); + + return data; + } + + case OBJECT_ARRAY: { + Object []data = new Object[length]; + in.addRef(data); + + for (int i = 0; i < data.length; i++) + data[i] = in.readObject(); + + return data; + } + + default: + throw new UnsupportedOperationException(String.valueOf(this)); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BasicSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BasicSerializer.java new file mode 100644 index 000000000000..2feb40b655db --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BasicSerializer.java @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.Date; + +/** + * Serializing an object for known object types. + */ +public class BasicSerializer extends AbstractSerializer { + public static final int NULL = 0; + public static final int BOOLEAN = NULL + 1; + public static final int BYTE = BOOLEAN + 1; + public static final int SHORT = BYTE + 1; + public static final int INTEGER = SHORT + 1; + public static final int LONG = INTEGER + 1; + public static final int FLOAT = LONG + 1; + public static final int DOUBLE = FLOAT + 1; + public static final int CHARACTER = DOUBLE + 1; + public static final int CHARACTER_OBJECT = CHARACTER + 1; + public static final int STRING = CHARACTER_OBJECT + 1; + public static final int DATE = STRING + 1; + public static final int NUMBER = DATE + 1; + public static final int OBJECT = NUMBER + 1; + + public static final int BOOLEAN_ARRAY = OBJECT + 1; + public static final int BYTE_ARRAY = BOOLEAN_ARRAY + 1; + public static final int SHORT_ARRAY = BYTE_ARRAY + 1; + public static final int INTEGER_ARRAY = SHORT_ARRAY + 1; + public static final int LONG_ARRAY = INTEGER_ARRAY + 1; + public static final int FLOAT_ARRAY = LONG_ARRAY + 1; + public static final int DOUBLE_ARRAY = FLOAT_ARRAY + 1; + public static final int CHARACTER_ARRAY = DOUBLE_ARRAY + 1; + public static final int STRING_ARRAY = CHARACTER_ARRAY + 1; + public static final int OBJECT_ARRAY = STRING_ARRAY + 1; + + private int code; + + public BasicSerializer(int code) + { + this.code = code; + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + switch (code) { + case BOOLEAN: + out.writeBoolean(((Boolean) obj).booleanValue()); + break; + + case BYTE: + case SHORT: + case INTEGER: + out.writeInt(((Number) obj).intValue()); + break; + + case LONG: + out.writeLong(((Number) obj).longValue()); + break; + + case FLOAT: + case DOUBLE: + out.writeDouble(((Number) obj).doubleValue()); + break; + + case CHARACTER: + case CHARACTER_OBJECT: + out.writeString(String.valueOf(obj)); + break; + + case STRING: + out.writeString((String) obj); + break; + + case DATE: + out.writeUTCDate(((Date) obj).getTime()); + break; + + case BOOLEAN_ARRAY: + { + if (out.addRef(obj)) + return; + + boolean []data = (boolean []) obj; + boolean hasEnd = out.writeListBegin(data.length, "[boolean"); + for (int i = 0; i < data.length; i++) + out.writeBoolean(data[i]); + + if (hasEnd) + out.writeListEnd(); + + break; + } + + case BYTE_ARRAY: + { + byte []data = (byte []) obj; + out.writeBytes(data, 0, data.length); + break; + } + + case SHORT_ARRAY: + { + if (out.addRef(obj)) + return; + + short []data = (short []) obj; + boolean hasEnd = out.writeListBegin(data.length, "[short"); + + for (int i = 0; i < data.length; i++) + out.writeInt(data[i]); + + if (hasEnd) + out.writeListEnd(); + break; + } + + case INTEGER_ARRAY: + { + if (out.addRef(obj)) + return; + + int []data = (int []) obj; + + boolean hasEnd = out.writeListBegin(data.length, "[int"); + + for (int i = 0; i < data.length; i++) + out.writeInt(data[i]); + + if (hasEnd) + out.writeListEnd(); + + break; + } + + case LONG_ARRAY: + { + if (out.addRef(obj)) + return; + + long []data = (long []) obj; + + boolean hasEnd = out.writeListBegin(data.length, "[long"); + + for (int i = 0; i < data.length; i++) + out.writeLong(data[i]); + + if (hasEnd) + out.writeListEnd(); + break; + } + + case FLOAT_ARRAY: + { + if (out.addRef(obj)) + return; + + float []data = (float []) obj; + + boolean hasEnd = out.writeListBegin(data.length, "[float"); + + for (int i = 0; i < data.length; i++) + out.writeDouble(data[i]); + + if (hasEnd) + out.writeListEnd(); + break; + } + + case DOUBLE_ARRAY: + { + if (out.addRef(obj)) + return; + + double []data = (double []) obj; + boolean hasEnd = out.writeListBegin(data.length, "[double"); + + for (int i = 0; i < data.length; i++) + out.writeDouble(data[i]); + + if (hasEnd) + out.writeListEnd(); + break; + } + + case STRING_ARRAY: + { + if (out.addRef(obj)) + return; + + String []data = (String []) obj; + + boolean hasEnd = out.writeListBegin(data.length, "[string"); + + for (int i = 0; i < data.length; i++) { + out.writeString(data[i]); + } + + if (hasEnd) + out.writeListEnd(); + break; + } + + case CHARACTER_ARRAY: + { + char []data = (char []) obj; + out.writeString(data, 0, data.length); + break; + } + + case OBJECT_ARRAY: + { + if (out.addRef(obj)) + return; + + Object []data = (Object []) obj; + + boolean hasEnd = out.writeListBegin(data.length, "[object"); + + for (int i = 0; i < data.length; i++) { + out.writeObject(data[i]); + } + + if (hasEnd) + out.writeListEnd(); + break; + } + + case NULL: + out.writeNull(); + break; + + default: + throw new RuntimeException(code + " " + String.valueOf(obj.getClass())); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanDeserializer.java new file mode 100644 index 000000000000..f669c70c6f56 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanDeserializer.java @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashMap; + +/** + * Serializing an object for known object types. + */ +public class BeanDeserializer extends AbstractMapDeserializer { + private Class _type; + private HashMap _methodMap; + private Method _readResolve; + private Constructor _constructor; + private Object []_constructorArgs; + + public BeanDeserializer(Class cl) + { + _type = cl; + _methodMap = getMethodMap(cl); + + _readResolve = getReadResolve(cl); + + Constructor []constructors = cl.getConstructors(); + int bestLength = Integer.MAX_VALUE; + + for (int i = 0; i < constructors.length; i++) { + if (constructors[i].getParameterTypes().length < bestLength) { + _constructor = constructors[i]; + bestLength = _constructor.getParameterTypes().length; + } + } + + if (_constructor != null) { + _constructor.setAccessible(true); + Class []params = _constructor.getParameterTypes(); + _constructorArgs = new Object[params.length]; + for (int i = 0; i < params.length; i++) { + _constructorArgs[i] = getParamArg(params[i]); + } + } + } + + public Class getType() + { + return _type; + } + + public Object readMap(AbstractHessianInput in) + throws IOException + { + try { + Object obj = instantiate(); + + return readMap(in, obj); + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOExceptionWrapper(e); + } + } + + public Object readMap(AbstractHessianInput in, Object obj) + throws IOException + { + try { + int ref = in.addRef(obj); + + while (! in.isEnd()) { + Object key = in.readObject(); + + Method method = (Method) _methodMap.get(key); + + if (method != null) { + Object value = in.readObject(method.getParameterTypes()[0]); + + method.invoke(obj, new Object[] {value }); + } + else { + Object value = in.readObject(); + } + } + + in.readMapEnd(); + + Object resolve = resolve(obj); + + if (obj != resolve) + in.setRef(ref, resolve); + + return resolve; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOExceptionWrapper(e); + } + } + + private Object resolve(Object obj) + { + // if there's a readResolve method, call it + try { + if (_readResolve != null) + return _readResolve.invoke(obj, new Object[0]); + } catch (Exception e) { + } + + return obj; + } + + protected Object instantiate() + throws Exception + { + return _constructor.newInstance(_constructorArgs); + } + + /** + * Returns the readResolve method + */ + protected Method getReadResolve(Class cl) + { + for (; cl != null; cl = cl.getSuperclass()) { + Method []methods = cl.getDeclaredMethods(); + + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + + if (method.getName().equals("readResolve") && + method.getParameterTypes().length == 0) + return method; + } + } + + return null; + } + + /** + * Creates a map of the classes fields. + */ + protected HashMap getMethodMap(Class cl) + { + HashMap methodMap = new HashMap(); + + for (; cl != null; cl = cl.getSuperclass()) { + Method []methods = cl.getDeclaredMethods(); + + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + + if (Modifier.isStatic(method.getModifiers())) + continue; + + String name = method.getName(); + + if (! name.startsWith("set")) + continue; + + Class []paramTypes = method.getParameterTypes(); + if (paramTypes.length != 1) + continue; + + if (! method.getReturnType().equals(void.class)) + continue; + + if (findGetter(methods, name, paramTypes[0]) == null) + continue; + + // XXX: could parameterize the handler to only deal with public + try { + method.setAccessible(true); + } catch (Throwable e) { + e.printStackTrace(); + } + + name = name.substring(3); + + int j = 0; + for (; j < name.length() && Character.isUpperCase(name.charAt(j)); j++) { + } + + if (j == 1) + name = name.substring(0, j).toLowerCase() + name.substring(j); + else if (j > 1) + name = name.substring(0, j - 1).toLowerCase() + name.substring(j - 1); + + + methodMap.put(name, method); + } + } + + return methodMap; + } + + /** + * Finds any matching setter. + */ + private Method findGetter(Method []methods, String setterName, Class arg) + { + String getterName = "get" + setterName.substring(3); + + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + + if (! method.getName().equals(getterName)) + continue; + + if (! method.getReturnType().equals(arg)) + continue; + + Class []params = method.getParameterTypes(); + + if (params.length == 0) + return method; + } + + return null; + } + + /** + * Creates a map of the classes fields. + */ + protected static Object getParamArg(Class cl) + { + if (! cl.isPrimitive()) + return null; + else if (boolean.class.equals(cl)) + return Boolean.FALSE; + else if (byte.class.equals(cl)) + return Byte.valueOf((byte) 0); + else if (short.class.equals(cl)) + return Short.valueOf((short) 0); + else if (char.class.equals(cl)) + return Character.valueOf((char) 0); + else if (int.class.equals(cl)) + return Integer.valueOf(0); + else if (long.class.equals(cl)) + return Long.valueOf(0); + else if (float.class.equals(cl)) + return Double.valueOf(0); + else if (double.class.equals(cl)) + return Double.valueOf(0); + else + throw new UnsupportedOperationException(); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanSerializer.java new file mode 100644 index 000000000000..40dd16689163 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanSerializer.java @@ -0,0 +1,315 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.logging.*; + +/** + * Serializing an object for known object types. + */ +public class BeanSerializer extends AbstractSerializer { + private static final Logger log + = Logger.getLogger(BeanSerializer.class.getName()); + + private static final Object []NULL_ARGS = new Object[0]; + private Method []_methods; + private String []_names; + + private Object _writeReplaceFactory; + private Method _writeReplace; + + public BeanSerializer(Class cl, ClassLoader loader) + { + introspectWriteReplace(cl, loader); + + ArrayList primitiveMethods = new ArrayList(); + ArrayList compoundMethods = new ArrayList(); + + for (; cl != null; cl = cl.getSuperclass()) { + Method []methods = cl.getDeclaredMethods(); + + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + + if (Modifier.isStatic(method.getModifiers())) + continue; + + if (method.getParameterTypes().length != 0) + continue; + + String name = method.getName(); + + if (! name.startsWith("get")) + continue; + + Class type = method.getReturnType(); + + if (type.equals(void.class)) + continue; + + if (findSetter(methods, name, type) == null) + continue; + + // XXX: could parameterize the handler to only deal with public + method.setAccessible(true); + + if (type.isPrimitive() + || type.getName().startsWith("java.lang.") + && ! type.equals(Object.class)) + primitiveMethods.add(method); + else + compoundMethods.add(method); + } + } + + ArrayList methodList = new ArrayList(); + methodList.addAll(primitiveMethods); + methodList.addAll(compoundMethods); + + Collections.sort(methodList, new MethodNameCmp()); + + _methods = new Method[methodList.size()]; + methodList.toArray(_methods); + + _names = new String[_methods.length]; + + for (int i = 0; i < _methods.length; i++) { + String name = _methods[i].getName(); + + name = name.substring(3); + + int j = 0; + for (; j < name.length() && Character.isUpperCase(name.charAt(j)); j++) { + } + + if (j == 1) + name = name.substring(0, j).toLowerCase() + name.substring(j); + else if (j > 1) + name = name.substring(0, j - 1).toLowerCase() + name.substring(j - 1); + + _names[i] = name; + } + } + + private void introspectWriteReplace(Class cl, ClassLoader loader) + { + try { + String className = cl.getName() + "HessianSerializer"; + + Class serializerClass = Class.forName(className, false, loader); + + Object serializerObject = serializerClass.newInstance(); + + Method writeReplace = getWriteReplace(serializerClass, cl); + + if (writeReplace != null) { + _writeReplaceFactory = serializerObject; + _writeReplace = writeReplace; + + return; + } + } catch (ClassNotFoundException e) { + } catch (Exception e) { + log.log(Level.FINER, e.toString(), e); + } + + _writeReplace = getWriteReplace(cl); + } + + /** + * Returns the writeReplace method + */ + protected Method getWriteReplace(Class cl) + { + for (; cl != null; cl = cl.getSuperclass()) { + Method []methods = cl.getDeclaredMethods(); + + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + + if (method.getName().equals("writeReplace") && + method.getParameterTypes().length == 0) + return method; + } + } + + return null; + } + + /** + * Returns the writeReplace method + */ + protected Method getWriteReplace(Class cl, Class param) + { + for (; cl != null; cl = cl.getSuperclass()) { + for (Method method : cl.getDeclaredMethods()) { + if (method.getName().equals("writeReplace") + && method.getParameterTypes().length == 1 + && param.equals(method.getParameterTypes()[0])) + return method; + } + } + + return null; + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + if (out.addRef(obj)) + return; + + Class cl = obj.getClass(); + + try { + if (_writeReplace != null) { + Object repl; + + if (_writeReplaceFactory != null) + repl = _writeReplace.invoke(_writeReplaceFactory, obj); + else + repl = _writeReplace.invoke(obj); + + out.removeRef(obj); + + out.writeObject(repl); + + out.replaceRef(repl, obj); + + return; + } + } catch (Exception e) { + log.log(Level.FINER, e.toString(), e); + } + + int ref = out.writeObjectBegin(cl.getName()); + + if (ref < -1) { + // Hessian 1.1 uses a map + + for (int i = 0; i < _methods.length; i++) { + Method method = _methods[i]; + Object value = null; + + try { + value = _methods[i].invoke(obj, (Object []) null); + } catch (Exception e) { + log.log(Level.FINE, e.toString(), e); + } + + out.writeString(_names[i]); + + out.writeObject(value); + } + + out.writeMapEnd(); + } + else { + if (ref == -1) { + out.writeInt(_names.length); + + for (int i = 0; i < _names.length; i++) + out.writeString(_names[i]); + + out.writeObjectBegin(cl.getName()); + } + + for (int i = 0; i < _methods.length; i++) { + Method method = _methods[i]; + Object value = null; + + try { + value = _methods[i].invoke(obj, (Object []) null); + } catch (Exception e) { + log.log(Level.FINER, e.toString(), e); + } + + out.writeObject(value); + } + } + } + + /** + * Finds any matching setter. + */ + private Method findSetter(Method []methods, String getterName, Class arg) + { + String setterName = "set" + getterName.substring(3); + + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + + if (! method.getName().equals(setterName)) + continue; + + if (! method.getReturnType().equals(void.class)) + continue; + + Class []params = method.getParameterTypes(); + + if (params.length == 1 && params[0].equals(arg)) + return method; + } + + return null; + } + + static class MethodNameCmp implements Comparator { + public int compare(Method a, Method b) + { + return a.getName().compareTo(b.getName()); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanSerializerFactory.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanSerializerFactory.java new file mode 100644 index 000000000000..18a7f0323e26 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BeanSerializerFactory.java @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +/** + * Factory for returning serialization methods. + */ +public class BeanSerializerFactory extends SerializerFactory { + /** + * Returns the default serializer for a class that isn't matched + * directly. Application can override this method to produce + * bean-style serialization instead of field serialization. + * + * @param cl the class of the object that needs to be serialized. + * + * @return a serializer object for the serialization. + */ + protected Serializer getDefaultSerializer(Class cl) + { + return new BeanSerializer(cl, getClassLoader()); + } + + /** + * Returns the default deserializer for a class that isn't matched + * directly. Application can override this method to produce + * bean-style serialization instead of field serialization. + * + * @param cl the class of the object that needs to be serialized. + * + * @return a serializer object for the serialization. + */ + protected Deserializer getDefaultDeserializer(Class cl) + { + return new BeanDeserializer(cl); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BigIntegerDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BigIntegerDeserializer.java new file mode 100644 index 000000000000..e718bef3dbb5 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/BigIntegerDeserializer.java @@ -0,0 +1,18 @@ +package com.alibaba.com.caucho.hessian.io; + +import java.math.BigInteger; + +/** + * @author kimi + */ +public class BigIntegerDeserializer extends JavaDeserializer { + + public BigIntegerDeserializer() { + super(BigInteger.class); + } + + @Override + protected Object instantiate() throws Exception { + return new BigInteger("0"); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CalendarHandle.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CalendarHandle.java new file mode 100644 index 000000000000..ed752664dc3a --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CalendarHandle.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +/** + * Handle for a calendar object. + */ +public class CalendarHandle implements java.io.Serializable, HessianHandle { + private Class type; + private Date date; + + public CalendarHandle() + { + } + + public CalendarHandle(Class type, long time) + { + if (! GregorianCalendar.class.equals(type)) + this.type = type; + + this.date = new Date(time); + } + + private Object readResolve() + { + try { + Calendar cal; + + if (this.type != null) + cal = (Calendar) this.type.newInstance(); + else + cal = new GregorianCalendar(); + + cal.setTimeInMillis(this.date.getTime()); + + return cal; + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CalendarSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CalendarSerializer.java new file mode 100644 index 000000000000..bc48f262ff78 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CalendarSerializer.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.Calendar; + +/** + * Serializing a calendar. + */ +public class CalendarSerializer extends AbstractSerializer { + private static CalendarSerializer SERIALIZER = new CalendarSerializer(); + + public static CalendarSerializer create() + { + return SERIALIZER; + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + if (obj == null) + out.writeNull(); + else { + Calendar cal = (Calendar) obj; + + out.writeObject(new CalendarHandle(cal.getClass(), + cal.getTimeInMillis())); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ClassDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ClassDeserializer.java new file mode 100644 index 000000000000..e35c67d7cb3d --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ClassDeserializer.java @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.HashMap; + +/** + * Deserializing a JDK 1.2 Class. + */ +public class ClassDeserializer extends AbstractMapDeserializer { + private static final HashMap _primClasses + = new HashMap(); + + private ClassLoader _loader; + + public ClassDeserializer(ClassLoader loader) + { + _loader = loader; + } + + public Class getType() + { + return Class.class; + } + + public Object readMap(AbstractHessianInput in) + throws IOException + { + int ref = in.addRef(null); + + String name = null; + + while (! in.isEnd()) { + String key = in.readString(); + + if (key.equals("name")) + name = in.readString(); + else + in.readObject(); + } + + in.readMapEnd(); + + Object value = create(name); + + in.setRef(ref, value); + + return value; + } + + public Object readObject(AbstractHessianInput in, String []fieldNames) + throws IOException + { + int ref = in.addRef(null); + + String name = null; + + for (int i = 0; i < fieldNames.length; i++) { + if ("name".equals(fieldNames[i])) + name = in.readString(); + else + in.readObject(); + } + + Object value = create(name); + + in.setRef(ref, value); + + return value; + } + + Object create(String name) + throws IOException + { + if (name == null) + throw new IOException("Serialized Class expects name."); + + Class cl = _primClasses.get(name); + + if (cl != null) + return cl; + + try { + if (_loader != null) + return Class.forName(name, false, _loader); + else + return Class.forName(name); + } catch (Exception e) { + throw new IOExceptionWrapper(e); + } + } + + static { + _primClasses.put("void", void.class); + _primClasses.put("boolean", boolean.class); + _primClasses.put("java.lang.Boolean", Boolean.class); + _primClasses.put("byte", byte.class); + _primClasses.put("java.lang.Byte", Byte.class); + _primClasses.put("char", char.class); + _primClasses.put("java.lang.Character", Character.class); + _primClasses.put("short", short.class); + _primClasses.put("java.lang.Short", Short.class); + _primClasses.put("int", int.class); + _primClasses.put("java.lang.Integer", Integer.class); + _primClasses.put("long", long.class); + _primClasses.put("java.lang.Long", Long.class); + _primClasses.put("float", float.class); + _primClasses.put("java.lang.Float", Float.class); + _primClasses.put("double", double.class); + _primClasses.put("java.lang.Double", Double.class); + _primClasses.put("java.lang.String", String.class); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ClassSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ClassSerializer.java new file mode 100644 index 000000000000..5d7d6233cb16 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ClassSerializer.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Serializing a remote object. + */ +public class ClassSerializer extends AbstractSerializer { + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + Class cl = (Class) obj; + + if (cl == null) { + out.writeNull(); + } + else if (out.addRef(obj)) { + return; + } + else { + int ref = out.writeObjectBegin("java.lang.Class"); + + if (ref < -1) { + out.writeString("name"); + out.writeString(cl.getName()); + out.writeMapEnd(); + } + else { + if (ref == -1) { + out.writeInt(1); + out.writeString("name"); + out.writeObjectBegin("java.lang.Class"); + } + + out.writeString(cl.getName()); + } + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CollectionDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CollectionDeserializer.java new file mode 100644 index 000000000000..c71312061129 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CollectionDeserializer.java @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.*; + +/** + * Deserializing a JDK 1.2 Collection. + */ +public class CollectionDeserializer extends AbstractListDeserializer { + private Class _type; + + public CollectionDeserializer(Class type) + { + _type = type; + } + + public Class getType() + { + return _type; + } + + public Object readList(AbstractHessianInput in, int length) + throws IOException + { + Collection list = createList(); + + in.addRef(list); + + while (! in.isEnd()) + list.add(in.readObject()); + + in.readEnd(); + + return list; + } + + public Object readLengthList(AbstractHessianInput in, int length) + throws IOException + { + Collection list = createList(); + + in.addRef(list); + + for (; length > 0; length--) + list.add(in.readObject()); + + return list; + } + + private Collection createList() + throws IOException + { + Collection list = null; + + if (_type == null) + list = new ArrayList(); + else if (! _type.isInterface()) { + try { + list = (Collection) _type.newInstance(); + } catch (Exception e) { + } + } + + if (list != null) { + } + else if (SortedSet.class.isAssignableFrom(_type)) + list = new TreeSet(); + else if (Set.class.isAssignableFrom(_type)) + list = new HashSet(); + else if (List.class.isAssignableFrom(_type)) + list = new ArrayList(); + else if (Collection.class.isAssignableFrom(_type)) + list = new ArrayList(); + else { + try { + list = (Collection) _type.newInstance(); + } catch (Exception e) { + throw new IOExceptionWrapper(e); + } + } + + return list; + } +} + + diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CollectionSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CollectionSerializer.java new file mode 100644 index 000000000000..135acbf05a8b --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/CollectionSerializer.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; + +/** + * Serializing a JDK 1.2 Collection. + */ +public class CollectionSerializer extends AbstractSerializer +{ + private boolean _sendJavaType = true; + + /** + * Set true if the java type of the collection should be sent. + */ + public void setSendJavaType(boolean sendJavaType) + { + _sendJavaType = sendJavaType; + } + + /** + * Return true if the java type of the collection should be sent. + */ + public boolean getSendJavaType() + { + return _sendJavaType; + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + if (out.addRef(obj)) + return; + + Collection list = (Collection) obj; + + Class cl = obj.getClass(); + boolean hasEnd; + + if (cl.equals(ArrayList.class) + || ! _sendJavaType + || ! Serializable.class.isAssignableFrom(cl)) + hasEnd = out.writeListBegin(list.size(), null); + else + hasEnd = out.writeListBegin(list.size(), obj.getClass().getName()); + + Iterator iter = list.iterator(); + while (iter.hasNext()) { + Object value = iter.next(); + + out.writeObject(value); + } + + if (hasEnd) + out.writeListEnd(); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Deflation.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Deflation.java new file mode 100644 index 000000000000..68cd46ec3bf7 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Deflation.java @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.util.*; +import java.util.zip.*; + +import java.io.*; + +import com.alibaba.com.caucho.hessian.io.*; + +public class Deflation extends HessianEnvelope { + public Deflation() + { + } + + public Hessian2Output wrap(Hessian2Output out) + throws IOException + { + OutputStream os = new DeflateOutputStream(out); + + Hessian2Output filterOut = new Hessian2Output(os); + + filterOut.setCloseStreamOnClose(true); + + return filterOut; + } + + public Hessian2Input unwrap(Hessian2Input in) + throws IOException + { + int version = in.readEnvelope(); + + String method = in.readMethod(); + + if (! method.equals(getClass().getName())) + throw new IOException("expected hessian Envelope method '" + + getClass().getName() + "' at '" + method + "'"); + + return unwrapHeaders(in); + } + + public Hessian2Input unwrapHeaders(Hessian2Input in) + throws IOException + { + InputStream is = new DeflateInputStream(in); + + Hessian2Input filter = new Hessian2Input(is); + + filter.setCloseStreamOnClose(true); + + return filter; + } + + static class DeflateOutputStream extends OutputStream { + private Hessian2Output _out; + private OutputStream _bodyOut; + private DeflaterOutputStream _deflateOut; + + DeflateOutputStream(Hessian2Output out) + throws IOException + { + _out = out; + + _out.startEnvelope(Deflation.class.getName()); + + _out.writeInt(0); + + _bodyOut = _out.getBytesOutputStream(); + + _deflateOut = new DeflaterOutputStream(_bodyOut); + } + + public void write(int ch) + throws IOException + { + _deflateOut.write(ch); + } + + public void write(byte []buffer, int offset, int length) + throws IOException + { + _deflateOut.write(buffer, offset, length); + } + + public void close() + throws IOException + { + Hessian2Output out = _out; + _out = null; + + if (out != null) { + _deflateOut.close(); + _bodyOut.close(); + + out.writeInt(0); + + out.completeEnvelope(); + + out.close(); + } + } + } + + static class DeflateInputStream extends InputStream { + private Hessian2Input _in; + + private InputStream _bodyIn; + private InflaterInputStream _inflateIn; + + DeflateInputStream(Hessian2Input in) + throws IOException + { + _in = in; + + int len = in.readInt(); + + if (len != 0) + throw new IOException("expected no headers"); + + _bodyIn = _in.readInputStream(); + + _inflateIn = new InflaterInputStream(_bodyIn); + } + + public int read() + throws IOException + { + return _inflateIn.read(); + } + + public int read(byte []buffer, int offset, int length) + throws IOException + { + return _inflateIn.read(buffer, offset, length); + } + + public void close() + throws IOException + { + Hessian2Input in = _in; + _in = null; + + if (in != null) { + _inflateIn.close(); + _bodyIn.close(); + + int len = in.readInt(); + + if (len != 0) + throw new IOException("Unexpected footer"); + + in.completeEnvelope(); + + in.close(); + } + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Deserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Deserializer.java new file mode 100644 index 000000000000..5f8cb814b74e --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Deserializer.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Deserializing an object. + */ +public interface Deserializer { + public Class getType(); + + public Object readObject(AbstractHessianInput in) + throws IOException; + + public Object readList(AbstractHessianInput in, int length) + throws IOException; + + public Object readLengthList(AbstractHessianInput in, int length) + throws IOException; + + public Object readMap(AbstractHessianInput in) + throws IOException; + + public Object readObject(AbstractHessianInput in, String []fieldNames) + throws IOException; +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumDeserializer.java new file mode 100644 index 000000000000..fab492747c5b --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumDeserializer.java @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.lang.reflect.Method; + +/** + * Deserializing an enum valued object + */ +public class EnumDeserializer extends AbstractDeserializer { + private Class _enumType; + private Method _valueOf; + + public EnumDeserializer(Class cl) + { + // hessian/33b[34], hessian/3bb[78] + if (cl.isEnum()) + _enumType = cl; + else if (cl.getSuperclass().isEnum()) + _enumType = cl.getSuperclass(); + else + throw new RuntimeException("Class " + cl.getName() + " is not an enum"); + + try { + _valueOf = _enumType.getMethod("valueOf", + new Class[] { Class.class, String.class }); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public Class getType() + { + return _enumType; + } + + public Object readMap(AbstractHessianInput in) + throws IOException + { + String name = null; + + while (! in.isEnd()) { + String key = in.readString(); + + if (key.equals("name")) + name = in.readString(); + else + in.readObject(); + } + + in.readMapEnd(); + + Object obj = create(name); + + in.addRef(obj); + + return obj; + } + + public Object readObject(AbstractHessianInput in, String []fieldNames) + throws IOException + { + String name = null; + + for (int i = 0; i < fieldNames.length; i++) { + if ("name".equals(fieldNames[i])) + name = in.readString(); + else + in.readObject(); + } + + Object obj = create(name); + + in.addRef(obj); + + return obj; + } + + private Object create(String name) + throws IOException + { + if (name == null) + throw new IOException(_enumType.getName() + " expects name."); + + try { + return _valueOf.invoke(null, _enumType, name); + } catch (Exception e) { + throw new IOExceptionWrapper(e); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumSerializer.java new file mode 100644 index 000000000000..cfb0ee97420d --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumSerializer.java @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.lang.reflect.Method; + +/** + * Serializing an object for known object types. + */ +public class EnumSerializer extends AbstractSerializer { + private Method _name; + + public EnumSerializer(Class cl) + { + // hessian/32b[12], hessian/3ab[23] + if (! cl.isEnum() && cl.getSuperclass().isEnum()) + cl = cl.getSuperclass(); + + try { + _name = cl.getMethod("name", new Class[0]); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + if (out.addRef(obj)) + return; + + Class cl = obj.getClass(); + + if (! cl.isEnum() && cl.getSuperclass().isEnum()) + cl = cl.getSuperclass(); + + String name = null; + try { + name = (String) _name.invoke(obj, (Object[]) null); + } catch (Exception e) { + throw new RuntimeException(e); + } + + int ref = out.writeObjectBegin(cl.getName()); + + if (ref < -1) { + out.writeString("name"); + out.writeString(name); + out.writeMapEnd(); + } + else { + if (ref == -1) { + out.writeClassFieldLength(1); + out.writeString("name"); + out.writeObjectBegin(cl.getName()); + } + + out.writeString(name); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumerationDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumerationDeserializer.java new file mode 100644 index 000000000000..412fe758e892 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumerationDeserializer.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.Vector; + +/** + * Deserializing a JDK 1.2 Collection. + */ +public class EnumerationDeserializer extends AbstractListDeserializer { + private static EnumerationDeserializer _deserializer; + + public static EnumerationDeserializer create() + { + if (_deserializer == null) + _deserializer = new EnumerationDeserializer(); + + return _deserializer; + } + + public Object readList(AbstractHessianInput in, int length) + throws IOException + { + Vector list = new Vector(); + + in.addRef(list); + + while (! in.isEnd()) + list.add(in.readObject()); + + in.readEnd(); + + return list.elements(); + } +} + + diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumerationSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumerationSerializer.java new file mode 100644 index 000000000000..be116eb18c80 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnumerationSerializer.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.Enumeration; + +/** + * Serializing a JDK 1.2 Enumeration. + */ +public class EnumerationSerializer extends AbstractSerializer { + private static EnumerationSerializer _serializer; + + public static EnumerationSerializer create() + { + if (_serializer == null) + _serializer = new EnumerationSerializer(); + + return _serializer; + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + Enumeration iter = (Enumeration) obj; + + boolean hasEnd = out.writeListBegin(-1, null); + + while (iter.hasMoreElements()) { + Object value = iter.nextElement(); + + out.writeObject(value); + } + + if (hasEnd) + out.writeListEnd(); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnvelopeFactory.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnvelopeFactory.java new file mode 100644 index 000000000000..078c3edb50bb --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/EnvelopeFactory.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.util.logging.*; + +public class EnvelopeFactory +{ + private static final Logger log + = Logger.getLogger(EnvelopeFactory.class.getName()); +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ExtSerializerFactory.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ExtSerializerFactory.java new file mode 100644 index 000000000000..e19b8c935ad5 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ExtSerializerFactory.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.util.HashMap; + +/** + * Factory for returning serialization methods. + */ +public class ExtSerializerFactory extends AbstractSerializerFactory { + private HashMap _serializerMap = new HashMap(); + private HashMap _deserializerMap = new HashMap(); + + /** + * Adds a serializer. + * + * @param cl the class of the serializer + * @param serializer the serializer + */ + public void addSerializer(Class cl, Serializer serializer) + { + _serializerMap.put(cl, serializer); + } + + /** + * Adds a deserializer. + * + * @param cl the class of the deserializer + * @param deserializer the deserializer + */ + public void addDeserializer(Class cl, Deserializer deserializer) + { + _deserializerMap.put(cl, deserializer); + } + + /** + * Returns the serializer for a class. + * + * @param cl the class of the object that needs to be serialized. + * + * @return a serializer object for the serialization. + */ + public Serializer getSerializer(Class cl) + throws HessianProtocolException + { + return (Serializer) _serializerMap.get(cl); + } + + /** + * Returns the deserializer for a class. + * + * @param cl the class of the object that needs to be deserialized. + * + * @return a deserializer object for the serialization. + */ + public Deserializer getDeserializer(Class cl) + throws HessianProtocolException + { + return (Deserializer) _deserializerMap.get(cl); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Constants.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Constants.java new file mode 100644 index 000000000000..ebe93d8b6b2b --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Constants.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +public interface Hessian2Constants +{ + public static final int BC_BINARY = 'B'; // final chunk + public static final int BC_BINARY_CHUNK = 'A'; // non-final chunk + public static final int BC_BINARY_DIRECT = 0x20; // 1-byte length binary + public static final int BINARY_DIRECT_MAX = 0x0f; + public static final int BC_BINARY_SHORT = 0x34; // 2-byte length binary + public static final int BINARY_SHORT_MAX = 0x3ff; // 0-1023 binary + + public static final int BC_CLASS_DEF = 'C'; // object/class definition + + public static final int BC_DATE = 0x4a; // 64-bit millisecond UTC date + public static final int BC_DATE_MINUTE = 0x4b; // 32-bit minute UTC date + + public static final int BC_DOUBLE = 'D'; // IEEE 64-bit double + + public static final int BC_DOUBLE_ZERO = 0x5b; + public static final int BC_DOUBLE_ONE = 0x5c; + public static final int BC_DOUBLE_BYTE = 0x5d; + public static final int BC_DOUBLE_SHORT = 0x5e; + public static final int BC_DOUBLE_MILL = 0x5f; + + public static final int BC_FALSE = 'F'; // boolean false + + public static final int BC_INT = 'I'; // 32-bit int + + public static final int INT_DIRECT_MIN = -0x10; + public static final int INT_DIRECT_MAX = 0x2f; + public static final int BC_INT_ZERO = 0x90; + + public static final int INT_BYTE_MIN = -0x800; + public static final int INT_BYTE_MAX = 0x7ff; + public static final int BC_INT_BYTE_ZERO = 0xc8; + + public static final int BC_END = 'Z'; + + public static final int INT_SHORT_MIN = -0x40000; + public static final int INT_SHORT_MAX = 0x3ffff; + public static final int BC_INT_SHORT_ZERO = 0xd4; + + public static final int BC_LIST_VARIABLE =0x55; + public static final int BC_LIST_FIXED = 'V'; + public static final int BC_LIST_VARIABLE_UNTYPED = 0x57; + public static final int BC_LIST_FIXED_UNTYPED =0x58; + + public static final int BC_LIST_DIRECT = 0x70; + public static final int BC_LIST_DIRECT_UNTYPED = 0x78; + public static final int LIST_DIRECT_MAX = 0x7; + + public static final int BC_LONG = 'L'; // 64-bit signed integer + public static final long LONG_DIRECT_MIN = -0x08; + public static final long LONG_DIRECT_MAX = 0x0f; + public static final int BC_LONG_ZERO = 0xe0; + + public static final long LONG_BYTE_MIN = -0x800; + public static final long LONG_BYTE_MAX = 0x7ff; + public static final int BC_LONG_BYTE_ZERO = 0xf8; + + public static final int LONG_SHORT_MIN = -0x40000; + public static final int LONG_SHORT_MAX = 0x3ffff; + public static final int BC_LONG_SHORT_ZERO = 0x3c; + + public static final int BC_LONG_INT = 0x59; + + public static final int BC_MAP = 'M'; + public static final int BC_MAP_UNTYPED = 'H'; + + public static final int BC_NULL = 'N'; + + public static final int BC_OBJECT = 'O'; + public static final int BC_OBJECT_DEF = 'C'; + + public static final int BC_OBJECT_DIRECT = 0x60; + public static final int OBJECT_DIRECT_MAX = 0x0f; + + public static final int BC_REF = 0x51; + + public static final int BC_STRING = 'S'; // final string + public static final int BC_STRING_CHUNK = 'R'; // non-final string + + public static final int BC_STRING_DIRECT = 0x00; + public static final int STRING_DIRECT_MAX = 0x1f; + public static final int BC_STRING_SHORT = 0x30; + public static final int STRING_SHORT_MAX = 0x3ff; + + public static final int BC_TRUE = 'T'; + + public static final int P_PACKET_CHUNK = 0x4f; + public static final int P_PACKET = 'P'; + + public static final int P_PACKET_DIRECT = 0x80; + public static final int PACKET_DIRECT_MAX = 0x7f; + + public static final int P_PACKET_SHORT = 0x70; + public static final int PACKET_SHORT_MAX = 0xfff; +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Input.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Input.java new file mode 100644 index 000000000000..92d0ba01ed17 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Input.java @@ -0,0 +1,2798 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.*; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.logging.*; + +/** + * Input stream for Hessian requests. + * + *

HessianInput is unbuffered, so any client needs to provide + * its own buffering. + * + *

+ * InputStream is = ...; // from http connection
+ * HessianInput in = new HessianInput(is);
+ * String value;
+ *
+ * in.startReply();         // read reply header
+ * value = in.readString(); // read string value
+ * in.completeReply();      // read reply footer
+ * 
+ */ +public class Hessian2Input + extends AbstractHessianInput + implements Hessian2Constants +{ + private static final Logger log + = Logger.getLogger(Hessian2Input.class.getName()); + + private static final double D_256 = 1.0 / 256.0; + private static final int END_OF_DATA = -2; + + private static Field _detailMessageField; + + private static final int SIZE = 256; + private static final int GAP = 16; + + // factory for deserializing objects in the input stream + protected SerializerFactory _serializerFactory; + + private static boolean _isCloseStreamOnClose; + + protected ArrayList _refs; + protected ArrayList _classDefs; + protected ArrayList _types; + + // the underlying input stream + private InputStream _is; + private final byte []_buffer = new byte[SIZE]; + + // a peek character + private int _offset; + private int _length; + + // true for streaming data + private boolean _isStreaming; + + // the method for a call + private String _method; + private int _argLength; + + private Reader _chunkReader; + private InputStream _chunkInputStream; + + private Throwable _replyFault; + + private StringBuffer _sbuf = new StringBuffer(); + + // true if this is the last chunk + private boolean _isLastChunk; + // the chunk length + private int _chunkLength; + + /** + * Creates a new Hessian input stream, initialized with an + * underlying input stream. + * + * @param is the underlying input stream. + */ + public Hessian2Input(InputStream is) + { + _is = is; + } + + /** + * Sets the serializer factory. + */ + public void setSerializerFactory(SerializerFactory factory) + { + _serializerFactory = factory; + } + + /** + * Gets the serializer factory. + */ + public SerializerFactory getSerializerFactory() + { + return _serializerFactory; + } + + /** + * Gets the serializer factory, creating a default if necessary. + */ + public final SerializerFactory findSerializerFactory() + { + SerializerFactory factory = _serializerFactory; + + if (factory == null) + _serializerFactory = factory = new SerializerFactory(); + + return factory; + } + + public void setCloseStreamOnClose(boolean isClose) + { + _isCloseStreamOnClose = isClose; + } + + public boolean isCloseStreamOnClose() + { + return _isCloseStreamOnClose; + } + + /** + * Returns the calls method + */ + public String getMethod() + { + return _method; + } + + /** + * Returns any reply fault. + */ + public Throwable getReplyFault() + { + return _replyFault; + } + + /** + * Starts reading the call + * + *
+   * c major minor
+   * 
+ */ + public int readCall() + throws IOException + { + int tag = read(); + + if (tag != 'C') + throw error("expected hessian call ('C') at " + codeName(tag)); + + return 0; + } + + /** + * Starts reading the envelope + * + *
+   * E major minor
+   * 
+ */ + public int readEnvelope() + throws IOException + { + int tag = read(); + int version = 0; + + if (tag == 'H') { + int major = read(); + int minor = read(); + + version = (major << 16) + minor; + + tag = read(); + } + + if (tag != 'E') + throw error("expected hessian Envelope ('E') at " + codeName(tag)); + + return version; + } + + /** + * Completes reading the envelope + * + *

A successful completion will have a single value: + * + *

+   * Z
+   * 
+ */ + public void completeEnvelope() + throws IOException + { + int tag = read(); + + if (tag != 'Z') + error("expected end of envelope at " + codeName(tag)); + } + + /** + * Starts reading the call + * + *

A successful completion will have a single value: + * + *

+   * string
+   * 
+ */ + public String readMethod() + throws IOException + { + _method = readString(); + + return _method; + } + + /** + * Returns the number of method arguments + * + *
+   * int
+   * 
+ */ + @Override + public int readMethodArgLength() + throws IOException + { + return readInt(); + } + + /** + * Starts reading the call, including the headers. + * + *

The call expects the following protocol data + * + *

+   * c major minor
+   * m b16 b8 method
+   * 
+ */ + public void startCall() + throws IOException + { + readCall(); + + readMethod(); + } + + /** + * Completes reading the call + * + *

A successful completion will have a single value: + * + *

+   * 
+ */ + public void completeCall() + throws IOException + { + } + + /** + * Reads a reply as an object. + * If the reply has a fault, throws the exception. + */ + @Override + public Object readReply(Class expectedClass) + throws Throwable + { + int tag = read(); + + if (tag == 'R') + return readObject(expectedClass); + else if (tag == 'F') { + HashMap map = (HashMap) readObject(HashMap.class); + + throw prepareFault(map); + } + else { + StringBuilder sb = new StringBuilder(); + sb.append((char) tag); + + try { + int ch; + + while ((ch = read()) >= 0) { + sb.append((char) ch); + } + } catch (IOException e) { + log.log(Level.FINE, e.toString(), e); + } + + throw error("expected hessian reply at " + codeName(tag) + "\n" + + sb); + } + } + + /** + * Starts reading the reply + * + *

A successful completion will have a single value: + * + *

+   * r
+   * 
+ */ + public void startReply() + throws Throwable + { + // XXX: for variable length (?) + + readReply(Object.class); + } + + /** + * Prepares the fault. + */ + private Throwable prepareFault(HashMap fault) + throws IOException + { + Object detail = fault.get("detail"); + String message = (String) fault.get("message"); + + if (detail instanceof Throwable) { + _replyFault = (Throwable) detail; + + if (message != null && _detailMessageField != null) { + try { + _detailMessageField.set(_replyFault, message); + } catch (Throwable e) { + } + } + + return _replyFault; + } + + else { + String code = (String) fault.get("code"); + + _replyFault = new HessianServiceException(message, code, detail); + + return _replyFault; + } + } + + /** + * Completes reading the call + * + *

A successful completion will have a single value: + * + *

+   * z
+   * 
+ */ + public void completeReply() + throws IOException + { + } + + /** + * Completes reading the call + * + *

A successful completion will have a single value: + * + *

+   * z
+   * 
+ */ + public void completeValueReply() + throws IOException + { + int tag = read(); + + if (tag != 'Z') + error("expected end of reply at " + codeName(tag)); + } + + /** + * Reads a header, returning null if there are no headers. + * + *
+   * H b16 b8 value
+   * 
+ */ + public String readHeader() + throws IOException + { + return null; + } + + /** + * Starts reading the message + * + *
+   * p major minor
+   * 
+ */ + public int startMessage() + throws IOException + { + int tag = read(); + + if (tag == 'p') + _isStreaming = false; + else if (tag == 'P') + _isStreaming = true; + else + throw error("expected Hessian message ('p') at " + codeName(tag)); + + int major = read(); + int minor = read(); + + return (major << 16) + minor; + } + + /** + * Completes reading the message + * + *

A successful completion will have a single value: + * + *

+   * z
+   * 
+ */ + public void completeMessage() + throws IOException + { + int tag = read(); + + if (tag != 'Z') + error("expected end of message at " + codeName(tag)); + } + + /** + * Reads a null + * + *
+   * N
+   * 
+ */ + public void readNull() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': return; + + default: + throw expect("null", tag); + } + } + + /** + * Reads a boolean + * + *
+   * T
+   * F
+   * 
+ */ + public boolean readBoolean() + throws IOException + { + int tag = _offset < _length ? (_buffer[_offset++] & 0xff) : read(); + + switch (tag) { + case 'T': return true; + case 'F': return false; + + // direct integer + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8a: case 0x8b: + case 0x8c: case 0x8d: case 0x8e: case 0x8f: + + case 0x90: case 0x91: case 0x92: case 0x93: + case 0x94: case 0x95: case 0x96: case 0x97: + case 0x98: case 0x99: case 0x9a: case 0x9b: + case 0x9c: case 0x9d: case 0x9e: case 0x9f: + + case 0xa0: case 0xa1: case 0xa2: case 0xa3: + case 0xa4: case 0xa5: case 0xa6: case 0xa7: + case 0xa8: case 0xa9: case 0xaa: case 0xab: + case 0xac: case 0xad: case 0xae: case 0xaf: + + case 0xb0: case 0xb1: case 0xb2: case 0xb3: + case 0xb4: case 0xb5: case 0xb6: case 0xb7: + case 0xb8: case 0xb9: case 0xba: case 0xbb: + case 0xbc: case 0xbd: case 0xbe: case 0xbf: + return tag != BC_INT_ZERO; + + // INT_BYTE = 0 + case 0xc8: + return read() != 0; + + // INT_BYTE != 0 + case 0xc0: case 0xc1: case 0xc2: case 0xc3: + case 0xc4: case 0xc5: case 0xc6: case 0xc7: + case 0xc9: case 0xca: case 0xcb: + case 0xcc: case 0xcd: case 0xce: case 0xcf: + read(); + return true; + + // INT_SHORT = 0 + case 0xd4: + return (256 * read() + read()) != 0; + + // INT_SHORT != 0 + case 0xd0: case 0xd1: case 0xd2: case 0xd3: + case 0xd5: case 0xd6: case 0xd7: + read(); + read(); + return true; + + case 'I': return + parseInt() != 0; + + case 0xd8: case 0xd9: case 0xda: case 0xdb: + case 0xdc: case 0xdd: case 0xde: case 0xdf: + + case 0xe0: case 0xe1: case 0xe2: case 0xe3: + case 0xe4: case 0xe5: case 0xe6: case 0xe7: + case 0xe8: case 0xe9: case 0xea: case 0xeb: + case 0xec: case 0xed: case 0xee: case 0xef: + return tag != BC_LONG_ZERO; + + // LONG_BYTE = 0 + case 0xf8: + return read() != 0; + + // LONG_BYTE != 0 + case 0xf0: case 0xf1: case 0xf2: case 0xf3: + case 0xf4: case 0xf5: case 0xf6: case 0xf7: + case 0xf9: case 0xfa: case 0xfb: + case 0xfc: case 0xfd: case 0xfe: case 0xff: + read(); + return true; + + // INT_SHORT = 0 + case 0x3c: + return (256 * read() + read()) != 0; + + // INT_SHORT != 0 + case 0x38: case 0x39: case 0x3a: case 0x3b: + case 0x3d: case 0x3e: case 0x3f: + read(); + read(); + return true; + + case BC_LONG_INT: + return (0x1000000L * read() + + 0x10000L * read() + + 0x100 * read() + + read()) != 0; + + case 'L': + return parseLong() != 0; + + case BC_DOUBLE_ZERO: + return false; + + case BC_DOUBLE_ONE: + return true; + + case BC_DOUBLE_BYTE: + return read() != 0; + + case BC_DOUBLE_SHORT: + return (0x100 * read() + read()) != 0; + + case BC_DOUBLE_MILL: + { + int mills = parseInt(); + + return mills != 0; + } + + case 'D': + return parseDouble() != 0.0; + + case 'N': + return false; + + default: + throw expect("boolean", tag); + } + } + + /** + * Reads a short + * + *
+   * I b32 b24 b16 b8
+   * 
+ */ + public short readShort() + throws IOException + { + return (short) readInt(); + } + + /** + * Reads an integer + * + *
+   * I b32 b24 b16 b8
+   * 
+ */ + public final int readInt() + throws IOException + { + //int tag = _offset < _length ? (_buffer[_offset++] & 0xff) : read(); + int tag = read(); + + switch (tag) { + case 'N': + return 0; + + case 'F': + return 0; + + case 'T': + return 1; + + // direct integer + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8a: case 0x8b: + case 0x8c: case 0x8d: case 0x8e: case 0x8f: + + case 0x90: case 0x91: case 0x92: case 0x93: + case 0x94: case 0x95: case 0x96: case 0x97: + case 0x98: case 0x99: case 0x9a: case 0x9b: + case 0x9c: case 0x9d: case 0x9e: case 0x9f: + + case 0xa0: case 0xa1: case 0xa2: case 0xa3: + case 0xa4: case 0xa5: case 0xa6: case 0xa7: + case 0xa8: case 0xa9: case 0xaa: case 0xab: + case 0xac: case 0xad: case 0xae: case 0xaf: + + case 0xb0: case 0xb1: case 0xb2: case 0xb3: + case 0xb4: case 0xb5: case 0xb6: case 0xb7: + case 0xb8: case 0xb9: case 0xba: case 0xbb: + case 0xbc: case 0xbd: case 0xbe: case 0xbf: + return tag - BC_INT_ZERO; + + /* byte int */ + case 0xc0: case 0xc1: case 0xc2: case 0xc3: + case 0xc4: case 0xc5: case 0xc6: case 0xc7: + case 0xc8: case 0xc9: case 0xca: case 0xcb: + case 0xcc: case 0xcd: case 0xce: case 0xcf: + return ((tag - BC_INT_BYTE_ZERO) << 8) + read(); + + /* short int */ + case 0xd0: case 0xd1: case 0xd2: case 0xd3: + case 0xd4: case 0xd5: case 0xd6: case 0xd7: + return ((tag - BC_INT_SHORT_ZERO) << 16) + 256 * read() + read(); + + case 'I': + case BC_LONG_INT: + return ((read() << 24) + + (read() << 16) + + (read() << 8) + + read()); + + // direct long + case 0xd8: case 0xd9: case 0xda: case 0xdb: + case 0xdc: case 0xdd: case 0xde: case 0xdf: + + case 0xe0: case 0xe1: case 0xe2: case 0xe3: + case 0xe4: case 0xe5: case 0xe6: case 0xe7: + case 0xe8: case 0xe9: case 0xea: case 0xeb: + case 0xec: case 0xed: case 0xee: case 0xef: + return tag - BC_LONG_ZERO; + + /* byte long */ + case 0xf0: case 0xf1: case 0xf2: case 0xf3: + case 0xf4: case 0xf5: case 0xf6: case 0xf7: + case 0xf8: case 0xf9: case 0xfa: case 0xfb: + case 0xfc: case 0xfd: case 0xfe: case 0xff: + return ((tag - BC_LONG_BYTE_ZERO) << 8) + read(); + + /* short long */ + case 0x38: case 0x39: case 0x3a: case 0x3b: + case 0x3c: case 0x3d: case 0x3e: case 0x3f: + return ((tag - BC_LONG_SHORT_ZERO) << 16) + 256 * read() + read(); + + case 'L': + return (int) parseLong(); + + case BC_DOUBLE_ZERO: + return 0; + + case BC_DOUBLE_ONE: + return 1; + + //case LONG_BYTE: + case BC_DOUBLE_BYTE: + return (byte) (_offset < _length ? _buffer[_offset++] : read()); + + //case INT_SHORT: + //case LONG_SHORT: + case BC_DOUBLE_SHORT: + return (short) (256 * read() + read()); + + case BC_DOUBLE_MILL: + { + int mills = parseInt(); + + return (int) (0.001 * mills); + } + + case 'D': + return (int) parseDouble(); + + default: + throw expect("integer", tag); + } + } + + /** + * Reads a long + * + *
+   * L b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + public long readLong() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': + return 0; + + case 'F': + return 0; + + case 'T': + return 1; + + // direct integer + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8a: case 0x8b: + case 0x8c: case 0x8d: case 0x8e: case 0x8f: + + case 0x90: case 0x91: case 0x92: case 0x93: + case 0x94: case 0x95: case 0x96: case 0x97: + case 0x98: case 0x99: case 0x9a: case 0x9b: + case 0x9c: case 0x9d: case 0x9e: case 0x9f: + + case 0xa0: case 0xa1: case 0xa2: case 0xa3: + case 0xa4: case 0xa5: case 0xa6: case 0xa7: + case 0xa8: case 0xa9: case 0xaa: case 0xab: + case 0xac: case 0xad: case 0xae: case 0xaf: + + case 0xb0: case 0xb1: case 0xb2: case 0xb3: + case 0xb4: case 0xb5: case 0xb6: case 0xb7: + case 0xb8: case 0xb9: case 0xba: case 0xbb: + case 0xbc: case 0xbd: case 0xbe: case 0xbf: + return tag - BC_INT_ZERO; + + /* byte int */ + case 0xc0: case 0xc1: case 0xc2: case 0xc3: + case 0xc4: case 0xc5: case 0xc6: case 0xc7: + case 0xc8: case 0xc9: case 0xca: case 0xcb: + case 0xcc: case 0xcd: case 0xce: case 0xcf: + return ((tag - BC_INT_BYTE_ZERO) << 8) + read(); + + /* short int */ + case 0xd0: case 0xd1: case 0xd2: case 0xd3: + case 0xd4: case 0xd5: case 0xd6: case 0xd7: + return ((tag - BC_INT_SHORT_ZERO) << 16) + 256 * read() + read(); + + //case LONG_BYTE: + case BC_DOUBLE_BYTE: + return (byte) (_offset < _length ? _buffer[_offset++] : read()); + + //case INT_SHORT: + //case LONG_SHORT: + case BC_DOUBLE_SHORT: + return (short) (256 * read() + read()); + + case 'I': + case BC_LONG_INT: + return parseInt(); + + // direct long + case 0xd8: case 0xd9: case 0xda: case 0xdb: + case 0xdc: case 0xdd: case 0xde: case 0xdf: + + case 0xe0: case 0xe1: case 0xe2: case 0xe3: + case 0xe4: case 0xe5: case 0xe6: case 0xe7: + case 0xe8: case 0xe9: case 0xea: case 0xeb: + case 0xec: case 0xed: case 0xee: case 0xef: + return tag - BC_LONG_ZERO; + + /* byte long */ + case 0xf0: case 0xf1: case 0xf2: case 0xf3: + case 0xf4: case 0xf5: case 0xf6: case 0xf7: + case 0xf8: case 0xf9: case 0xfa: case 0xfb: + case 0xfc: case 0xfd: case 0xfe: case 0xff: + return ((tag - BC_LONG_BYTE_ZERO) << 8) + read(); + + /* short long */ + case 0x38: case 0x39: case 0x3a: case 0x3b: + case 0x3c: case 0x3d: case 0x3e: case 0x3f: + return ((tag - BC_LONG_SHORT_ZERO) << 16) + 256 * read() + read(); + + case 'L': + return parseLong(); + + case BC_DOUBLE_ZERO: + return 0; + + case BC_DOUBLE_ONE: + return 1; + + case BC_DOUBLE_MILL: + { + int mills = parseInt(); + + return (long) (0.001 * mills); + } + + case 'D': + return (long) parseDouble(); + + default: + throw expect("long", tag); + } + } + + /** + * Reads a float + * + *
+   * D b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + public float readFloat() + throws IOException + { + return (float) readDouble(); + } + + /** + * Reads a double + * + *
+   * D b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + public double readDouble() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': + return 0; + + case 'F': + return 0; + + case 'T': + return 1; + + // direct integer + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8a: case 0x8b: + case 0x8c: case 0x8d: case 0x8e: case 0x8f: + + case 0x90: case 0x91: case 0x92: case 0x93: + case 0x94: case 0x95: case 0x96: case 0x97: + case 0x98: case 0x99: case 0x9a: case 0x9b: + case 0x9c: case 0x9d: case 0x9e: case 0x9f: + + case 0xa0: case 0xa1: case 0xa2: case 0xa3: + case 0xa4: case 0xa5: case 0xa6: case 0xa7: + case 0xa8: case 0xa9: case 0xaa: case 0xab: + case 0xac: case 0xad: case 0xae: case 0xaf: + + case 0xb0: case 0xb1: case 0xb2: case 0xb3: + case 0xb4: case 0xb5: case 0xb6: case 0xb7: + case 0xb8: case 0xb9: case 0xba: case 0xbb: + case 0xbc: case 0xbd: case 0xbe: case 0xbf: + return tag - 0x90; + + /* byte int */ + case 0xc0: case 0xc1: case 0xc2: case 0xc3: + case 0xc4: case 0xc5: case 0xc6: case 0xc7: + case 0xc8: case 0xc9: case 0xca: case 0xcb: + case 0xcc: case 0xcd: case 0xce: case 0xcf: + return ((tag - BC_INT_BYTE_ZERO) << 8) + read(); + + /* short int */ + case 0xd0: case 0xd1: case 0xd2: case 0xd3: + case 0xd4: case 0xd5: case 0xd6: case 0xd7: + return ((tag - BC_INT_SHORT_ZERO) << 16) + 256 * read() + read(); + + case 'I': + case BC_LONG_INT: + return parseInt(); + + // direct long + case 0xd8: case 0xd9: case 0xda: case 0xdb: + case 0xdc: case 0xdd: case 0xde: case 0xdf: + + case 0xe0: case 0xe1: case 0xe2: case 0xe3: + case 0xe4: case 0xe5: case 0xe6: case 0xe7: + case 0xe8: case 0xe9: case 0xea: case 0xeb: + case 0xec: case 0xed: case 0xee: case 0xef: + return tag - BC_LONG_ZERO; + + /* byte long */ + case 0xf0: case 0xf1: case 0xf2: case 0xf3: + case 0xf4: case 0xf5: case 0xf6: case 0xf7: + case 0xf8: case 0xf9: case 0xfa: case 0xfb: + case 0xfc: case 0xfd: case 0xfe: case 0xff: + return ((tag - BC_LONG_BYTE_ZERO) << 8) + read(); + + /* short long */ + case 0x38: case 0x39: case 0x3a: case 0x3b: + case 0x3c: case 0x3d: case 0x3e: case 0x3f: + return ((tag - BC_LONG_SHORT_ZERO) << 16) + 256 * read() + read(); + + case 'L': + return (double) parseLong(); + + case BC_DOUBLE_ZERO: + return 0; + + case BC_DOUBLE_ONE: + return 1; + + case BC_DOUBLE_BYTE: + return (byte) (_offset < _length ? _buffer[_offset++] : read()); + + case BC_DOUBLE_SHORT: + return (short) (256 * read() + read()); + + case BC_DOUBLE_MILL: + { + int mills = parseInt(); + + return 0.001 * mills; + } + + case 'D': + return parseDouble(); + + default: + throw expect("double", tag); + } + } + + /** + * Reads a date. + * + *
+   * T b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + public long readUTCDate() + throws IOException + { + int tag = read(); + + if (tag == BC_DATE) { + return parseLong(); + } + else if (tag == BC_DATE_MINUTE) { + return parseInt() * 60000L; + } + else + throw expect("date", tag); + } + + /** + * Reads a byte from the stream. + */ + public int readChar() + throws IOException + { + if (_chunkLength > 0) { + _chunkLength--; + if (_chunkLength == 0 && _isLastChunk) + _chunkLength = END_OF_DATA; + + int ch = parseUTF8Char(); + return ch; + } + else if (_chunkLength == END_OF_DATA) { + _chunkLength = 0; + return -1; + } + + int tag = read(); + + switch (tag) { + case 'N': + return -1; + + case 'S': + case BC_STRING_CHUNK: + _isLastChunk = tag == 'S'; + _chunkLength = (read() << 8) + read(); + + _chunkLength--; + int value = parseUTF8Char(); + + // special code so successive read byte won't + // be read as a single object. + if (_chunkLength == 0 && _isLastChunk) + _chunkLength = END_OF_DATA; + + return value; + + default: + throw expect("char", tag); + } + } + + /** + * Reads a byte array from the stream. + */ + public int readString(char []buffer, int offset, int length) + throws IOException + { + int readLength = 0; + + if (_chunkLength == END_OF_DATA) { + _chunkLength = 0; + return -1; + } + else if (_chunkLength == 0) { + int tag = read(); + + switch (tag) { + case 'N': + return -1; + + case 'S': + case BC_STRING_CHUNK: + _isLastChunk = tag == 'S'; + _chunkLength = (read() << 8) + read(); + break; + + case 0x00: case 0x01: case 0x02: case 0x03: + case 0x04: case 0x05: case 0x06: case 0x07: + case 0x08: case 0x09: case 0x0a: case 0x0b: + case 0x0c: case 0x0d: case 0x0e: case 0x0f: + + case 0x10: case 0x11: case 0x12: case 0x13: + case 0x14: case 0x15: case 0x16: case 0x17: + case 0x18: case 0x19: case 0x1a: case 0x1b: + case 0x1c: case 0x1d: case 0x1e: case 0x1f: + _isLastChunk = true; + _chunkLength = tag - 0x00; + break; + + default: + throw expect("string", tag); + } + } + + while (length > 0) { + if (_chunkLength > 0) { + buffer[offset++] = (char) parseUTF8Char(); + _chunkLength--; + length--; + readLength++; + } + else if (_isLastChunk) { + if (readLength == 0) + return -1; + else { + _chunkLength = END_OF_DATA; + return readLength; + } + } + else { + int tag = read(); + + switch (tag) { + case 'S': + case BC_STRING_CHUNK: + _isLastChunk = tag == 'S'; + _chunkLength = (read() << 8) + read(); + break; + + default: + throw expect("string", tag); + } + } + } + + if (readLength == 0) + return -1; + else if (_chunkLength > 0 || ! _isLastChunk) + return readLength; + else { + _chunkLength = END_OF_DATA; + return readLength; + } + } + + /** + * Reads a string + * + *
+   * S b16 b8 string value
+   * 
+ */ + public String readString() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': + return null; + case 'T': + return "true"; + case 'F': + return "false"; + + // direct integer + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8a: case 0x8b: + case 0x8c: case 0x8d: case 0x8e: case 0x8f: + + case 0x90: case 0x91: case 0x92: case 0x93: + case 0x94: case 0x95: case 0x96: case 0x97: + case 0x98: case 0x99: case 0x9a: case 0x9b: + case 0x9c: case 0x9d: case 0x9e: case 0x9f: + + case 0xa0: case 0xa1: case 0xa2: case 0xa3: + case 0xa4: case 0xa5: case 0xa6: case 0xa7: + case 0xa8: case 0xa9: case 0xaa: case 0xab: + case 0xac: case 0xad: case 0xae: case 0xaf: + + case 0xb0: case 0xb1: case 0xb2: case 0xb3: + case 0xb4: case 0xb5: case 0xb6: case 0xb7: + case 0xb8: case 0xb9: case 0xba: case 0xbb: + case 0xbc: case 0xbd: case 0xbe: case 0xbf: + return String.valueOf((tag - 0x90)); + + /* byte int */ + case 0xc0: case 0xc1: case 0xc2: case 0xc3: + case 0xc4: case 0xc5: case 0xc6: case 0xc7: + case 0xc8: case 0xc9: case 0xca: case 0xcb: + case 0xcc: case 0xcd: case 0xce: case 0xcf: + return String.valueOf(((tag - BC_INT_BYTE_ZERO) << 8) + read()); + + /* short int */ + case 0xd0: case 0xd1: case 0xd2: case 0xd3: + case 0xd4: case 0xd5: case 0xd6: case 0xd7: + return String.valueOf(((tag - BC_INT_SHORT_ZERO) << 16) + + 256 * read() + read()); + + case 'I': + case BC_LONG_INT: + return String.valueOf(parseInt()); + + // direct long + case 0xd8: case 0xd9: case 0xda: case 0xdb: + case 0xdc: case 0xdd: case 0xde: case 0xdf: + + case 0xe0: case 0xe1: case 0xe2: case 0xe3: + case 0xe4: case 0xe5: case 0xe6: case 0xe7: + case 0xe8: case 0xe9: case 0xea: case 0xeb: + case 0xec: case 0xed: case 0xee: case 0xef: + return String.valueOf(tag - BC_LONG_ZERO); + + /* byte long */ + case 0xf0: case 0xf1: case 0xf2: case 0xf3: + case 0xf4: case 0xf5: case 0xf6: case 0xf7: + case 0xf8: case 0xf9: case 0xfa: case 0xfb: + case 0xfc: case 0xfd: case 0xfe: case 0xff: + return String.valueOf(((tag - BC_LONG_BYTE_ZERO) << 8) + read()); + + /* short long */ + case 0x38: case 0x39: case 0x3a: case 0x3b: + case 0x3c: case 0x3d: case 0x3e: case 0x3f: + return String.valueOf(((tag - BC_LONG_SHORT_ZERO) << 16) + + 256 * read() + read()); + + case 'L': + return String.valueOf(parseLong()); + + case BC_DOUBLE_ZERO: + return "0.0"; + + case BC_DOUBLE_ONE: + return "1.0"; + + case BC_DOUBLE_BYTE: + return String.valueOf((byte) (_offset < _length + ? _buffer[_offset++] + : read())); + + case BC_DOUBLE_SHORT: + return String.valueOf(((short) (256 * read() + read()))); + + case BC_DOUBLE_MILL: + { + int mills = parseInt(); + + return String.valueOf(0.001 * mills); + } + + case 'D': + return String.valueOf(parseDouble()); + + case 'S': + case BC_STRING_CHUNK: + _isLastChunk = tag == 'S'; + _chunkLength = (read() << 8) + read(); + + _sbuf.setLength(0); + int ch; + + while ((ch = parseChar()) >= 0) + _sbuf.append((char) ch); + + return _sbuf.toString(); + + // 0-byte string + case 0x00: case 0x01: case 0x02: case 0x03: + case 0x04: case 0x05: case 0x06: case 0x07: + case 0x08: case 0x09: case 0x0a: case 0x0b: + case 0x0c: case 0x0d: case 0x0e: case 0x0f: + + case 0x10: case 0x11: case 0x12: case 0x13: + case 0x14: case 0x15: case 0x16: case 0x17: + case 0x18: case 0x19: case 0x1a: case 0x1b: + case 0x1c: case 0x1d: case 0x1e: case 0x1f: + _isLastChunk = true; + _chunkLength = tag - 0x00; + + _sbuf.setLength(0); + + while ((ch = parseChar()) >= 0) + _sbuf.append((char) ch); + + return _sbuf.toString(); + + case 0x30: case 0x31: case 0x32: case 0x33: + _isLastChunk = true; + _chunkLength = (tag - 0x30) * 256 + read(); + + _sbuf.setLength(0); + + while ((ch = parseChar()) >= 0) + _sbuf.append((char) ch); + + return _sbuf.toString(); + + default: + throw expect("string", tag); + } + } + + /** + * Reads a byte array + * + *
+   * B b16 b8 data value
+   * 
+ */ + public byte []readBytes() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': + return null; + + case 'B': + case BC_BINARY_CHUNK: + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + int data; + while ((data = parseByte()) >= 0) + bos.write(data); + + return bos.toByteArray(); + + case 0x20: case 0x21: case 0x22: case 0x23: + case 0x24: case 0x25: case 0x26: case 0x27: + case 0x28: case 0x29: case 0x2a: case 0x2b: + case 0x2c: case 0x2d: case 0x2e: case 0x2f: + { + _isLastChunk = true; + _chunkLength = tag - 0x20; + + byte []buffer = new byte[_chunkLength]; + + int k = 0; + while ((data = parseByte()) >= 0) + buffer[k++] = (byte) data; + + return buffer; + } + + case 0x34: case 0x35: case 0x36: case 0x37: + { + _isLastChunk = true; + _chunkLength = (tag - 0x34) * 256 + read(); + + byte []buffer = new byte[_chunkLength]; + int k = 0; + + while ((data = parseByte()) >= 0) { + buffer[k++] = (byte) data; + } + + return buffer; + } + + default: + throw expect("bytes", tag); + } + } + + /** + * Reads a byte from the stream. + */ + public int readByte() + throws IOException + { + if (_chunkLength > 0) { + _chunkLength--; + if (_chunkLength == 0 && _isLastChunk) + _chunkLength = END_OF_DATA; + + return read(); + } + else if (_chunkLength == END_OF_DATA) { + _chunkLength = 0; + return -1; + } + + int tag = read(); + + switch (tag) { + case 'N': + return -1; + + case 'B': + case BC_BINARY_CHUNK: + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + + int value = parseByte(); + + // special code so successive read byte won't + // be read as a single object. + if (_chunkLength == 0 && _isLastChunk) + _chunkLength = END_OF_DATA; + + return value; + + default: + throw expect("binary", tag); + } + } + + /** + * Reads a byte array from the stream. + */ + public int readBytes(byte []buffer, int offset, int length) + throws IOException + { + int readLength = 0; + + if (_chunkLength == END_OF_DATA) { + _chunkLength = 0; + return -1; + } + else if (_chunkLength == 0) { + int tag = read(); + + switch (tag) { + case 'N': + return -1; + + case 'B': + case BC_BINARY_CHUNK: + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + break; + + default: + throw expect("binary", tag); + } + } + + while (length > 0) { + if (_chunkLength > 0) { + buffer[offset++] = (byte) read(); + _chunkLength--; + length--; + readLength++; + } + else if (_isLastChunk) { + if (readLength == 0) + return -1; + else { + _chunkLength = END_OF_DATA; + return readLength; + } + } + else { + int tag = read(); + + switch (tag) { + case 'B': + case BC_BINARY_CHUNK: + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + break; + + default: + throw expect("binary", tag); + } + } + } + + if (readLength == 0) + return -1; + else if (_chunkLength > 0 || ! _isLastChunk) + return readLength; + else { + _chunkLength = END_OF_DATA; + return readLength; + } + } + + /** + * Reads a fault. + */ + private HashMap readFault() + throws IOException + { + HashMap map = new HashMap(); + + int code = read(); + for (; code > 0 && code != 'Z'; code = read()) { + _offset--; + + Object key = readObject(); + Object value = readObject(); + + if (key != null && value != null) + map.put(key, value); + } + + if (code != 'Z') + throw expect("fault", code); + + return map; + } + + /** + * Reads an object from the input stream with an expected type. + */ + public Object readObject(Class cl) + throws IOException + { + if (cl == null || cl == Object.class) + return readObject(); + + int tag = _offset < _length ? (_buffer[_offset++] & 0xff) : read(); + + switch (tag) { + case 'N': + return null; + + case 'H': + { + Deserializer reader = findSerializerFactory().getDeserializer(cl); + + return reader.readMap(this); + } + + case 'M': + { + String type = readType(); + + // hessian/3bb3 + if ("".equals(type)) { + Deserializer reader; + reader = findSerializerFactory().getDeserializer(cl); + + return reader.readMap(this); + } + else { + Deserializer reader; + reader = findSerializerFactory().getObjectDeserializer(type, cl); + + return reader.readMap(this); + } + } + + case 'C': + { + readObjectDefinition(cl); + + return readObject(cl); + } + + case 0x60: case 0x61: case 0x62: case 0x63: + case 0x64: case 0x65: case 0x66: case 0x67: + case 0x68: case 0x69: case 0x6a: case 0x6b: + case 0x6c: case 0x6d: case 0x6e: case 0x6f: + { + int ref = tag - 0x60; + int size = _classDefs.size(); + + if (ref < 0 || size <= ref) + throw new HessianProtocolException("'" + ref + "' is an unknown class definition"); + + ObjectDefinition def = (ObjectDefinition) _classDefs.get(ref); + + return readObjectInstance(cl, def); + } + + case 'O': + { + int ref = readInt(); + int size = _classDefs.size(); + + if (ref < 0 || size <= ref) + throw new HessianProtocolException("'" + ref + "' is an unknown class definition"); + + ObjectDefinition def = (ObjectDefinition) _classDefs.get(ref); + + return readObjectInstance(cl, def); + } + + case BC_LIST_VARIABLE: + { + String type = readType(); + + Deserializer reader; + reader = findSerializerFactory().getListDeserializer(type, cl); + + Object v = reader.readList(this, -1); + + return v; + } + + case BC_LIST_FIXED: + { + String type = readType(); + int length = readInt(); + + Deserializer reader; + reader = findSerializerFactory().getListDeserializer(type, cl); + + Object v = reader.readLengthList(this, length); + + return v; + } + + case 0x70: case 0x71: case 0x72: case 0x73: + case 0x74: case 0x75: case 0x76: case 0x77: + { + int length = tag - 0x70; + + String type = readType(); + + Deserializer reader; + reader = findSerializerFactory().getListDeserializer(null, cl); + + Object v = reader.readLengthList(this, length); + + return v; + } + + case BC_LIST_VARIABLE_UNTYPED: + { + Deserializer reader; + reader = findSerializerFactory().getListDeserializer(null, cl); + + Object v = reader.readList(this, -1); + + return v; + } + + case BC_LIST_FIXED_UNTYPED: + { + int length = readInt(); + + Deserializer reader; + reader = findSerializerFactory().getListDeserializer(null, cl); + + Object v = reader.readLengthList(this, length); + + return v; + } + + case 0x78: case 0x79: case 0x7a: case 0x7b: + case 0x7c: case 0x7d: case 0x7e: case 0x7f: + { + int length = tag - 0x78; + + Deserializer reader; + reader = findSerializerFactory().getListDeserializer(null, cl); + + Object v = reader.readLengthList(this, length); + + return v; + } + + case BC_REF: + { + int ref = readInt(); + + return _refs.get(ref); + } + } + + if (tag >= 0) + _offset--; + + // hessian/3b2i vs hessian/3406 + // return readObject(); + Object value = findSerializerFactory().getDeserializer(cl).readObject(this); + return value; + } + + /** + * Reads an arbitrary object from the input stream when the type + * is unknown. + */ + public Object readObject() + throws IOException + { + int tag = _offset < _length ? (_buffer[_offset++] & 0xff) : read(); + + switch (tag) { + case 'N': + return null; + + case 'T': + return Boolean.valueOf(true); + + case 'F': + return Boolean.valueOf(false); + + // direct integer + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8a: case 0x8b: + case 0x8c: case 0x8d: case 0x8e: case 0x8f: + + case 0x90: case 0x91: case 0x92: case 0x93: + case 0x94: case 0x95: case 0x96: case 0x97: + case 0x98: case 0x99: case 0x9a: case 0x9b: + case 0x9c: case 0x9d: case 0x9e: case 0x9f: + + case 0xa0: case 0xa1: case 0xa2: case 0xa3: + case 0xa4: case 0xa5: case 0xa6: case 0xa7: + case 0xa8: case 0xa9: case 0xaa: case 0xab: + case 0xac: case 0xad: case 0xae: case 0xaf: + + case 0xb0: case 0xb1: case 0xb2: case 0xb3: + case 0xb4: case 0xb5: case 0xb6: case 0xb7: + case 0xb8: case 0xb9: case 0xba: case 0xbb: + case 0xbc: case 0xbd: case 0xbe: case 0xbf: + return Integer.valueOf(tag - BC_INT_ZERO); + + /* byte int */ + case 0xc0: case 0xc1: case 0xc2: case 0xc3: + case 0xc4: case 0xc5: case 0xc6: case 0xc7: + case 0xc8: case 0xc9: case 0xca: case 0xcb: + case 0xcc: case 0xcd: case 0xce: case 0xcf: + return Integer.valueOf(((tag - BC_INT_BYTE_ZERO) << 8) + read()); + + /* short int */ + case 0xd0: case 0xd1: case 0xd2: case 0xd3: + case 0xd4: case 0xd5: case 0xd6: case 0xd7: + return Integer.valueOf(((tag - BC_INT_SHORT_ZERO) << 16) + + 256 * read() + read()); + + case 'I': + return Integer.valueOf(parseInt()); + + // direct long + case 0xd8: case 0xd9: case 0xda: case 0xdb: + case 0xdc: case 0xdd: case 0xde: case 0xdf: + + case 0xe0: case 0xe1: case 0xe2: case 0xe3: + case 0xe4: case 0xe5: case 0xe6: case 0xe7: + case 0xe8: case 0xe9: case 0xea: case 0xeb: + case 0xec: case 0xed: case 0xee: case 0xef: + return Long.valueOf(tag - BC_LONG_ZERO); + + /* byte long */ + case 0xf0: case 0xf1: case 0xf2: case 0xf3: + case 0xf4: case 0xf5: case 0xf6: case 0xf7: + case 0xf8: case 0xf9: case 0xfa: case 0xfb: + case 0xfc: case 0xfd: case 0xfe: case 0xff: + return Long.valueOf(((tag - BC_LONG_BYTE_ZERO) << 8) + read()); + + /* short long */ + case 0x38: case 0x39: case 0x3a: case 0x3b: + case 0x3c: case 0x3d: case 0x3e: case 0x3f: + return Long.valueOf(((tag - BC_LONG_SHORT_ZERO) << 16) + 256 * read() + read()); + + case BC_LONG_INT: + return Long.valueOf(parseInt()); + + case 'L': + return Long.valueOf(parseLong()); + + case BC_DOUBLE_ZERO: + return Double.valueOf(0); + + case BC_DOUBLE_ONE: + return Double.valueOf(1); + + case BC_DOUBLE_BYTE: + return Double.valueOf((byte) read()); + + case BC_DOUBLE_SHORT: + return Double.valueOf((short) (256 * read() + read())); + + case BC_DOUBLE_MILL: + { + int mills = parseInt(); + + return Double.valueOf(0.001 * mills); + } + + case 'D': + return Double.valueOf(parseDouble()); + + case BC_DATE: + return new Date(parseLong()); + + case BC_DATE_MINUTE: + return new Date(parseInt() * 60000L); + + case BC_STRING_CHUNK: + case 'S': + { + _isLastChunk = tag == 'S'; + _chunkLength = (read() << 8) + read(); + + int data; + _sbuf.setLength(0); + + while ((data = parseChar()) >= 0) + _sbuf.append((char) data); + + return _sbuf.toString(); + } + + case 0x00: case 0x01: case 0x02: case 0x03: + case 0x04: case 0x05: case 0x06: case 0x07: + case 0x08: case 0x09: case 0x0a: case 0x0b: + case 0x0c: case 0x0d: case 0x0e: case 0x0f: + + case 0x10: case 0x11: case 0x12: case 0x13: + case 0x14: case 0x15: case 0x16: case 0x17: + case 0x18: case 0x19: case 0x1a: case 0x1b: + case 0x1c: case 0x1d: case 0x1e: case 0x1f: + { + _isLastChunk = true; + _chunkLength = tag - 0x00; + + int data; + _sbuf.setLength(0); + + while ((data = parseChar()) >= 0) + _sbuf.append((char) data); + + return _sbuf.toString(); + } + + case 0x30: case 0x31: case 0x32: case 0x33: + { + _isLastChunk = true; + _chunkLength = (tag - 0x30) * 256 + read(); + + _sbuf.setLength(0); + + int ch; + while ((ch = parseChar()) >= 0) + _sbuf.append((char) ch); + + return _sbuf.toString(); + } + + case BC_BINARY_CHUNK: + case 'B': + { + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + + int data; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + while ((data = parseByte()) >= 0) + bos.write(data); + + return bos.toByteArray(); + } + + case 0x20: case 0x21: case 0x22: case 0x23: + case 0x24: case 0x25: case 0x26: case 0x27: + case 0x28: case 0x29: case 0x2a: case 0x2b: + case 0x2c: case 0x2d: case 0x2e: case 0x2f: + { + _isLastChunk = true; + int len = tag - 0x20; + _chunkLength = 0; + + byte []data = new byte[len]; + + for (int i = 0; i < len; i++) + data[i] = (byte) read(); + + return data; + } + + case 0x34: case 0x35: case 0x36: case 0x37: + { + _isLastChunk = true; + int len = (tag - 0x34) * 256 + read(); + _chunkLength = 0; + + byte []buffer = new byte[len]; + + for (int i = 0; i < len; i++) { + buffer[i] = (byte) read(); + } + + return buffer; + } + + case BC_LIST_VARIABLE: + { + // variable length list + String type = readType(); + + return findSerializerFactory().readList(this, -1, type); + } + + case BC_LIST_VARIABLE_UNTYPED: + { + return findSerializerFactory().readList(this, -1, null); + } + + case BC_LIST_FIXED: + { + // fixed length lists + String type = readType(); + int length = readInt(); + + Deserializer reader; + reader = findSerializerFactory().getListDeserializer(type, null); + + return reader.readLengthList(this, length); + } + + case BC_LIST_FIXED_UNTYPED: + { + // fixed length lists + int length = readInt(); + + Deserializer reader; + reader = findSerializerFactory().getListDeserializer(null, null); + + return reader.readLengthList(this, length); + } + + // compact fixed list + case 0x70: case 0x71: case 0x72: case 0x73: + case 0x74: case 0x75: case 0x76: case 0x77: + { + // fixed length lists + String type = readType(); + int length = tag - 0x70; + + Deserializer reader; + reader = findSerializerFactory().getListDeserializer(type, null); + + return reader.readLengthList(this, length); + } + + // compact fixed untyped list + case 0x78: case 0x79: case 0x7a: case 0x7b: + case 0x7c: case 0x7d: case 0x7e: case 0x7f: + { + // fixed length lists + int length = tag - 0x78; + + Deserializer reader; + reader = findSerializerFactory().getListDeserializer(null, null); + + return reader.readLengthList(this, length); + } + + case 'H': + { + return findSerializerFactory().readMap(this, null); + } + + case 'M': + { + String type = readType(); + + return findSerializerFactory().readMap(this, type); + } + + case 'C': + { + readObjectDefinition(null); + + return readObject(); + } + + case 0x60: case 0x61: case 0x62: case 0x63: + case 0x64: case 0x65: case 0x66: case 0x67: + case 0x68: case 0x69: case 0x6a: case 0x6b: + case 0x6c: case 0x6d: case 0x6e: case 0x6f: + { + int ref = tag - 0x60; + + if (_classDefs == null) + throw error("No classes defined at reference '{0}'" + tag); + + ObjectDefinition def = (ObjectDefinition) _classDefs.get(ref); + + return readObjectInstance(null, def); + } + + case 'O': + { + int ref = readInt(); + + ObjectDefinition def = (ObjectDefinition) _classDefs.get(ref); + + return readObjectInstance(null, def); + } + + case BC_REF: + { + int ref = readInt(); + + return _refs.get(ref); + } + + default: + if (tag < 0) + throw new EOFException("readObject: unexpected end of file"); + else + throw error("readObject: unknown code " + codeName(tag)); + } + } + + /** + * Reads an object definition: + * + *
+   * O string  (string)* *
+   * 
+ */ + private void readObjectDefinition(Class cl) + throws IOException + { + String type = readString(); + int len = readInt(); + + String []fieldNames = new String[len]; + for (int i = 0; i < len; i++) + fieldNames[i] = readString(); + + ObjectDefinition def = new ObjectDefinition(type, fieldNames); + + if (_classDefs == null) + _classDefs = new ArrayList(); + + _classDefs.add(def); + } + + private Object readObjectInstance(Class cl, ObjectDefinition def) + throws IOException + { + String type = def.getType(); + String []fieldNames = def.getFieldNames(); + + if (cl != null) { + Deserializer reader; + reader = findSerializerFactory().getObjectDeserializer(type, cl); + + return reader.readObject(this, fieldNames); + } + else { + return findSerializerFactory().readObject(this, type, fieldNames); + } + } + + private String readLenString() + throws IOException + { + int len = readInt(); + + _isLastChunk = true; + _chunkLength = len; + + _sbuf.setLength(0); + int ch; + while ((ch = parseChar()) >= 0) + _sbuf.append((char) ch); + + return _sbuf.toString(); + } + + private String readLenString(int len) + throws IOException + { + _isLastChunk = true; + _chunkLength = len; + + _sbuf.setLength(0); + int ch; + while ((ch = parseChar()) >= 0) + _sbuf.append((char) ch); + + return _sbuf.toString(); + } + + /** + * Reads a remote object. + */ + public Object readRemote() + throws IOException + { + String type = readType(); + String url = readString(); + + return resolveRemote(type, url); + } + + /** + * Reads a reference. + */ + public Object readRef() + throws IOException + { + return _refs.get(parseInt()); + } + + /** + * Reads the start of a list. + */ + public int readListStart() + throws IOException + { + return read(); + } + + /** + * Reads the start of a list. + */ + public int readMapStart() + throws IOException + { + return read(); + } + + /** + * Returns true if this is the end of a list or a map. + */ + public boolean isEnd() + throws IOException + { + int code; + + if (_offset < _length) + code = (_buffer[_offset] & 0xff); + else { + code = read(); + + if (code >= 0) + _offset--; + } + + return (code < 0 || code == 'Z'); + } + + /** + * Reads the end byte. + */ + public void readEnd() + throws IOException + { + int code = _offset < _length ? (_buffer[_offset++] & 0xff) : read(); + + if (code == 'Z') + return; + else if (code < 0) + throw error("unexpected end of file"); + else + throw error("unknown code:" + codeName(code)); + } + + /** + * Reads the end byte. + */ + public void readMapEnd() + throws IOException + { + int code = _offset < _length ? (_buffer[_offset++] & 0xff) : read(); + + if (code != 'Z') + throw error("expected end of map ('Z') at '" + codeName(code) + "'"); + } + + /** + * Reads the end byte. + */ + public void readListEnd() + throws IOException + { + int code = _offset < _length ? (_buffer[_offset++] & 0xff) : read(); + + if (code != 'Z') + throw error("expected end of list ('Z') at '" + codeName(code) + "'"); + } + + /** + * Adds a list/map reference. + */ + public int addRef(Object ref) + { + if (_refs == null) + _refs = new ArrayList(); + + _refs.add(ref); + + return _refs.size() - 1; + } + + /** + * Adds a list/map reference. + */ + public void setRef(int i, Object ref) + { + _refs.set(i, ref); + } + + /** + * Resets the references for streaming. + */ + public void resetReferences() + { + if (_refs != null) + _refs.clear(); + } + + public Object readStreamingObject() + throws IOException + { + if (_refs != null) + _refs.clear(); + + return readObject(); + } + + /** + * Resolves a remote object. + */ + public Object resolveRemote(String type, String url) + throws IOException + { + HessianRemoteResolver resolver = getRemoteResolver(); + + if (resolver != null) + return resolver.lookup(type, url); + else + return new HessianRemote(type, url); + } + + /** + * Parses a type from the stream. + * + *
+   * type ::= string
+   * type ::= int
+   * 
+ */ + public String readType() + throws IOException + { + int code = _offset < _length ? (_buffer[_offset++] & 0xff) : read(); + _offset--; + + switch (code) { + case 0x00: case 0x01: case 0x02: case 0x03: + case 0x04: case 0x05: case 0x06: case 0x07: + case 0x08: case 0x09: case 0x0a: case 0x0b: + case 0x0c: case 0x0d: case 0x0e: case 0x0f: + + case 0x10: case 0x11: case 0x12: case 0x13: + case 0x14: case 0x15: case 0x16: case 0x17: + case 0x18: case 0x19: case 0x1a: case 0x1b: + case 0x1c: case 0x1d: case 0x1e: case 0x1f: + + case 0x30: case 0x31: case 0x32: case 0x33: + case BC_STRING_CHUNK: case 'S': + { + String type = readString(); + + if (_types == null) + _types = new ArrayList(); + + _types.add(type); + + return type; + } + + default: + { + int ref = readInt(); + + if (_types.size() <= ref) + throw new IndexOutOfBoundsException("type ref #" + ref + " is greater than the number of valid types (" + _types.size() + ")"); + + return (String) _types.get(ref); + } + } + } + + /** + * Parses the length for an array + * + *
+   * l b32 b24 b16 b8
+   * 
+ */ + public int readLength() + throws IOException + { + throw new UnsupportedOperationException(); + } + + /** + * Parses a 32-bit integer value from the stream. + * + *
+   * b32 b24 b16 b8
+   * 
+ */ + private int parseInt() + throws IOException + { + int offset = _offset; + + if (offset + 3 < _length) { + byte []buffer = _buffer; + + int b32 = buffer[offset + 0] & 0xff; + int b24 = buffer[offset + 1] & 0xff; + int b16 = buffer[offset + 2] & 0xff; + int b8 = buffer[offset + 3] & 0xff; + + _offset = offset + 4; + + return (b32 << 24) + (b24 << 16) + (b16 << 8) + b8; + } + else { + int b32 = read(); + int b24 = read(); + int b16 = read(); + int b8 = read(); + + return (b32 << 24) + (b24 << 16) + (b16 << 8) + b8; + } + } + + /** + * Parses a 64-bit long value from the stream. + * + *
+   * b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + private long parseLong() + throws IOException + { + long b64 = read(); + long b56 = read(); + long b48 = read(); + long b40 = read(); + long b32 = read(); + long b24 = read(); + long b16 = read(); + long b8 = read(); + + return ((b64 << 56) + + (b56 << 48) + + (b48 << 40) + + (b40 << 32) + + (b32 << 24) + + (b24 << 16) + + (b16 << 8) + + b8); + } + + /** + * Parses a 64-bit double value from the stream. + * + *
+   * b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + private double parseDouble() + throws IOException + { + long bits = parseLong(); + + return Double.longBitsToDouble(bits); + } + + org.w3c.dom.Node parseXML() + throws IOException + { + throw new UnsupportedOperationException(); + } + + /** + * Reads a character from the underlying stream. + */ + private int parseChar() + throws IOException + { + while (_chunkLength <= 0) { + if (_isLastChunk) + return -1; + + int code = _offset < _length ? (_buffer[_offset++] & 0xff) : read(); + + switch (code) { + case BC_STRING_CHUNK: + _isLastChunk = false; + + _chunkLength = (read() << 8) + read(); + break; + + case 'S': + _isLastChunk = true; + + _chunkLength = (read() << 8) + read(); + break; + + case 0x00: case 0x01: case 0x02: case 0x03: + case 0x04: case 0x05: case 0x06: case 0x07: + case 0x08: case 0x09: case 0x0a: case 0x0b: + case 0x0c: case 0x0d: case 0x0e: case 0x0f: + + case 0x10: case 0x11: case 0x12: case 0x13: + case 0x14: case 0x15: case 0x16: case 0x17: + case 0x18: case 0x19: case 0x1a: case 0x1b: + case 0x1c: case 0x1d: case 0x1e: case 0x1f: + _isLastChunk = true; + _chunkLength = code - 0x00; + break; + + // qian.lei 2010-7-21 + case 0x30: case 0x31: case 0x32: case 0x33: + _isLastChunk = true; + _chunkLength = ((code - 0x30) << 8) + read(); + break; + + default: + throw expect("string", code); + } + + } + + _chunkLength--; + + return parseUTF8Char(); + } + + /** + * Parses a single UTF8 character. + */ + private int parseUTF8Char() + throws IOException + { + int ch = _offset < _length ? (_buffer[_offset++] & 0xff) : read(); + + if (ch < 0x80) + return ch; + else if ((ch & 0xe0) == 0xc0) { + int ch1 = read(); + int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); + + return v; + } + else if ((ch & 0xf0) == 0xe0) { + int ch1 = read(); + int ch2 = read(); + int v = ((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f); + + return v; + } + else + throw error("bad utf-8 encoding at " + codeName(ch)); + } + + /** + * Reads a byte from the underlying stream. + */ + private int parseByte() + throws IOException + { + while (_chunkLength <= 0) { + if (_isLastChunk) { + return -1; + } + + int code = read(); + + switch (code) { + case BC_BINARY_CHUNK: + _isLastChunk = false; + + _chunkLength = (read() << 8) + read(); + break; + + case 'B': + _isLastChunk = true; + + _chunkLength = (read() << 8) + read(); + break; + + case 0x20: case 0x21: case 0x22: case 0x23: + case 0x24: case 0x25: case 0x26: case 0x27: + case 0x28: case 0x29: case 0x2a: case 0x2b: + case 0x2c: case 0x2d: case 0x2e: case 0x2f: + _isLastChunk = true; + + _chunkLength = code - 0x20; + break; + + case 0x34: case 0x35: case 0x36: case 0x37: + _isLastChunk = true; + _chunkLength = (code - 0x34) * 256 + read(); + break; + + default: + throw expect("byte[]", code); + } + } + + _chunkLength--; + + return read(); + } + + /** + * Reads bytes based on an input stream. + */ + public InputStream readInputStream() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': + return null; + + case 'B': + case 'b': + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + break; + + case 0x20: case 0x21: case 0x22: case 0x23: + case 0x24: case 0x25: case 0x26: case 0x27: + case 0x28: case 0x29: case 0x2a: case 0x2b: + case 0x2c: case 0x2d: case 0x2e: case 0x2f: + _isLastChunk = true; + _chunkLength = tag - 0x20; + break; + + default: + throw expect("binary", tag); + } + + return new ReadInputStream(); + } + + /** + * Reads bytes from the underlying stream. + */ + int read(byte []buffer, int offset, int length) + throws IOException + { + int readLength = 0; + + while (length > 0) { + while (_chunkLength <= 0) { + if (_isLastChunk) + return readLength == 0 ? -1 : readLength; + + int code = read(); + + switch (code) { + case 'b': + _isLastChunk = false; + + _chunkLength = (read() << 8) + read(); + break; + + case 'B': + _isLastChunk = true; + + _chunkLength = (read() << 8) + read(); + break; + + case 0x20: case 0x21: case 0x22: case 0x23: + case 0x24: case 0x25: case 0x26: case 0x27: + case 0x28: case 0x29: case 0x2a: case 0x2b: + case 0x2c: case 0x2d: case 0x2e: case 0x2f: + _isLastChunk = true; + _chunkLength = code - 0x20; + break; + + default: + throw expect("byte[]", code); + } + } + + int sublen = _chunkLength; + if (length < sublen) + sublen = length; + + if (_length <= _offset && ! readBuffer()) + return -1; + + if (_length - _offset < sublen) + sublen = _length - _offset; + + System.arraycopy(_buffer, _offset, buffer, offset, sublen); + + _offset += sublen; + + offset += sublen; + readLength += sublen; + length -= sublen; + _chunkLength -= sublen; + } + + return readLength; + } + + /** + * Normally, shouldn't be called externally, but needed for QA, e.g. + * ejb/3b01. + */ + public final int read() + throws IOException + { + if (_length <= _offset && ! readBuffer()) + return -1; + + return _buffer[_offset++] & 0xff; + } + + private final boolean readBuffer() + throws IOException + { + byte []buffer = _buffer; + int offset = _offset; + int length = _length; + + if (offset < length) { + System.arraycopy(buffer, offset, buffer, 0, length - offset); + offset = length - offset; + } + else + offset = 0; + + int len = _is.read(buffer, offset, SIZE - offset); + + if (len <= 0) { + _length = offset; + _offset = 0; + + return offset > 0; + } + + _length = offset + len; + _offset = 0; + + return true; + } + + public Reader getReader() + { + return null; + } + + protected IOException expect(String expect, int ch) + throws IOException + { + if (ch < 0) + return error("expected " + expect + " at end of file"); + else { + _offset--; + + try { + Object obj = readObject(); + + if (obj != null) { + return error("expected " + expect + + " at 0x" + Integer.toHexString(ch & 0xff) + + " " + obj.getClass().getName() + " (" + obj + ")"); + } + else + return error("expected " + expect + + " at 0x" + Integer.toHexString(ch & 0xff) + " null"); + } catch (IOException e) { + log.log(Level.FINE, e.toString(), e); + + return error("expected " + expect + + " at 0x" + Integer.toHexString(ch & 0xff)); + } + } + } + + protected String codeName(int ch) + { + if (ch < 0) + return "end of file"; + else + return "0x" + Integer.toHexString(ch & 0xff) + " (" + (char) + ch + ")"; + } + + protected IOException error(String message) + { + if (_method != null) + return new HessianProtocolException(_method + ": " + message); + else + return new HessianProtocolException(message); + } + + public void close() + throws IOException + { + InputStream is = _is; + _is = null; + + if (_isCloseStreamOnClose && is != null) + is.close(); + } + + class ReadInputStream extends InputStream { + boolean _isClosed = false; + + public int read() + throws IOException + { + if (_isClosed) + return -1; + + int ch = parseByte(); + if (ch < 0) + _isClosed = true; + + return ch; + } + + public int read(byte []buffer, int offset, int length) + throws IOException + { + if (_isClosed) + return -1; + + int len = Hessian2Input.this.read(buffer, offset, length); + if (len < 0) + _isClosed = true; + + return len; + } + + public void close() + throws IOException + { + while (read() >= 0) { + } + } + }; + + final static class ObjectDefinition { + private final String _type; + private final String []_fields; + + ObjectDefinition(String type, String []fields) + { + _type = type; + _fields = fields; + } + + String getType() + { + return _type; + } + + String []getFieldNames() + { + return _fields; + } + } + + static { + try { + _detailMessageField = Throwable.class.getDeclaredField("detailMessage"); + _detailMessageField.setAccessible(true); + } catch (Throwable e) { + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Output.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Output.java new file mode 100644 index 000000000000..657d4d2edde8 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2Output.java @@ -0,0 +1,1605 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import com.alibaba.com.caucho.hessian.util.IdentityIntMap; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.HashMap; + +/** + * Output stream for Hessian 2 requests. + * + *

Since HessianOutput does not depend on any classes other than + * in the JDK, it can be extracted independently into a smaller package. + * + *

HessianOutput is unbuffered, so any client needs to provide + * its own buffering. + * + *

+ * OutputStream os = ...; // from http connection
+ * Hessian2Output out = new Hessian2Output(os);
+ * String value;
+ *
+ * out.startCall("hello", 1); // start hello call
+ * out.writeString("arg1");   // write a string argument
+ * out.completeCall();        // complete the call
+ * 
+ */ +public class Hessian2Output + extends AbstractHessianOutput + implements Hessian2Constants +{ + // the output stream/ + protected OutputStream _os; + + // map of references + private IdentityIntMap _refs = new IdentityIntMap(); + + private boolean _isCloseStreamOnClose; + + // map of classes + private HashMap _classRefs; + + // map of types + private HashMap _typeRefs; + + public final static int SIZE = 4096; + + private final byte []_buffer = new byte[SIZE]; + private int _offset; + + private boolean _isStreaming; + + /** + * Creates a new Hessian output stream, initialized with an + * underlying output stream. + * + * @param os the underlying output stream. + */ + public Hessian2Output(OutputStream os) + { + _os = os; + } + + public void setCloseStreamOnClose(boolean isClose) + { + _isCloseStreamOnClose = isClose; + } + + public boolean isCloseStreamOnClose() + { + return _isCloseStreamOnClose; + } + + + /** + * Writes a complete method call. + */ + @Override + public void call(String method, Object []args) + throws IOException + { + int length = args != null ? args.length : 0; + + startCall(method, length); + + for (int i = 0; i < args.length; i++) + writeObject(args[i]); + + completeCall(); + } + + /** + * Starts the method call. Clients would use startCall + * instead of call if they wanted finer control over + * writing the arguments, or needed to write headers. + * + *
+   * C
+   * string # method name
+   * int    # arg count
+   * 
+ * + * @param method the method name to call. + */ + public void startCall(String method, int length) + throws IOException + { + int offset = _offset; + + if (SIZE < offset + 32) { + flush(); + offset = _offset; + } + + byte []buffer = _buffer; + + buffer[_offset++] = (byte) 'C'; + + writeString(method); + writeInt(length); + } + + /** + * Writes the call tag. This would be followed by the + * method and the arguments + * + *
+   * C
+   * 
+ * + * @param method the method name to call. + */ + public void startCall() + throws IOException + { + flushIfFull(); + + _buffer[_offset++] = (byte) 'C'; + } + + /** + * Starts an envelope. + * + *
+   * E major minor
+   * m b16 b8 method-name
+   * 
+ * + * @param method the method name to call. + */ + public void startEnvelope(String method) + throws IOException + { + int offset = _offset; + + if (SIZE < offset + 32) { + flush(); + offset = _offset; + } + + _buffer[_offset++] = (byte) 'E'; + + writeString(method); + } + + /** + * Completes an envelope. + * + *

A successful completion will have a single value: + * + *

+   * Z
+   * 
+ */ + public void completeEnvelope() + throws IOException + { + flushIfFull(); + + _buffer[_offset++] = (byte) 'Z'; + } + + /** + * Writes the method tag. + * + *
+   * string
+   * 
+ * + * @param method the method name to call. + */ + public void writeMethod(String method) + throws IOException + { + writeString(method); + } + + /** + * Completes. + * + *
+   * z
+   * 
+ */ + public void completeCall() + throws IOException + { + /* + flushIfFull(); + + _buffer[_offset++] = (byte) 'Z'; + */ + } + + /** + * Starts the reply + * + *

A successful completion will have a single value: + * + *

+   * R
+   * 
+ */ + public void startReply() + throws IOException + { + writeVersion(); + + flushIfFull(); + + _buffer[_offset++] = (byte) 'R'; + } + + public void writeVersion() + throws IOException + { + flushIfFull(); + _buffer[_offset++] = (byte) 'H'; + _buffer[_offset++] = (byte) 2; + _buffer[_offset++] = (byte) 0; + } + + /** + * Completes reading the reply + * + *

A successful completion will have a single value: + * + *

+   * z
+   * 
+ */ + public void completeReply() + throws IOException + { + } + + /** + * Starts a packet + * + *

A message contains several objects encapsulated by a length

+ * + *
+   * p x02 x00
+   * 
+ */ + public void startMessage() + throws IOException + { + flushIfFull(); + + _buffer[_offset++] = (byte) 'p'; + _buffer[_offset++] = (byte) 2; + _buffer[_offset++] = (byte) 0; + } + + /** + * Completes reading the message + * + *

A successful completion will have a single value: + * + *

+   * z
+   * 
+ */ + public void completeMessage() + throws IOException + { + flushIfFull(); + + _buffer[_offset++] = (byte) 'z'; + } + + /** + * Writes a fault. The fault will be written + * as a descriptive string followed by an object: + * + *
+   * F map
+   * 
+ * + *
+   * F H
+   * \x04code
+   * \x10the fault code
+   *
+   * \x07message
+   * \x11the fault message
+   *
+   * \x06detail
+   * M\xnnjavax.ejb.FinderException
+   *     ...
+   * Z
+   * Z
+   * 
+ * + * @param code the fault code, a three digit + */ + public void writeFault(String code, String message, Object detail) + throws IOException + { + flushIfFull(); + + writeVersion(); + + _buffer[_offset++] = (byte) 'F'; + _buffer[_offset++] = (byte) 'H'; + + _refs.put(new HashMap(), _refs.size()); + + writeString("code"); + writeString(code); + + writeString("message"); + writeString(message); + + if (detail != null) { + writeString("detail"); + writeObject(detail); + } + + flushIfFull(); + _buffer[_offset++] = (byte) 'Z'; + } + + /** + * Writes any object to the output stream. + */ + public void writeObject(Object object) + throws IOException + { + if (object == null) { + writeNull(); + return; + } + + Serializer serializer; + + serializer = findSerializerFactory().getSerializer(object.getClass()); + + serializer.writeObject(object, this); + } + + /** + * Writes the list header to the stream. List writers will call + * writeListBegin followed by the list contents and then + * call writeListEnd. + * + *
+   * list ::= V type value* Z
+   *      ::= v type int value*
+   * 
+ * + * @return true for variable lists, false for fixed lists + */ + public boolean writeListBegin(int length, String type) + throws IOException + { + flushIfFull(); + + if (length < 0) { + if (type != null) { + _buffer[_offset++] = (byte) BC_LIST_VARIABLE; + writeType(type); + } + else + _buffer[_offset++] = (byte) BC_LIST_VARIABLE_UNTYPED; + + return true; + } + else if (length <= LIST_DIRECT_MAX) { + if (type != null) { + _buffer[_offset++] = (byte) (BC_LIST_DIRECT + length); + writeType(type); + } + else { + _buffer[_offset++] = (byte) (BC_LIST_DIRECT_UNTYPED + length); + } + + return false; + } + else { + if (type != null) { + _buffer[_offset++] = (byte) BC_LIST_FIXED; + writeType(type); + } + else { + _buffer[_offset++] = (byte) BC_LIST_FIXED_UNTYPED; + } + + writeInt(length); + + return false; + } + } + + /** + * Writes the tail of the list to the stream for a variable-length list. + */ + public void writeListEnd() + throws IOException + { + flushIfFull(); + + _buffer[_offset++] = (byte) BC_END; + } + + /** + * Writes the map header to the stream. Map writers will call + * writeMapBegin followed by the map contents and then + * call writeMapEnd. + * + *
+   * map ::= M type ( )* Z
+   *     ::= H ( )* Z
+   * 
+ */ + public void writeMapBegin(String type) + throws IOException + { + if (SIZE < _offset + 32) + flush(); + + if (type != null) { + _buffer[_offset++] = BC_MAP; + + writeType(type); + } + else + _buffer[_offset++] = BC_MAP_UNTYPED; + } + + /** + * Writes the tail of the map to the stream. + */ + public void writeMapEnd() + throws IOException + { + if (SIZE < _offset + 32) + flush(); + + _buffer[_offset++] = (byte) BC_END; + } + + /** + * Writes the object definition + * + *
+   * C <string> <int> <string>*
+   * 
+ */ + public int writeObjectBegin(String type) + throws IOException + { + if (_classRefs == null) + _classRefs = new HashMap(); + + Integer refV = (Integer) _classRefs.get(type); + + if (refV != null) { + int ref = refV.intValue(); + + if (SIZE < _offset + 32) + flush(); + + if (ref <= OBJECT_DIRECT_MAX) { + _buffer[_offset++] = (byte) (BC_OBJECT_DIRECT + ref); + } + else { + _buffer[_offset++] = (byte) 'O'; + writeInt(ref); + } + + return ref; + } + else { + int ref = _classRefs.size(); + + _classRefs.put(type, Integer.valueOf(ref)); + + if (SIZE < _offset + 32) + flush(); + + _buffer[_offset++] = (byte) 'C'; + + writeString(type); + + return -1; + } + } + + /** + * Writes the tail of the class definition to the stream. + */ + public void writeClassFieldLength(int len) + throws IOException + { + writeInt(len); + } + + /** + * Writes the tail of the object definition to the stream. + */ + public void writeObjectEnd() + throws IOException + { + } + + /** + *
+   * type ::= string
+   *      ::= int
+   * 
+ */ + private void writeType(String type) + throws IOException + { + flushIfFull(); + + int len = type.length(); + if (len == 0) { + throw new IllegalArgumentException("empty type is not allowed"); + } + + if (_typeRefs == null) + _typeRefs = new HashMap(); + + Integer typeRefV = (Integer) _typeRefs.get(type); + + if (typeRefV != null) { + int typeRef = typeRefV.intValue(); + + writeInt(typeRef); + } + else { + _typeRefs.put(type, Integer.valueOf(_typeRefs.size())); + + writeString(type); + } + } + + /** + * Writes a boolean value to the stream. The boolean will be written + * with the following syntax: + * + *
+   * T
+   * F
+   * 
+ * + * @param value the boolean value to write. + */ + public void writeBoolean(boolean value) + throws IOException + { + if (SIZE < _offset + 16) + flush(); + + if (value) + _buffer[_offset++] = (byte) 'T'; + else + _buffer[_offset++] = (byte) 'F'; + } + + /** + * Writes an integer value to the stream. The integer will be written + * with the following syntax: + * + *
+   * I b32 b24 b16 b8
+   * 
+ * + * @param value the integer value to write. + */ + public void writeInt(int value) + throws IOException + { + int offset = _offset; + byte []buffer = _buffer; + + if (SIZE <= offset + 16) { + flush(); + offset = _offset; + } + + if (INT_DIRECT_MIN <= value && value <= INT_DIRECT_MAX) + buffer[offset++] = (byte) (value + BC_INT_ZERO); + else if (INT_BYTE_MIN <= value && value <= INT_BYTE_MAX) { + buffer[offset++] = (byte) (BC_INT_BYTE_ZERO + (value >> 8)); + buffer[offset++] = (byte) (value); + } + else if (INT_SHORT_MIN <= value && value <= INT_SHORT_MAX) { + buffer[offset++] = (byte) (BC_INT_SHORT_ZERO + (value >> 16)); + buffer[offset++] = (byte) (value >> 8); + buffer[offset++] = (byte) (value); + } + else { + buffer[offset++] = (byte) ('I'); + buffer[offset++] = (byte) (value >> 24); + buffer[offset++] = (byte) (value >> 16); + buffer[offset++] = (byte) (value >> 8); + buffer[offset++] = (byte) (value); + } + + _offset = offset; + } + + /** + * Writes a long value to the stream. The long will be written + * with the following syntax: + * + *
+   * L b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ * + * @param value the long value to write. + */ + public void writeLong(long value) + throws IOException + { + int offset = _offset; + byte []buffer = _buffer; + + if (SIZE <= offset + 16) { + flush(); + offset = _offset; + } + + if (LONG_DIRECT_MIN <= value && value <= LONG_DIRECT_MAX) { + buffer[offset++] = (byte) (value + BC_LONG_ZERO); + } + else if (LONG_BYTE_MIN <= value && value <= LONG_BYTE_MAX) { + buffer[offset++] = (byte) (BC_LONG_BYTE_ZERO + (value >> 8)); + buffer[offset++] = (byte) (value); + } + else if (LONG_SHORT_MIN <= value && value <= LONG_SHORT_MAX) { + buffer[offset++] = (byte) (BC_LONG_SHORT_ZERO + (value >> 16)); + buffer[offset++] = (byte) (value >> 8); + buffer[offset++] = (byte) (value); + } + else if (-0x80000000L <= value && value <= 0x7fffffffL) { + buffer[offset + 0] = (byte) BC_LONG_INT; + buffer[offset + 1] = (byte) (value >> 24); + buffer[offset + 2] = (byte) (value >> 16); + buffer[offset + 3] = (byte) (value >> 8); + buffer[offset + 4] = (byte) (value); + + offset += 5; + } + else { + buffer[offset + 0] = (byte) 'L'; + buffer[offset + 1] = (byte) (value >> 56); + buffer[offset + 2] = (byte) (value >> 48); + buffer[offset + 3] = (byte) (value >> 40); + buffer[offset + 4] = (byte) (value >> 32); + buffer[offset + 5] = (byte) (value >> 24); + buffer[offset + 6] = (byte) (value >> 16); + buffer[offset + 7] = (byte) (value >> 8); + buffer[offset + 8] = (byte) (value); + + offset += 9; + } + + _offset = offset; + } + + /** + * Writes a double value to the stream. The double will be written + * with the following syntax: + * + *
+   * D b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ * + * @param value the double value to write. + */ + public void writeDouble(double value) + throws IOException + { + int offset = _offset; + byte []buffer = _buffer; + + if (SIZE <= offset + 16) { + flush(); + offset = _offset; + } + + int intValue = (int) value; + + if (intValue == value) { + if (intValue == 0) { + buffer[offset++] = (byte) BC_DOUBLE_ZERO; + + _offset = offset; + + return; + } + else if (intValue == 1) { + buffer[offset++] = (byte) BC_DOUBLE_ONE; + + _offset = offset; + + return; + } + else if (-0x80 <= intValue && intValue < 0x80) { + buffer[offset++] = (byte) BC_DOUBLE_BYTE; + buffer[offset++] = (byte) intValue; + + _offset = offset; + + return; + } + else if (-0x8000 <= intValue && intValue < 0x8000) { + buffer[offset + 0] = (byte) BC_DOUBLE_SHORT; + buffer[offset + 1] = (byte) (intValue >> 8); + buffer[offset + 2] = (byte) intValue; + + _offset = offset + 3; + + return; + } + } + + int mills = (int) (value * 1000); + + if (0.001 * mills == value) { + buffer[offset + 0] = (byte) (BC_DOUBLE_MILL); + buffer[offset + 1] = (byte) (mills >> 24); + buffer[offset + 2] = (byte) (mills >> 16); + buffer[offset + 3] = (byte) (mills >> 8); + buffer[offset + 4] = (byte) (mills); + + _offset = offset + 5; + + return; + } + + long bits = Double.doubleToLongBits(value); + + buffer[offset + 0] = (byte) 'D'; + buffer[offset + 1] = (byte) (bits >> 56); + buffer[offset + 2] = (byte) (bits >> 48); + buffer[offset + 3] = (byte) (bits >> 40); + buffer[offset + 4] = (byte) (bits >> 32); + buffer[offset + 5] = (byte) (bits >> 24); + buffer[offset + 6] = (byte) (bits >> 16); + buffer[offset + 7] = (byte) (bits >> 8); + buffer[offset + 8] = (byte) (bits); + + _offset = offset + 9; + } + + /** + * Writes a date to the stream. + * + *
+   * date ::= d   b7 b6 b5 b4 b3 b2 b1 b0
+   *      ::= x65 b3 b2 b1 b0
+   * 
+ * + * @param time the date in milliseconds from the epoch in UTC + */ + public void writeUTCDate(long time) + throws IOException + { + if (SIZE < _offset + 32) + flush(); + + int offset = _offset; + byte []buffer = _buffer; + + if (time % 60000L == 0) { + // compact date ::= x65 b3 b2 b1 b0 + + long minutes = time / 60000L; + + if ((minutes >> 31) == 0 || (minutes >> 31) == -1) { + buffer[offset++] = (byte) BC_DATE_MINUTE; + buffer[offset++] = ((byte) (minutes >> 24)); + buffer[offset++] = ((byte) (minutes >> 16)); + buffer[offset++] = ((byte) (minutes >> 8)); + buffer[offset++] = ((byte) (minutes >> 0)); + + _offset = offset; + return; + } + } + + buffer[offset++] = (byte) BC_DATE; + buffer[offset++] = ((byte) (time >> 56)); + buffer[offset++] = ((byte) (time >> 48)); + buffer[offset++] = ((byte) (time >> 40)); + buffer[offset++] = ((byte) (time >> 32)); + buffer[offset++] = ((byte) (time >> 24)); + buffer[offset++] = ((byte) (time >> 16)); + buffer[offset++] = ((byte) (time >> 8)); + buffer[offset++] = ((byte) (time)); + + _offset = offset; + } + + /** + * Writes a null value to the stream. + * The null will be written with the following syntax + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + public void writeNull() + throws IOException + { + int offset = _offset; + byte []buffer = _buffer; + + if (SIZE <= offset + 16) { + flush(); + offset = _offset; + } + + buffer[offset++] = 'N'; + + _offset = offset; + } + + /** + * Writes a string value to the stream using UTF-8 encoding. + * The string will be written with the following syntax: + * + *
+   * S b16 b8 string-value
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + public void writeString(String value) + throws IOException + { + int offset = _offset; + byte []buffer = _buffer; + + if (SIZE <= offset + 16) { + flush(); + offset = _offset; + } + + if (value == null) { + buffer[offset++] = (byte) 'N'; + + _offset = offset; + } + else { + int length = value.length(); + int strOffset = 0; + + while (length > 0x8000) { + int sublen = 0x8000; + + offset = _offset; + + if (SIZE <= offset + 16) { + flush(); + offset = _offset; + } + + // chunk can't end in high surrogate + char tail = value.charAt(strOffset + sublen - 1); + + if (0xd800 <= tail && tail <= 0xdbff) + sublen--; + + buffer[offset + 0] = (byte) BC_STRING_CHUNK; + buffer[offset + 1] = (byte) (sublen >> 8); + buffer[offset + 2] = (byte) (sublen); + + _offset = offset + 3; + + printString(value, strOffset, sublen); + + length -= sublen; + strOffset += sublen; + } + + offset = _offset; + + if (SIZE <= offset + 16) { + flush(); + offset = _offset; + } + + if (length <= STRING_DIRECT_MAX) { + buffer[offset++] = (byte) (BC_STRING_DIRECT + length); + } + else if (length <= STRING_SHORT_MAX) { + buffer[offset++] = (byte) (BC_STRING_SHORT + (length >> 8)); + buffer[offset++] = (byte) (length); + } + else { + buffer[offset++] = (byte) ('S'); + buffer[offset++] = (byte) (length >> 8); + buffer[offset++] = (byte) (length); + } + + _offset = offset; + + printString(value, strOffset, length); + } + } + + /** + * Writes a string value to the stream using UTF-8 encoding. + * The string will be written with the following syntax: + * + *
+   * S b16 b8 string-value
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + public void writeString(char []buffer, int offset, int length) + throws IOException + { + if (buffer == null) { + if (SIZE < _offset + 16) + flush(); + + _buffer[_offset++] = (byte) ('N'); + } + else { + while (length > 0x8000) { + int sublen = 0x8000; + + if (SIZE < _offset + 16) + flush(); + + // chunk can't end in high surrogate + char tail = buffer[offset + sublen - 1]; + + if (0xd800 <= tail && tail <= 0xdbff) + sublen--; + + _buffer[_offset++] = (byte) BC_STRING_CHUNK; + _buffer[_offset++] = (byte) (sublen >> 8); + _buffer[_offset++] = (byte) (sublen); + + printString(buffer, offset, sublen); + + length -= sublen; + offset += sublen; + } + + if (SIZE < _offset + 16) + flush(); + + if (length <= STRING_DIRECT_MAX) { + _buffer[_offset++] = (byte) (BC_STRING_DIRECT + length); + } + else if (length <= STRING_SHORT_MAX) { + _buffer[_offset++] = (byte) (BC_STRING_SHORT + (length >> 8)); + _buffer[_offset++] = (byte) length; + } + else { + _buffer[_offset++] = (byte) ('S'); + _buffer[_offset++] = (byte) (length >> 8); + _buffer[_offset++] = (byte) (length); + } + + printString(buffer, offset, length); + } + } + + /** + * Writes a byte array to the stream. + * The array will be written with the following syntax: + * + *
+   * B b16 b18 bytes
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + public void writeBytes(byte []buffer) + throws IOException + { + if (buffer == null) { + if (SIZE < _offset + 16) + flush(); + + _buffer[_offset++] = 'N'; + } + else + writeBytes(buffer, 0, buffer.length); + } + + /** + * Writes a byte array to the stream. + * The array will be written with the following syntax: + * + *
+   * B b16 b18 bytes
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + public void writeBytes(byte []buffer, int offset, int length) + throws IOException + { + if (buffer == null) { + if (SIZE < _offset + 16) + flushBuffer(); + + _buffer[_offset++] = (byte) 'N'; + } + else { + flush(); + + while (SIZE - _offset - 3 < length) { + int sublen = SIZE - _offset - 3; + + if (sublen < 16) { + flushBuffer(); + + sublen = SIZE - _offset - 3; + + if (length < sublen) + sublen = length; + } + + _buffer[_offset++] = (byte) BC_BINARY_CHUNK; + _buffer[_offset++] = (byte) (sublen >> 8); + _buffer[_offset++] = (byte) sublen; + + System.arraycopy(buffer, offset, _buffer, _offset, sublen); + _offset += sublen; + + length -= sublen; + offset += sublen; + + flushBuffer(); + } + + if (SIZE < _offset + 16) + flushBuffer(); + + if (length <= BINARY_DIRECT_MAX) { + _buffer[_offset++] = (byte) (BC_BINARY_DIRECT + length); + } + else if (length <= BINARY_SHORT_MAX) { + _buffer[_offset++] = (byte) (BC_BINARY_SHORT + (length >> 8)); + _buffer[_offset++] = (byte) (length); + } + else { + _buffer[_offset++] = (byte) 'B'; + _buffer[_offset++] = (byte) (length >> 8); + _buffer[_offset++] = (byte) (length); + } + + System.arraycopy(buffer, offset, _buffer, _offset, length); + + _offset += length; + } + } + + /** + * Writes a byte buffer to the stream. + * + *
+   * 
+ */ + public void writeByteBufferStart() + throws IOException + { + } + + /** + * Writes a byte buffer to the stream. + * + *
+   * b b16 b18 bytes
+   * 
+ */ + public void writeByteBufferPart(byte []buffer, int offset, int length) + throws IOException + { + while (length > 0) { + int sublen = length; + + if (0x8000 < sublen) + sublen = 0x8000; + + flush(); // bypass buffer + + _os.write(BC_BINARY_CHUNK); + _os.write(sublen >> 8); + _os.write(sublen); + + _os.write(buffer, offset, sublen); + + length -= sublen; + offset += sublen; + } + } + + /** + * Writes a byte buffer to the stream. + * + *
+   * b b16 b18 bytes
+   * 
+ */ + public void writeByteBufferEnd(byte []buffer, int offset, int length) + throws IOException + { + writeBytes(buffer, offset, length); + } + + /** + * Returns an output stream to write binary data. + */ + public OutputStream getBytesOutputStream() + throws IOException + { + return new BytesOutputStream(); + } + + /** + * Writes a reference. + * + *
+   * x51 <int>
+   * 
+ * + * @param value the integer value to write. + */ + @Override + protected void writeRef(int value) + throws IOException + { + if (SIZE < _offset + 16) + flush(); + + _buffer[_offset++] = (byte) BC_REF; + + writeInt(value); + } + + /** + * If the object has already been written, just write its ref. + * + * @return true if we're writing a ref. + */ + public boolean addRef(Object object) + throws IOException + { + int ref = _refs.get(object); + + if (ref >= 0) { + writeRef(ref); + + return true; + } + else { + _refs.put(object, _refs.size()); + + return false; + } + } + + /** + * Removes a reference. + */ + public boolean removeRef(Object obj) + throws IOException + { + if (_refs != null) { + _refs.remove(obj); + + return true; + } + else + return false; + } + + /** + * Replaces a reference from one object to another. + */ + public boolean replaceRef(Object oldRef, Object newRef) + throws IOException + { + Integer value = (Integer) _refs.remove(oldRef); + + if (value != null) { + _refs.put(newRef, value); + return true; + } + else + return false; + } + + /** + * Resets the references for streaming. + */ + public void resetReferences() + { + if (_refs != null) + _refs.clear(); + } + + /** + * Starts the streaming message + * + *

A streaming message starts with 'P'

+ * + *
+   * P x02 x00
+   * 
+ */ + public void writeStreamingObject(Object obj) + throws IOException + { + startStreamingPacket(); + + writeObject(obj); + + endStreamingPacket(); + } + + /** + * Starts a streaming packet + * + *

A streaming message starts with 'P'

+ * + *
+   * P x02 x00
+   * 
+ */ + public void startStreamingPacket() + throws IOException + { + if (_refs != null) + _refs.clear(); + + flush(); + + _isStreaming = true; + _offset = 3; + } + + public void endStreamingPacket() + throws IOException + { + int len = _offset - 3; + + _buffer[0] = (byte) 'P'; + _buffer[1] = (byte) (len >> 8); + _buffer[2] = (byte) len; + + _isStreaming = false; + + flush(); + } + + /** + * Prints a string to the stream, encoded as UTF-8 with preceeding length + * + * @param v the string to print. + */ + public void printLenString(String v) + throws IOException + { + if (SIZE < _offset + 16) + flush(); + + if (v == null) { + _buffer[_offset++] = (byte) (0); + _buffer[_offset++] = (byte) (0); + } + else { + int len = v.length(); + _buffer[_offset++] = (byte) (len >> 8); + _buffer[_offset++] = (byte) (len); + + printString(v, 0, len); + } + } + + /** + * Prints a string to the stream, encoded as UTF-8 + * + * @param v the string to print. + */ + public void printString(String v) + throws IOException + { + printString(v, 0, v.length()); + } + + /** + * Prints a string to the stream, encoded as UTF-8 + * + * @param v the string to print. + */ + public void printString(String v, int strOffset, int length) + throws IOException + { + int offset = _offset; + byte []buffer = _buffer; + + for (int i = 0; i < length; i++) { + if (SIZE <= offset + 16) { + _offset = offset; + flush(); + offset = _offset; + } + + char ch = v.charAt(i + strOffset); + + if (ch < 0x80) + buffer[offset++] = (byte) (ch); + else if (ch < 0x800) { + buffer[offset++] = (byte) (0xc0 + ((ch >> 6) & 0x1f)); + buffer[offset++] = (byte) (0x80 + (ch & 0x3f)); + } + else { + buffer[offset++] = (byte) (0xe0 + ((ch >> 12) & 0xf)); + buffer[offset++] = (byte) (0x80 + ((ch >> 6) & 0x3f)); + buffer[offset++] = (byte) (0x80 + (ch & 0x3f)); + } + } + + _offset = offset; + } + + /** + * Prints a string to the stream, encoded as UTF-8 + * + * @param v the string to print. + */ + public void printString(char []v, int strOffset, int length) + throws IOException + { + int offset = _offset; + byte []buffer = _buffer; + + for (int i = 0; i < length; i++) { + if (SIZE <= offset + 16) { + _offset = offset; + flush(); + offset = _offset; + } + + char ch = v[i + strOffset]; + + if (ch < 0x80) + buffer[offset++] = (byte) (ch); + else if (ch < 0x800) { + buffer[offset++] = (byte) (0xc0 + ((ch >> 6) & 0x1f)); + buffer[offset++] = (byte) (0x80 + (ch & 0x3f)); + } + else { + buffer[offset++] = (byte) (0xe0 + ((ch >> 12) & 0xf)); + buffer[offset++] = (byte) (0x80 + ((ch >> 6) & 0x3f)); + buffer[offset++] = (byte) (0x80 + (ch & 0x3f)); + } + } + + _offset = offset; + } + + private final void flushIfFull() + throws IOException + { + int offset = _offset; + + if (SIZE < offset + 32) { + _offset = 0; + _os.write(_buffer, 0, offset); + } + } + + public final void flush() + throws IOException + { + flushBuffer(); + + if (_os != null) + _os.flush(); + } + + public final void flushBuffer() + throws IOException + { + int offset = _offset; + + if (! _isStreaming && offset > 0) { + _offset = 0; + + _os.write(_buffer, 0, offset); + } + else if (_isStreaming && offset > 3) { + int len = offset - 3; + _buffer[0] = 'p'; + _buffer[1] = (byte) (len >> 8); + _buffer[2] = (byte) len; + _offset = 3; + + _os.write(_buffer, 0, offset); + } + } + + public final void close() + throws IOException + { + // hessian/3a8c + flush(); + + OutputStream os = _os; + _os = null; + + if (os != null) { + if (_isCloseStreamOnClose) + os.close(); + } + } + + class BytesOutputStream extends OutputStream { + private int _startOffset; + + BytesOutputStream() + throws IOException + { + if (SIZE < _offset + 16) { + Hessian2Output.this.flush(); + } + + _startOffset = _offset; + _offset += 3; // skip 'b' xNN xNN + } + + @Override + public void write(int ch) + throws IOException + { + if (SIZE <= _offset) { + int length = (_offset - _startOffset) - 3; + + _buffer[_startOffset] = (byte) BC_BINARY_CHUNK; + _buffer[_startOffset + 1] = (byte) (length >> 8); + _buffer[_startOffset + 2] = (byte) (length); + + Hessian2Output.this.flush(); + + _startOffset = _offset; + _offset += 3; + } + + _buffer[_offset++] = (byte) ch; + } + + @Override + public void write(byte []buffer, int offset, int length) + throws IOException + { + while (length > 0) { + int sublen = SIZE - _offset; + + if (length < sublen) + sublen = length; + + if (sublen > 0) { + System.arraycopy(buffer, offset, _buffer, _offset, sublen); + _offset += sublen; + } + + length -= sublen; + offset += sublen; + + if (SIZE <= _offset) { + int chunkLength = (_offset - _startOffset) - 3; + + _buffer[_startOffset] = (byte) BC_BINARY_CHUNK; + _buffer[_startOffset + 1] = (byte) (chunkLength >> 8); + _buffer[_startOffset + 2] = (byte) (chunkLength); + + Hessian2Output.this.flush(); + + _startOffset = _offset; + _offset += 3; + } + } + } + + @Override + public void close() + throws IOException + { + int startOffset = _startOffset; + _startOffset = -1; + + if (startOffset < 0) + return; + + int length = (_offset - startOffset) - 3; + + _buffer[startOffset] = (byte) 'B'; + _buffer[startOffset + 1] = (byte) (length >> 8); + _buffer[startOffset + 2] = (byte) (length); + + Hessian2Output.this.flush(); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2StreamingInput.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2StreamingInput.java new file mode 100644 index 000000000000..ac8e8e9d9fdf --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2StreamingInput.java @@ -0,0 +1,165 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Output stream for Hessian 2 streaming requests. + */ +public class Hessian2StreamingInput +{ + private Hessian2Input _in; + + /** + * Creates a new Hessian input stream, initialized with an + * underlying input stream. + * + * @param is the underlying output stream. + */ + public Hessian2StreamingInput(InputStream is) + { + _in = new Hessian2Input(new StreamingInputStream(is)); + } + + /** + * Read the next object + */ + public Object readObject() + throws IOException + { + return _in.readStreamingObject(); + } + + /** + * Close the output. + */ + public void close() + throws IOException + { + _in.close(); + } + + static class StreamingInputStream extends InputStream { + private InputStream _is; + private int _length; + + StreamingInputStream(InputStream is) + { + _is = is; + } + + public int read() + throws IOException + { + InputStream is = _is; + + while (_length == 0) { + int code = is.read(); + + if (code < 0) + return -1; + else if (code != 'p' && code != 'P') + throw new HessianProtocolException("expected streaming packet at 0x" + + Integer.toHexString(code & 0xff)); + + int d1 = is.read(); + int d2 = is.read(); + + if (d2 < 0) + return -1; + + _length = (d1 << 8) + d2; + } + + _length--; + return is.read(); + } + + public int read(byte []buffer, int offset, int length) + throws IOException + { + InputStream is = _is; + + while (_length == 0) { + int code = is.read(); + + if (code < 0) + return -1; + else if (code != 'p' && code != 'P') { + throw new HessianProtocolException("expected streaming packet at 0x" + + Integer.toHexString(code & 0xff) + + " (" + (char) code + ")"); + } + + int d1 = is.read(); + int d2 = is.read(); + + if (d2 < 0) + return -1; + + _length = (d1 << 8) + d2; + } + + int sublen = _length; + if (length < sublen) + sublen = length; + + sublen = is.read(buffer, offset, sublen); + + if (sublen < 0) + return -1; + + _length -= sublen; + + return sublen; + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2StreamingOutput.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2StreamingOutput.java new file mode 100644 index 000000000000..28c44cdf5805 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Hessian2StreamingOutput.java @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.HashMap; + +/** + * Output stream for Hessian 2 streaming requests. + */ +public class Hessian2StreamingOutput +{ + private Hessian2Output _out; + + /** + * Creates a new Hessian output stream, initialized with an + * underlying output stream. + * + * @param os the underlying output stream. + */ + public Hessian2StreamingOutput(OutputStream os) + { + _out = new Hessian2Output(os); + } + + public void setCloseStreamOnClose(boolean isClose) + { + _out.setCloseStreamOnClose(isClose); + } + + public boolean isCloseStreamOnClose() + { + return _out.isCloseStreamOnClose(); + } + + /** + * Writes any object to the output stream. + */ + public void writeObject(Object object) + throws IOException + { + _out.writeStreamingObject(object); + } + + /** + * Flushes the output. + */ + public void flush() + throws IOException + { + _out.flush(); + } + + /** + * Close the output. + */ + public void close() + throws IOException + { + _out.close(); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugInputStream.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugInputStream.java new file mode 100644 index 000000000000..31e1f2881a14 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugInputStream.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Writer; +import java.io.PrintWriter; +import java.util.ArrayList; + +import java.util.logging.Logger; +import java.util.logging.Level; + +/** + * Debugging input stream for Hessian requests. + */ +public class HessianDebugInputStream extends InputStream +{ + private InputStream _is; + + private HessianDebugState _state; + + /** + * Creates an uninitialized Hessian input stream. + */ + public HessianDebugInputStream(InputStream is, PrintWriter dbg) + { + _is = is; + + if (dbg == null) + dbg = new PrintWriter(System.out); + + _state = new HessianDebugState(dbg); + } + + /** + * Creates an uninitialized Hessian input stream. + */ + public HessianDebugInputStream(InputStream is, Logger log, Level level) + { + this(is, new PrintWriter(new LogWriter(log, level))); + } + + public void startTop2() + { + _state.startTop2(); + } + + /** + * Reads a character. + */ + public int read() + throws IOException + { + int ch; + + InputStream is = _is; + + if (is == null) + return -1; + else { + ch = is.read(); + } + + _state.next(ch); + + return ch; + } + + /** + * closes the stream. + */ + public void close() + throws IOException + { + InputStream is = _is; + _is = null; + + if (is != null) + is.close(); + + _state.println(); + } + + static class LogWriter extends Writer { + private Logger _log; + private Level _level; + private StringBuilder _sb = new StringBuilder(); + + LogWriter(Logger log, Level level) + { + _log = log; + _level = level; + } + + public void write(char ch) + { + if (ch == '\n' && _sb.length() > 0) { + _log.log(_level, _sb.toString()); + _sb.setLength(0); + } + else + _sb.append((char) ch); + } + + public void write(char []buffer, int offset, int length) + { + for (int i = 0; i < length; i++) { + char ch = buffer[offset + i]; + + if (ch == '\n' && _sb.length() > 0) { + _log.log(_level, _sb.toString()); + _sb.setLength(0); + } + else + _sb.append((char) ch); + } + } + + public void flush() + { + } + + public void close() + { + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugOutputStream.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugOutputStream.java new file mode 100644 index 000000000000..0511e664f2cc --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugOutputStream.java @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.io.PrintWriter; + +import java.util.logging.Logger; +import java.util.logging.Level; + +/** + * Debugging output stream for Hessian requests. + */ +public class HessianDebugOutputStream extends OutputStream +{ + private OutputStream _os; + + private HessianDebugState _state; + + /** + * Creates an uninitialized Hessian input stream. + */ + public HessianDebugOutputStream(OutputStream os, PrintWriter dbg) + { + _os = os; + + _state = new HessianDebugState(dbg); + } + + /** + * Creates an uninitialized Hessian input stream. + */ + public HessianDebugOutputStream(OutputStream os, Logger log, Level level) + { + this(os, new PrintWriter(new LogWriter(log, level))); + } + + public void startTop2() + { + _state.startTop2(); + } + + /** + * Writes a character. + */ + public void write(int ch) + throws IOException + { + ch = ch & 0xff; + + _os.write(ch); + + _state.next(ch); + } + + public void flush() + throws IOException + { + _os.flush(); + } + + /** + * closes the stream. + */ + public void close() + throws IOException + { + OutputStream os = _os; + _os = null; + + if (os != null) + os.close(); + + _state.println(); + } + + static class LogWriter extends Writer { + private Logger _log; + private Level _level; + private StringBuilder _sb = new StringBuilder(); + + LogWriter(Logger log, Level level) + { + _log = log; + _level = level; + } + + public void write(char ch) + { + if (ch == '\n' && _sb.length() > 0) { + _log.log(_level, _sb.toString()); + _sb.setLength(0); + } + else + _sb.append((char) ch); + } + + public void write(char []buffer, int offset, int length) + { + for (int i = 0; i < length; i++) { + char ch = buffer[offset + i]; + + if (ch == '\n' && _sb.length() > 0) { + _log.log(_level, _sb.toString()); + _sb.setLength(0); + } + else + _sb.append((char) ch); + } + } + + public void flush() + { + } + + public void close() + { + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugState.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugState.java new file mode 100644 index 000000000000..89239e842f9d --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianDebugState.java @@ -0,0 +1,2090 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.util.ArrayList; + +/** + * Debugging input stream for Hessian requests. + */ +public class HessianDebugState implements Hessian2Constants +{ + private PrintWriter _dbg; + + private State _state; + private ArrayList _stateStack = new ArrayList(); + + private ArrayList _objectDefList + = new ArrayList(); + + private ArrayList _typeDefList + = new ArrayList(); + + private int _refId; + private boolean _isNewline = true; + private boolean _isObject = false; + private int _column; + + /** + * Creates an uninitialized Hessian input stream. + */ + public HessianDebugState(PrintWriter dbg) + { + _dbg = dbg; + + _state = new InitialState(); + } + + public void startTop2() + { + _state = new Top2State(); + } + + /** + * Reads a character. + */ + public void next(int ch) + throws IOException + { + _state = _state.next(ch); + } + + void pushStack(State state) + { + _stateStack.add(state); + } + + State popStack() + { + return _stateStack.remove(_stateStack.size() - 1); + } + + void println() + { + if (! _isNewline) { + _dbg.println(); + _dbg.flush(); + } + + _isNewline = true; + _column = 0; + } + + static boolean isString(int ch) + { + switch (ch) { + case 0x00: case 0x01: case 0x02: case 0x03: + case 0x04: case 0x05: case 0x06: case 0x07: + case 0x08: case 0x09: case 0x0a: case 0x0b: + case 0x0c: case 0x0d: case 0x0e: case 0x0f: + + case 0x10: case 0x11: case 0x12: case 0x13: + case 0x14: case 0x15: case 0x16: case 0x17: + case 0x18: case 0x19: case 0x1a: case 0x1b: + case 0x1c: case 0x1d: case 0x1e: case 0x1f: + + case 0x30: case 0x31: case 0x32: case 0x33: + + case 'R': + case 'S': + return true; + + default: + return false; + } + } + + static boolean isInteger(int ch) + { + switch (ch) { + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8a: case 0x8b: + case 0x8c: case 0x8d: case 0x8e: case 0x8f: + + case 0x90: case 0x91: case 0x92: case 0x93: + case 0x94: case 0x95: case 0x96: case 0x97: + case 0x98: case 0x99: case 0x9a: case 0x9b: + case 0x9c: case 0x9d: case 0x9e: case 0x9f: + + case 0xa0: case 0xa1: case 0xa2: case 0xa3: + case 0xa4: case 0xa5: case 0xa6: case 0xa7: + case 0xa8: case 0xa9: case 0xaa: case 0xab: + case 0xac: case 0xad: case 0xae: case 0xaf: + + case 0xb0: case 0xb1: case 0xb2: case 0xb3: + case 0xb4: case 0xb5: case 0xb6: case 0xb7: + case 0xb8: case 0xb9: case 0xba: case 0xbb: + case 0xbc: case 0xbd: case 0xbe: case 0xbf: + + case 0xc0: case 0xc1: case 0xc2: case 0xc3: + case 0xc4: case 0xc5: case 0xc6: case 0xc7: + case 0xc8: case 0xc9: case 0xca: case 0xcb: + case 0xcc: case 0xcd: case 0xce: case 0xcf: + + case 0xd0: case 0xd1: case 0xd2: case 0xd3: + case 0xd4: case 0xd5: case 0xd6: case 0xd7: + + case 'I': + return true; + + default: + return false; + } + } + + abstract class State { + State _next; + + State() + { + } + + State(State next) + { + _next = next; + } + + abstract State next(int ch); + + boolean isShift(Object value) + { + return false; + } + + State shift(Object value) + { + return this; + } + + int depth() + { + if (_next != null) + return _next.depth(); + else + return 0; + } + + void printIndent(int depth) + { + if (_isNewline) { + for (int i = _column; i < depth() + depth; i++) { + _dbg.print(" "); + _column++; + } + } + } + + void print(String string) + { + print(0, string); + } + + void print(int depth, String string) + { + printIndent(depth); + + _dbg.print(string); + _isNewline = false; + _isObject = false; + + int p = string.lastIndexOf('\n'); + if (p > 0) + _column = string.length() - p - 1; + else + _column += string.length(); + } + + void println(String string) + { + println(0, string); + } + + void println(int depth, String string) + { + printIndent(depth); + + _dbg.println(string); + _dbg.flush(); + _isNewline = true; + _isObject = false; + _column = 0; + } + + void println() + { + if (! _isNewline) { + _dbg.println(); + _dbg.flush(); + } + + _isNewline = true; + _isObject = false; + _column = 0; + } + + void printObject(String string) + { + if (_isObject) + println(); + + printIndent(0); + + _dbg.print(string); + _dbg.flush(); + + _column += string.length(); + + _isNewline = false; + _isObject = true; + } + + protected State nextObject(int ch) + { + switch (ch) { + case -1: + println(); + return this; + + case 'N': + if (isShift(null)) + return shift(null); + else { + printObject("null"); + return this; + } + + case 'T': + if (isShift(Boolean.TRUE)) + return shift(Boolean.TRUE); + else { + printObject("true"); + return this; + } + + case 'F': + if (isShift(Boolean.FALSE)) + return shift(Boolean.FALSE); + else { + printObject("false"); + return this; + } + + case 0x80: case 0x81: case 0x82: case 0x83: + case 0x84: case 0x85: case 0x86: case 0x87: + case 0x88: case 0x89: case 0x8a: case 0x8b: + case 0x8c: case 0x8d: case 0x8e: case 0x8f: + + case 0x90: case 0x91: case 0x92: case 0x93: + case 0x94: case 0x95: case 0x96: case 0x97: + case 0x98: case 0x99: case 0x9a: case 0x9b: + case 0x9c: case 0x9d: case 0x9e: case 0x9f: + + case 0xa0: case 0xa1: case 0xa2: case 0xa3: + case 0xa4: case 0xa5: case 0xa6: case 0xa7: + case 0xa8: case 0xa9: case 0xaa: case 0xab: + case 0xac: case 0xad: case 0xae: case 0xaf: + + case 0xb0: case 0xb1: case 0xb2: case 0xb3: + case 0xb4: case 0xb5: case 0xb6: case 0xb7: + case 0xb8: case 0xb9: case 0xba: case 0xbb: + case 0xbc: case 0xbd: case 0xbe: case 0xbf: + { + Integer value = new Integer(ch - 0x90); + + if (isShift(value)) + return shift(value); + else { + printObject(value.toString()); + return this; + } + } + + case 0xc0: case 0xc1: case 0xc2: case 0xc3: + case 0xc4: case 0xc5: case 0xc6: case 0xc7: + case 0xc8: case 0xc9: case 0xca: case 0xcb: + case 0xcc: case 0xcd: case 0xce: case 0xcf: + return new IntegerState(this, "int", ch - 0xc8, 3); + + case 0xd0: case 0xd1: case 0xd2: case 0xd3: + case 0xd4: case 0xd5: case 0xd6: case 0xd7: + return new IntegerState(this, "int", ch - 0xd4, 2); + + case 'I': + return new IntegerState(this, "int"); + + case 0xd8: case 0xd9: case 0xda: case 0xdb: + case 0xdc: case 0xdd: case 0xde: case 0xdf: + case 0xe0: case 0xe1: case 0xe2: case 0xe3: + case 0xe4: case 0xe5: case 0xe6: case 0xe7: + case 0xe8: case 0xe9: case 0xea: case 0xeb: + case 0xec: case 0xed: case 0xee: case 0xef: + { + Long value = new Long(ch - 0xe0); + + if (isShift(value)) + return shift(value); + else { + printObject(value.toString() + "L"); + return this; + } + } + + case 0xf0: case 0xf1: case 0xf2: case 0xf3: + case 0xf4: case 0xf5: case 0xf6: case 0xf7: + case 0xf8: case 0xf9: case 0xfa: case 0xfb: + case 0xfc: case 0xfd: case 0xfe: case 0xff: + return new LongState(this, "long", ch - 0xf8, 7); + + case 0x38: case 0x39: case 0x3a: case 0x3b: + case 0x3c: case 0x3d: case 0x3e: case 0x3f: + return new LongState(this, "long", ch - 0x3c, 6); + + case BC_LONG_INT: + return new LongState(this, "long", 0, 4); + + case 'L': + return new LongState(this, "long"); + + case 0x5b: case 0x5c: + { + Double value = new Double(ch - 0x5b); + + if (isShift(value)) + return shift(value); + else { + printObject(value.toString()); + return this; + } + } + + case 0x5d: + return new DoubleIntegerState(this, 3); + + case 0x5e: + return new DoubleIntegerState(this, 2); + + case 0x5f: + return new MillsState(this); + + case 'D': + return new DoubleState(this); + + case 'Q': + return new RefState(this); + + case BC_DATE: + return new DateState(this); + + case BC_DATE_MINUTE: + return new DateState(this, true); + + case 0x00: + { + String value = "\"\""; + + if (isShift(value)) + return shift(value); + else { + printObject(value.toString()); + return this; + } + } + + case 0x01: case 0x02: case 0x03: + case 0x04: case 0x05: case 0x06: case 0x07: + case 0x08: case 0x09: case 0x0a: case 0x0b: + case 0x0c: case 0x0d: case 0x0e: case 0x0f: + + case 0x10: case 0x11: case 0x12: case 0x13: + case 0x14: case 0x15: case 0x16: case 0x17: + case 0x18: case 0x19: case 0x1a: case 0x1b: + case 0x1c: case 0x1d: case 0x1e: case 0x1f: + return new StringState(this, 'S', ch); + + case 0x30: case 0x31: case 0x32: case 0x33: + return new StringState(this, 'S', ch - 0x30, true); + + case 'R': + return new StringState(this, 'S', false); + + case 'S': + return new StringState(this, 'S', true); + + case 0x20: + { + String value = "binary(0)"; + + if (isShift(value)) + return shift(value); + else { + printObject(value.toString()); + return this; + } + } + + case 0x21: case 0x22: case 0x23: + case 0x24: case 0x25: case 0x26: case 0x27: + case 0x28: case 0x29: case 0x2a: case 0x2b: + case 0x2c: case 0x2d: case 0x2e: case 0x2f: + return new BinaryState(this, 'B', ch - 0x20); + + case 0x34: case 0x35: case 0x36: case 0x37: + return new BinaryState(this, 'B', ch - 0x34, true); + + case 'A': + return new BinaryState(this, 'B', false); + + case 'B': + return new BinaryState(this, 'B', true); + + case 'M': + return new MapState(this, _refId++); + + case 'H': + return new MapState(this, _refId++, false); + + case BC_LIST_VARIABLE: + return new ListState(this, _refId++, true); + + case BC_LIST_VARIABLE_UNTYPED: + return new ListState(this, _refId++, false); + + case BC_LIST_FIXED: + return new CompactListState(this, _refId++, true); + + case BC_LIST_FIXED_UNTYPED: + return new CompactListState(this, _refId++, false); + + case 0x70: case 0x71: case 0x72: case 0x73: + case 0x74: case 0x75: case 0x76: case 0x77: + return new CompactListState(this, _refId++, true, ch - 0x70); + + case 0x78: case 0x79: case 0x7a: case 0x7b: + case 0x7c: case 0x7d: case 0x7e: case 0x7f: + return new CompactListState(this, _refId++, false, ch - 0x78); + + case 'C': + return new ObjectDefState(this); + + case 0x60: case 0x61: case 0x62: case 0x63: + case 0x64: case 0x65: case 0x66: case 0x67: + case 0x68: case 0x69: case 0x6a: case 0x6b: + case 0x6c: case 0x6d: case 0x6e: case 0x6f: + return new ObjectState(this, _refId++, ch - 0x60); + + case 'O': + return new ObjectState(this, _refId++); + + default: + return this; + } + } + } + + class InitialState extends State { + State next(int ch) + { + println(); + + if (ch == 'r') { + return new ReplyState(this); + } + else if (ch == 'c') { + return new CallState(this); + } + else + return nextObject(ch); + } + } + + class Top2State extends State { + State next(int ch) + { + println(); + + if (ch == 'R') { + return new Reply2State(this); + } + else if (ch == 'F') { + return new Fault2State(this); + } + else if (ch == 'C') { + return new Call2State(this); + } + else if (ch == 'H') { + return new Hessian2State(this); + } + else if (ch == 'r') { + return new ReplyState(this); + } + else if (ch == 'c') { + return new CallState(this); + } + else + return nextObject(ch); + } + } + + class IntegerState extends State { + String _typeCode; + + int _length; + int _value; + + IntegerState(State next, String typeCode) + { + super(next); + + _typeCode = typeCode; + } + + IntegerState(State next, String typeCode, int value, int length) + { + super(next); + + _typeCode = typeCode; + + _value = value; + _length = length; + } + + State next(int ch) + { + _value = 256 * _value + (ch & 0xff); + + if (++_length == 4) { + Integer value = new Integer(_value); + + if (_next.isShift(value)) + return _next.shift(value); + else { + printObject(value.toString()); + + return _next; + } + } + else + return this; + } + } + + class LongState extends State { + String _typeCode; + + int _length; + long _value; + + LongState(State next, String typeCode) + { + super(next); + + _typeCode = typeCode; + } + + LongState(State next, String typeCode, long value, int length) + { + super(next); + + _typeCode = typeCode; + + _value = value; + _length = length; + } + + State next(int ch) + { + _value = 256 * _value + (ch & 0xff); + + if (++_length == 8) { + Long value = new Long(_value); + + if (_next.isShift(value)) + return _next.shift(value); + else { + printObject(value.toString() + "L"); + + return _next; + } + } + else + return this; + } + } + + class DoubleIntegerState extends State { + int _length; + int _value; + boolean _isFirst = true; + + DoubleIntegerState(State next, int length) + { + super(next); + + _length = length; + } + + State next(int ch) + { + if (_isFirst) + _value = (byte) ch; + else + _value = 256 * _value + (ch & 0xff); + + _isFirst = false; + + if (++_length == 4) { + Double value = new Double(_value); + + if (_next.isShift(value)) + return _next.shift(value); + else { + printObject(value.toString()); + + return _next; + } + } + else + return this; + } + } + + class RefState extends State { + String _typeCode; + + int _length; + int _value; + + RefState(State next) + { + super(next); + } + + RefState(State next, String typeCode) + { + super(next); + + _typeCode = typeCode; + } + + RefState(State next, String typeCode, int value, int length) + { + super(next); + + _typeCode = typeCode; + + _value = value; + _length = length; + } + + @Override + boolean isShift(Object o) + { + return true; + } + + @Override + State shift(Object o) + { + println("ref #" + o); + + return _next; + } + + @Override + State next(int ch) + { + return nextObject(ch); + } + } + + class DateState extends State { + int _length; + long _value; + boolean _isMinute; + + DateState(State next) + { + super(next); + } + + DateState(State next, boolean isMinute) + { + super(next); + + _length = 4; + _isMinute = isMinute; + } + + + State next(int ch) + { + _value = 256 * _value + (ch & 0xff); + + if (++_length == 8) { + java.util.Date value; + + if (_isMinute) + value = new java.util.Date(_value * 60000L); + else + value = new java.util.Date(_value); + + if (_next.isShift(value)) + return _next.shift(value); + else { + printObject(value.toString()); + + return _next; + } + } + else + return this; + } + } + + class DoubleState extends State { + int _length; + long _value; + + DoubleState(State next) + { + super(next); + } + + State next(int ch) + { + _value = 256 * _value + (ch & 0xff); + + if (++_length == 8) { + Double value = Double.longBitsToDouble(_value); + + if (_next.isShift(value)) + return _next.shift(value); + else { + printObject(value.toString()); + + return _next; + } + } + else + return this; + } + } + + class MillsState extends State { + int _length; + int _value; + + MillsState(State next) + { + super(next); + } + + State next(int ch) + { + _value = 256 * _value + (ch & 0xff); + + if (++_length == 4) { + Double value = 0.001 * _value; + + if (_next.isShift(value)) + return _next.shift(value); + else { + printObject(value.toString()); + + return _next; + } + } + else + return this; + } + } + + class StringState extends State { + private static final int TOP = 0; + private static final int UTF_2_1 = 1; + private static final int UTF_3_1 = 2; + private static final int UTF_3_2 = 3; + + char _typeCode; + + StringBuilder _value = new StringBuilder(); + int _lengthIndex; + int _length; + boolean _isLastChunk; + + int _utfState; + char _ch; + + StringState(State next, char typeCode, boolean isLastChunk) + { + super(next); + + _typeCode = typeCode; + _isLastChunk = isLastChunk; + } + + StringState(State next, char typeCode, int length) + { + super(next); + + _typeCode = typeCode; + _isLastChunk = true; + _length = length; + _lengthIndex = 2; + } + + StringState(State next, char typeCode, int length, boolean isLastChunk) + { + super(next); + + _typeCode = typeCode; + _isLastChunk = isLastChunk; + _length = length; + _lengthIndex = 1; + } + + State next(int ch) + { + if (_lengthIndex < 2) { + _length = 256 * _length + (ch & 0xff); + + if (++_lengthIndex == 2 && _length == 0 && _isLastChunk) { + if (_next.isShift(_value.toString())) + return _next.shift(_value.toString()); + else { + printObject("\"" + _value + "\""); + return _next; + } + } + else + return this; + } + else if (_length == 0) { + if (ch == 's' || ch == 'x') { + _isLastChunk = false; + _lengthIndex = 0; + return this; + } + else if (ch == 'S' || ch == 'X') { + _isLastChunk = true; + _lengthIndex = 0; + return this; + } + else if (ch == 0x00) { + if (_next.isShift(_value.toString())) + return _next.shift(_value.toString()); + else { + printObject("\"" + _value + "\""); + return _next; + } + } + else if (0x00 <= ch && ch < 0x20) { + _isLastChunk = true; + _lengthIndex = 2; + _length = ch & 0xff; + return this; + } + else if (0x30 <= ch && ch < 0x34) { + _isLastChunk = true; + _lengthIndex = 1; + _length = (ch - 0x30); + return this; + } + else { + println(String.valueOf((char) ch) + ": unexpected character"); + return _next; + } + } + + switch (_utfState) { + case TOP: + if (ch < 0x80) { + _length--; + + _value.append((char) ch); + } + else if (ch < 0xe0) { + _ch = (char) ((ch & 0x1f) << 6); + _utfState = UTF_2_1; + } + else { + _ch = (char) ((ch & 0xf) << 12); + _utfState = UTF_3_1; + } + break; + + case UTF_2_1: + case UTF_3_2: + _ch += ch & 0x3f; + _value.append(_ch); + _length--; + _utfState = TOP; + break; + + case UTF_3_1: + _ch += (char) ((ch & 0x3f) << 6); + _utfState = UTF_3_2; + break; + } + + if (_length == 0 && _isLastChunk) { + if (_next.isShift(_value.toString())) + return _next.shift(_value.toString()); + else { + printObject("\"" + _value + "\""); + + return _next; + } + } + else + return this; + } + } + + class BinaryState extends State { + char _typeCode; + + int _totalLength; + + int _lengthIndex; + int _length; + boolean _isLastChunk; + + BinaryState(State next, char typeCode, boolean isLastChunk) + { + super(next); + + _typeCode = typeCode; + _isLastChunk = isLastChunk; + } + + BinaryState(State next, char typeCode, int length) + { + super(next); + + _typeCode = typeCode; + _isLastChunk = true; + _length = length; + _lengthIndex = 2; + } + + BinaryState(State next, char typeCode, int length, boolean isLastChunk) + { + super(next); + + _typeCode = typeCode; + _isLastChunk = isLastChunk; + _length = length; + _lengthIndex = 1; + } + + State next(int ch) + { + if (_lengthIndex < 2) { + _length = 256 * _length + (ch & 0xff); + + if (++_lengthIndex == 2 && _length == 0 && _isLastChunk) { + String value = "binary(" + _totalLength + ")"; + + if (_next.isShift(value)) + return _next.shift(value); + else { + printObject(value); + return _next; + } + } + else + return this; + } + else if (_length == 0) { + if (ch == 'b') { + _isLastChunk = false; + _lengthIndex = 0; + return this; + } + else if (ch == 'B') { + _isLastChunk = true; + _lengthIndex = 0; + return this; + } + else if (ch == 0x20) { + String value = "binary(" + _totalLength + ")"; + + if (_next.isShift(value)) + return _next.shift(value); + else { + printObject(value); + return _next; + } + } + else if (0x20 <=ch && ch < 0x30) { + _isLastChunk = true; + _lengthIndex = 2; + _length = (ch & 0xff) - 0x20; + return this; + } + else { + println(String.valueOf((char) ch) + ": unexpected character"); + return _next; + } + } + + _length--; + _totalLength++; + + if (_length == 0 && _isLastChunk) { + String value = "binary(" + _totalLength + ")"; + + if (_next.isShift(value)) + return _next.shift(value); + else { + printObject(value); + + return _next; + } + } + else + return this; + } + } + + class MapState extends State { + private static final int TYPE = 0; + private static final int KEY = 1; + private static final int VALUE = 2; + + private int _refId; + + private int _state; + private int _valueDepth; + private boolean _hasData; + + MapState(State next, int refId) + { + super(next); + + _refId = refId; + _state = TYPE; + } + + MapState(State next, int refId, boolean isType) + { + super(next); + + _refId = refId; + + if (isType) + _state = TYPE; + else { + printObject("map (#" + _refId + ")"); + _state = VALUE; + } + } + + @Override + boolean isShift(Object value) + { + return _state == TYPE; + } + + @Override + State shift(Object type) + { + if (_state == TYPE) { + if (type instanceof String) { + _typeDefList.add((String) type); + } + else if (type instanceof Integer) { + int iValue = (Integer) type; + + if (iValue >= 0 && iValue < _typeDefList.size()) + type = _typeDefList.get(iValue); + } + + printObject("map " + type + " (#" + _refId + ")"); + + _state = VALUE; + + return this; + } + else + throw new IllegalStateException(); + } + + @Override + int depth() + { + if (_state == TYPE) + return _next.depth(); + else if (_state == KEY) + return _next.depth() + 2; + else + return _valueDepth; + } + + State next(int ch) + { + switch (_state) { + case TYPE: + return nextObject(ch); + + case VALUE: + if (ch == 'Z') { + if (_hasData) + println(); + + return _next; + } + else { + if (_hasData) + println(); + + _hasData = true; + _state = KEY; + + return nextObject(ch); + } + + case KEY: + print(" => "); + _isObject = false; + _valueDepth = _column; + + _state = VALUE; + + return nextObject(ch); + + default: + throw new IllegalStateException(); + } + } + } + + class ObjectDefState extends State { + private static final int TYPE = 1; + private static final int COUNT = 2; + private static final int FIELD = 3; + private static final int COMPLETE = 4; + + private int _refId; + + private int _state; + private boolean _hasData; + private int _count; + + private String _type; + private ArrayList _fields = new ArrayList(); + + ObjectDefState(State next) + { + super(next); + + _state = TYPE; + } + + @Override + boolean isShift(Object value) + { + return true; + } + + @Override + State shift(Object object) + { + if (_state == TYPE) { + _type = (String) object; + + print("/* defun " + _type + " ["); + + _objectDefList.add(new ObjectDef(_type, _fields)); + + _state = COUNT; + } + else if (_state == COUNT) { + _count = (Integer) object; + + _state = FIELD; + } + else if (_state == FIELD) { + String field = (String) object; + + _count--; + + _fields.add(field); + + if (_fields.size() == 1) + print(field); + else + print(", " + field); + } + else { + throw new UnsupportedOperationException(); + } + + return this; + } + + @Override + int depth() + { + if (_state <= TYPE) + return _next.depth(); + else + return _next.depth() + 2; + } + + State next(int ch) + { + switch (_state) { + case TYPE: + return nextObject(ch); + + case COUNT: + return nextObject(ch); + + case FIELD: + if (_count == 0) { + println("] */"); + _next.printIndent(0); + + return _next.nextObject(ch); + } + else + return nextObject(ch); + + default: + throw new IllegalStateException(); + } + } + } + + class ObjectState extends State { + private static final int TYPE = 0; + private static final int FIELD = 1; + + private int _refId; + + private int _state; + private ObjectDef _def; + private int _count; + private int _fieldDepth; + + ObjectState(State next, int refId) + { + super(next); + + _refId = refId; + _state = TYPE; + } + + ObjectState(State next, int refId, int def) + { + super(next); + + _refId = refId; + _state = FIELD; + + if (def < 0 || _objectDefList.size() <= def) { + throw new IllegalStateException(def + " is an unknown object type"); + } + + _def = _objectDefList.get(def); + + println("object " + _def.getType() + " (#" + _refId + ")"); + } + + @Override + boolean isShift(Object value) + { + if (_state == TYPE) + return true; + else + return false; + } + + @Override + State shift(Object object) + { + if (_state == TYPE) { + int def = (Integer) object; + + _def = _objectDefList.get(def); + + println("object " + _def.getType() + " (#" + _refId + ")"); + + _state = FIELD; + + if (_def.getFields().size() == 0) + return _next; + } + + return this; + } + + @Override + int depth() + { + if (_state <= TYPE) + return _next.depth(); + else + return _fieldDepth; + } + + State next(int ch) + { + switch (_state) { + case TYPE: + return nextObject(ch); + + case FIELD: + if (_def.getFields().size() <= _count) + return _next.next(ch); + + _fieldDepth = _next.depth() + 2; + println(); + print(_def.getFields().get(_count++) + ": "); + + _fieldDepth = _column; + + _isObject = false; + return nextObject(ch); + + default: + throw new IllegalStateException(); + } + } + } + + class ListState extends State { + private static final int TYPE = 0; + private static final int LENGTH = 1; + private static final int VALUE = 2; + + private int _refId; + + private int _state; + private boolean _hasData; + private int _count; + private int _valueDepth; + + ListState(State next, int refId, boolean isType) + { + super(next); + + _refId = refId; + + if (isType) + _state = TYPE; + else { + printObject("list (#" + _refId + ")"); + _state = VALUE; + } + } + + @Override + boolean isShift(Object value) + { + return _state == TYPE || _state == LENGTH; + } + + @Override + State shift(Object object) + { + if (_state == TYPE) { + Object type = object; + + if (type instanceof String) { + _typeDefList.add((String) type); + } + else if (object instanceof Integer) { + int index = (Integer) object; + + if (index >= 0 && index < _typeDefList.size()) + type = _typeDefList.get(index); + else + type = "type-unknown(" + index + ")"; + } + + printObject("list " + type + "(#" + _refId + ")"); + + _state = VALUE; + + return this; + } + else if (_state == LENGTH) { + _state = VALUE; + + return this; + } + else + return this; + } + + @Override + int depth() + { + if (_state <= LENGTH) + return _next.depth(); + else if (_state == VALUE) + return _valueDepth; + else + return _next.depth() + 2; + } + + State next(int ch) + { + switch (_state) { + case TYPE: + return nextObject(ch); + + case VALUE: + if (ch == 'Z') { + if (_count > 0) + println(); + + return _next; + } + else { + _valueDepth = _next.depth() + 2; + println(); + printObject(_count++ + ": "); + _valueDepth = _column; + _isObject = false; + + return nextObject(ch); + } + + default: + throw new IllegalStateException(); + } + } + } + + class CompactListState extends State { + private static final int TYPE = 0; + private static final int LENGTH = 1; + private static final int VALUE = 2; + + private int _refId; + + private boolean _isTyped; + private boolean _isLength; + + private int _state; + private boolean _hasData; + private int _length; + private int _count; + private int _valueDepth; + + CompactListState(State next, int refId, boolean isTyped) + { + super(next); + + _isTyped = isTyped; + _refId = refId; + + if (isTyped) + _state = TYPE; + else + _state = LENGTH; + } + + CompactListState(State next, int refId, boolean isTyped, int length) + { + super(next); + + _isTyped = isTyped; + _refId = refId; + _length = length; + + _isLength = true; + + if (isTyped) + _state = TYPE; + else { + printObject("list (#" + _refId + ")"); + + _state = VALUE; + } + } + + @Override + boolean isShift(Object value) + { + return _state == TYPE || _state == LENGTH; + } + + @Override + State shift(Object object) + { + if (_state == TYPE) { + Object type = object; + + if (object instanceof Integer) { + int index = (Integer) object; + + if (index >= 0 && index < _typeDefList.size()) + type = _typeDefList.get(index); + else + type = "type-unknown(" + index + ")"; + } + else if (object instanceof String) + _typeDefList.add((String) object); + + printObject("list " + type + " (#" + _refId + ")"); + + if (_isLength) { + _state = VALUE; + + if (_length == 0) + return _next; + } + else + _state = LENGTH; + + return this; + } + else if (_state == LENGTH) { + _length = (Integer) object; + + if (! _isTyped) + printObject("list (#" + _refId + ")"); + + _state = VALUE; + + if (_length == 0) + return _next; + else + return this; + } + else + return this; + } + + @Override + int depth() + { + if (_state <= LENGTH) + return _next.depth(); + else if (_state == VALUE) + return _valueDepth; + else + return _next.depth() + 2; + } + + State next(int ch) + { + switch (_state) { + case TYPE: + return nextObject(ch); + + case LENGTH: + return nextObject(ch); + + case VALUE: + if (_length <= _count) + return _next.next(ch); + else { + _valueDepth = _next.depth() + 2; + println(); + printObject(_count++ + ": "); + _valueDepth = _column; + _isObject = false; + + return nextObject(ch); + } + + default: + throw new IllegalStateException(); + } + } + } + + class Hessian2State extends State { + private static final int MAJOR = 0; + private static final int MINOR = 1; + + private int _state; + private int _major; + private int _minor; + + Hessian2State(State next) + { + super(next); + } + + int depth() + { + return _next.depth() + 2; + } + + State next(int ch) + { + switch (_state) { + case MAJOR: + _major = ch; + _state = MINOR; + return this; + + case MINOR: + _minor = ch; + println(-2, "hessian " + _major + "." + _minor); + return _next; + + default: + throw new IllegalStateException(); + } + } + } + + class CallState extends State { + private static final int MAJOR = 0; + private static final int MINOR = 1; + private static final int HEADER = 2; + private static final int METHOD = 3; + private static final int VALUE = 4; + private static final int ARG = 5; + + private int _state; + private int _major; + private int _minor; + + CallState(State next) + { + super(next); + } + + int depth() + { + return _next.depth() + 2; + } + + State next(int ch) + { + switch (_state) { + case MAJOR: + _major = ch; + _state = MINOR; + return this; + + case MINOR: + _minor = ch; + _state = HEADER; + println(-2, "call " + _major + "." + _minor); + return this; + + case HEADER: + if (ch == 'H') { + println(); + print("header "); + _isObject = false; + _state = VALUE; + return new StringState(this, 'H', true); + } + else if (ch == 'm') { + println(); + print("method "); + _isObject = false; + _state = ARG; + return new StringState(this, 'm', true); + } + else { + println((char) ch + ": unexpected char"); + return popStack(); + } + + case VALUE: + print(" => "); + _isObject = false; + _state = HEADER; + return nextObject(ch); + + case ARG: + if (ch == 'Z') + return _next; + else + return nextObject(ch); + + default: + throw new IllegalStateException(); + } + } + } + + class Call2State extends State { + private static final int METHOD = 0; + private static final int COUNT = 1; + private static final int ARG = 2; + + private int _state = METHOD; + private int _i; + private int _count; + + Call2State(State next) + { + super(next); + } + + int depth() + { + return _next.depth() + 5; + } + + @Override + boolean isShift(Object value) + { + return _state != ARG; + } + + @Override + State shift(Object object) + { + if (_state == METHOD) { + println(-5, "Call " + object); + + _state = COUNT; + return this; + } + else if (_state == COUNT) { + Integer count = (Integer) object; + + _count = count; + + _state = ARG; + + if (_count == 0) + return _next; + else + return this; + } + else + return this; + } + + @Override + State next(int ch) + { + switch (_state) { + case COUNT: + return nextObject(ch); + + case METHOD: + return nextObject(ch); + + case ARG: + if (_count <= _i) + return _next.next(ch); + else { + println(); + print(-3, _i++ + ": "); + + return nextObject(ch); + } + + default: + throw new IllegalStateException(); + } + } + } + + class ReplyState extends State { + private static final int MAJOR = 0; + private static final int MINOR = 1; + private static final int HEADER = 2; + private static final int VALUE = 3; + private static final int END = 4; + + private int _state; + private int _major; + private int _minor; + + ReplyState(State next) + { + _next = next; + } + + int depth() + { + return _next.depth() + 2; + } + + State next(int ch) + { + switch (_state) { + case MAJOR: + if (ch == 't' || ch == 'S') + return new RemoteState(this).next(ch); + + _major = ch; + _state = MINOR; + return this; + + case MINOR: + _minor = ch; + _state = HEADER; + println(-2, "reply " + _major + "." + _minor); + return this; + + case HEADER: + if (ch == 'H') { + _state = VALUE; + return new StringState(this, 'H', true); + } + else if (ch == 'f') { + print("fault "); + _isObject = false; + _state = END; + return new MapState(this, 0); + } + else { + _state = END; + return nextObject(ch); + } + + case VALUE: + _state = HEADER; + return nextObject(ch); + + case END: + println(); + if (ch == 'Z') { + return _next; + } + else + return _next.next(ch); + + default: + throw new IllegalStateException(); + } + } + } + + class Reply2State extends State { + Reply2State(State next) + { + super(next); + + println(-2, "Reply"); + } + + int depth() + { + return _next.depth() + 2; + } + + @Override + State next(int ch) + { + return nextObject(ch); + } + } + + class Fault2State extends State { + Fault2State(State next) + { + super(next); + + println(-2, "Fault"); + } + + int depth() + { + return _next.depth() + 2; + } + + @Override + State next(int ch) + { + return nextObject(ch); + } + } + + class IndirectState extends State { + IndirectState(State next) + { + super(next); + } + + boolean isShift(Object object) + { + return _next.isShift(object); + } + + State shift(Object object) + { + return _next.shift(object); + } + + State next(int ch) + { + return nextObject(ch); + } + } + + class RemoteState extends State { + private static final int TYPE = 0; + private static final int VALUE = 1; + private static final int END = 2; + + private int _state; + private int _major; + private int _minor; + + RemoteState(State next) + { + super(next); + } + + State next(int ch) + { + switch (_state) { + case TYPE: + println(-1, "remote"); + if (ch == 't') { + _state = VALUE; + return new StringState(this, 't', false); + } + else { + _state = END; + return nextObject(ch); + } + + case VALUE: + _state = END; + return _next.nextObject(ch); + + case END: + return _next.next(ch); + + default: + throw new IllegalStateException(); + } + } + } + + class StreamingState extends State { + private int _digit; + private int _length; + private boolean _isLast; + private boolean _isFirst = true; + + private State _childState; + + StreamingState(State next, boolean isLast) + { + super(next); + + _isLast = isLast; + _childState = new InitialState(); + } + + State next(int ch) + { + if (_digit < 2) { + _length = 256 * _length + ch; + _digit++; + + if (_digit == 2 && _length == 0 && _isLast) { + _refId = 0; + return _next; + } + else { + if (_digit == 2) + println(-1, "packet-start(" + _length + ")"); + + return this; + } + } + else if (_length == 0) { + _isLast = (ch == 'P'); + _digit = 0; + + return this; + } + + _childState = _childState.next(ch); + + _length--; + + if (_length == 0 && _isLast) { + println(-1, ""); + println(-1, "packet-end"); + _refId = 0; + return _next; + } + else + return this; + } + } + + static class ObjectDef { + private String _type; + private ArrayList _fields; + + ObjectDef(String type, ArrayList fields) + { + _type = type; + _fields = fields; + } + + String getType() + { + return _type; + } + + ArrayList getFields() + { + return _fields; + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianEnvelope.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianEnvelope.java new file mode 100644 index 000000000000..626548f4df4f --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianEnvelope.java @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.*; + +/** + * Factory class for wrapping and unwrapping hessian streams. + */ +abstract public class HessianEnvelope { + /** + * Wrap the Hessian output stream in an envelope. + */ + abstract public Hessian2Output wrap(Hessian2Output out) + throws IOException; + + /** + * Unwrap the Hessian input stream with this envelope. It is an + * error if the actual envelope does not match the expected envelope + * class. + */ + abstract public Hessian2Input unwrap(Hessian2Input in) + throws IOException; + + /** + * Unwrap the envelope after having read the envelope code ('E') and + * the envelope method. Called by the EnvelopeFactory for dynamic + * reading of the envelopes. + */ + abstract public Hessian2Input unwrapHeaders(Hessian2Input in) + throws IOException; +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianFieldException.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianFieldException.java new file mode 100644 index 000000000000..72dcd62f804d --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianFieldException.java @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Exception during field reading. + */ +public class HessianFieldException extends HessianProtocolException { + /** + * Zero-arg constructor. + */ + public HessianFieldException() + { + } + + /** + * Create the exception. + */ + public HessianFieldException(String message) + { + super(message); + } + + /** + * Create the exception. + */ + public HessianFieldException(String message, Throwable cause) + { + super(message, cause); + } + + /** + * Create the exception. + */ + public HessianFieldException(Throwable cause) + { + super(cause); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianHandle.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianHandle.java new file mode 100644 index 000000000000..3103a871f761 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianHandle.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +/** + * Marks a type as a handle + */ +public interface HessianHandle { +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianInput.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianInput.java new file mode 100644 index 000000000000..363222ef69ba --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianInput.java @@ -0,0 +1,1700 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; + +/** + * Input stream for Hessian requests. + * + *

HessianInput is unbuffered, so any client needs to provide + * its own buffering. + * + *

+ * InputStream is = ...; // from http connection
+ * HessianInput in = new HessianInput(is);
+ * String value;
+ *
+ * in.startReply();         // read reply header
+ * value = in.readString(); // read string value
+ * in.completeReply();      // read reply footer
+ * 
+ */ +public class HessianInput extends AbstractHessianInput { + private static int END_OF_DATA = -2; + + private static Field _detailMessageField; + + // factory for deserializing objects in the input stream + protected SerializerFactory _serializerFactory; + + protected ArrayList _refs; + + // the underlying input stream + private InputStream _is; + // a peek character + protected int _peek = -1; + + // the method for a call + private String _method; + + private Reader _chunkReader; + private InputStream _chunkInputStream; + + private Throwable _replyFault; + + private StringBuffer _sbuf = new StringBuffer(); + + // true if this is the last chunk + private boolean _isLastChunk; + // the chunk length + private int _chunkLength; + + /** + * Creates an uninitialized Hessian input stream. + */ + public HessianInput() + { + } + + /** + * Creates a new Hessian input stream, initialized with an + * underlying input stream. + * + * @param is the underlying input stream. + */ + public HessianInput(InputStream is) + { + init(is); + } + + /** + * Sets the serializer factory. + */ + public void setSerializerFactory(SerializerFactory factory) + { + _serializerFactory = factory; + } + + /** + * Gets the serializer factory. + */ + public SerializerFactory getSerializerFactory() + { + return _serializerFactory; + } + + /** + * Initialize the hessian stream with the underlying input stream. + */ + public void init(InputStream is) + { + _is = is; + _method = null; + _isLastChunk = true; + _chunkLength = 0; + _peek = -1; + _refs = null; + _replyFault = null; + + if (_serializerFactory == null) + _serializerFactory = new SerializerFactory(); + } + + /** + * Returns the calls method + */ + public String getMethod() + { + return _method; + } + + /** + * Returns any reply fault. + */ + public Throwable getReplyFault() + { + return _replyFault; + } + + /** + * Starts reading the call + * + *
+   * c major minor
+   * 
+ */ + public int readCall() + throws IOException + { + int tag = read(); + + if (tag != 'c') + throw error("expected hessian call ('c') at " + codeName(tag)); + + int major = read(); + int minor = read(); + + return (major << 16) + minor; + } + + /** + * For backward compatibility with HessianSkeleton + */ + public void skipOptionalCall() + throws IOException + { + int tag = read(); + + if (tag == 'c') { + read(); + read(); + } + else + _peek = tag; + } + + /** + * Starts reading the call + * + *

A successful completion will have a single value: + * + *

+   * m b16 b8 method
+   * 
+ */ + public String readMethod() + throws IOException + { + int tag = read(); + + if (tag != 'm') + throw error("expected hessian method ('m') at " + codeName(tag)); + int d1 = read(); + int d2 = read(); + + _isLastChunk = true; + _chunkLength = d1 * 256 + d2; + _sbuf.setLength(0); + int ch; + while ((ch = parseChar()) >= 0) + _sbuf.append((char) ch); + + _method = _sbuf.toString(); + + return _method; + } + + /** + * Starts reading the call, including the headers. + * + *

The call expects the following protocol data + * + *

+   * c major minor
+   * m b16 b8 method
+   * 
+ */ + public void startCall() + throws IOException + { + readCall(); + + while (readHeader() != null) { + readObject(); + } + + readMethod(); + } + + /** + * Completes reading the call + * + *

A successful completion will have a single value: + * + *

+   * z
+   * 
+ */ + public void completeCall() + throws IOException + { + int tag = read(); + + if (tag == 'z') { + } + else + throw error("expected end of call ('z') at " + codeName(tag) + ". Check method arguments and ensure method overloading is enabled if necessary"); + } + + /** + * Reads a reply as an object. + * If the reply has a fault, throws the exception. + */ + public Object readReply(Class expectedClass) + throws Throwable + { + int tag = read(); + + if (tag != 'r') + error("expected hessian reply at " + codeName(tag)); + + int major = read(); + int minor = read(); + + tag = read(); + if (tag == 'f') + throw prepareFault(); + else { + _peek = tag; + + Object value = readObject(expectedClass); + + completeValueReply(); + + return value; + } + } + + /** + * Starts reading the reply + * + *

A successful completion will have a single value: + * + *

+   * r
+   * 
+ */ + public void startReply() + throws Throwable + { + int tag = read(); + + if (tag != 'r') + error("expected hessian reply at " + codeName(tag)); + + int major = read(); + int minor = read(); + + tag = read(); + if (tag == 'f') + throw prepareFault(); + else + _peek = tag; + } + + /** + * Prepares the fault. + */ + private Throwable prepareFault() + throws IOException + { + HashMap fault = readFault(); + + Object detail = fault.get("detail"); + String message = (String) fault.get("message"); + + if (detail instanceof Throwable) { + _replyFault = (Throwable) detail; + + if (message != null && _detailMessageField != null) { + try { + _detailMessageField.set(_replyFault, message); + } catch (Throwable e) { + } + } + + return _replyFault; + } + + else { + String code = (String) fault.get("code"); + + _replyFault = new HessianServiceException(message, code, detail); + + return _replyFault; + } + } + + /** + * Completes reading the call + * + *

A successful completion will have a single value: + * + *

+   * z
+   * 
+ */ + public void completeReply() + throws IOException + { + int tag = read(); + + if (tag != 'z') + error("expected end of reply at " + codeName(tag)); + } + + /** + * Completes reading the call + * + *

A successful completion will have a single value: + * + *

+   * z
+   * 
+ */ + public void completeValueReply() + throws IOException + { + int tag = read(); + + if (tag != 'z') + error("expected end of reply at " + codeName(tag)); + } + + /** + * Reads a header, returning null if there are no headers. + * + *
+   * H b16 b8 value
+   * 
+ */ + public String readHeader() + throws IOException + { + int tag = read(); + + if (tag == 'H') { + _isLastChunk = true; + _chunkLength = (read() << 8) + read(); + + _sbuf.setLength(0); + int ch; + while ((ch = parseChar()) >= 0) + _sbuf.append((char) ch); + + return _sbuf.toString(); + } + + _peek = tag; + + return null; + } + + /** + * Reads a null + * + *
+   * N
+   * 
+ */ + public void readNull() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': return; + + default: + throw expect("null", tag); + } + } + + /** + * Reads a boolean + * + *
+   * T
+   * F
+   * 
+ */ + public boolean readBoolean() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'T': return true; + case 'F': return false; + case 'I': return parseInt() == 0; + case 'L': return parseLong() == 0; + case 'D': return parseDouble() == 0.0; + case 'N': return false; + + default: + throw expect("boolean", tag); + } + } + + /** + * Reads a byte + * + *
+   * I b32 b24 b16 b8
+   * 
+ */ + /* + public byte readByte() + throws IOException + { + return (byte) readInt(); + } + */ + + /** + * Reads a short + * + *
+   * I b32 b24 b16 b8
+   * 
+ */ + public short readShort() + throws IOException + { + return (short) readInt(); + } + + /** + * Reads an integer + * + *
+   * I b32 b24 b16 b8
+   * 
+ */ + public int readInt() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'T': return 1; + case 'F': return 0; + case 'I': return parseInt(); + case 'L': return (int) parseLong(); + case 'D': return (int) parseDouble(); + + default: + throw expect("int", tag); + } + } + + /** + * Reads a long + * + *
+   * L b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + public long readLong() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'T': return 1; + case 'F': return 0; + case 'I': return parseInt(); + case 'L': return parseLong(); + case 'D': return (long) parseDouble(); + + default: + throw expect("long", tag); + } + } + + /** + * Reads a float + * + *
+   * D b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + public float readFloat() + throws IOException + { + return (float) readDouble(); + } + + /** + * Reads a double + * + *
+   * D b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + public double readDouble() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'T': return 1; + case 'F': return 0; + case 'I': return parseInt(); + case 'L': return (double) parseLong(); + case 'D': return parseDouble(); + + default: + throw expect("long", tag); + } + } + + /** + * Reads a date. + * + *
+   * T b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + public long readUTCDate() + throws IOException + { + int tag = read(); + + if (tag != 'd') + throw error("expected date at " + codeName(tag)); + + long b64 = read(); + long b56 = read(); + long b48 = read(); + long b40 = read(); + long b32 = read(); + long b24 = read(); + long b16 = read(); + long b8 = read(); + + return ((b64 << 56) + + (b56 << 48) + + (b48 << 40) + + (b40 << 32) + + (b32 << 24) + + (b24 << 16) + + (b16 << 8) + + b8); + } + + /** + * Reads a byte from the stream. + */ + public int readChar() + throws IOException + { + if (_chunkLength > 0) { + _chunkLength--; + if (_chunkLength == 0 && _isLastChunk) + _chunkLength = END_OF_DATA; + + int ch = parseUTF8Char(); + return ch; + } + else if (_chunkLength == END_OF_DATA) { + _chunkLength = 0; + return -1; + } + + int tag = read(); + + switch (tag) { + case 'N': + return -1; + + case 'S': + case 's': + case 'X': + case 'x': + _isLastChunk = tag == 'S' || tag == 'X'; + _chunkLength = (read() << 8) + read(); + + _chunkLength--; + int value = parseUTF8Char(); + + // special code so successive read byte won't + // be read as a single object. + if (_chunkLength == 0 && _isLastChunk) + _chunkLength = END_OF_DATA; + + return value; + + default: + throw new IOException("expected 'S' at " + (char) tag); + } + } + + /** + * Reads a byte array from the stream. + */ + public int readString(char []buffer, int offset, int length) + throws IOException + { + int readLength = 0; + + if (_chunkLength == END_OF_DATA) { + _chunkLength = 0; + return -1; + } + else if (_chunkLength == 0) { + int tag = read(); + + switch (tag) { + case 'N': + return -1; + + case 'S': + case 's': + case 'X': + case 'x': + _isLastChunk = tag == 'S' || tag == 'X'; + _chunkLength = (read() << 8) + read(); + break; + + default: + throw new IOException("expected 'S' at " + (char) tag); + } + } + + while (length > 0) { + if (_chunkLength > 0) { + buffer[offset++] = (char) parseUTF8Char(); + _chunkLength--; + length--; + readLength++; + } + else if (_isLastChunk) { + if (readLength == 0) + return -1; + else { + _chunkLength = END_OF_DATA; + return readLength; + } + } + else { + int tag = read(); + + switch (tag) { + case 'S': + case 's': + case 'X': + case 'x': + _isLastChunk = tag == 'S' || tag == 'X'; + _chunkLength = (read() << 8) + read(); + break; + + default: + throw new IOException("expected 'S' at " + (char) tag); + } + } + } + + if (readLength == 0) + return -1; + else if (_chunkLength > 0 || ! _isLastChunk) + return readLength; + else { + _chunkLength = END_OF_DATA; + return readLength; + } + } + + /** + * Reads a string + * + *
+   * S b16 b8 string value
+   * 
+ */ + public String readString() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': + return null; + + case 'I': + return String.valueOf(parseInt()); + case 'L': + return String.valueOf(parseLong()); + case 'D': + return String.valueOf(parseDouble()); + + case 'S': + case 's': + case 'X': + case 'x': + _isLastChunk = tag == 'S' || tag == 'X'; + _chunkLength = (read() << 8) + read(); + + _sbuf.setLength(0); + int ch; + + while ((ch = parseChar()) >= 0) + _sbuf.append((char) ch); + + return _sbuf.toString(); + + default: + throw expect("string", tag); + } + } + + /** + * Reads an XML node. + * + *
+   * S b16 b8 string value
+   * 
+ */ + public org.w3c.dom.Node readNode() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': + return null; + + case 'S': + case 's': + case 'X': + case 'x': + _isLastChunk = tag == 'S' || tag == 'X'; + _chunkLength = (read() << 8) + read(); + + throw error("Can't handle string in this context"); + + default: + throw expect("string", tag); + } + } + + /** + * Reads a byte array + * + *
+   * B b16 b8 data value
+   * 
+ */ + public byte []readBytes() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': + return null; + + case 'B': + case 'b': + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + int data; + while ((data = parseByte()) >= 0) + bos.write(data); + + return bos.toByteArray(); + + default: + throw expect("bytes", tag); + } + } + + /** + * Reads a byte from the stream. + */ + public int readByte() + throws IOException + { + if (_chunkLength > 0) { + _chunkLength--; + if (_chunkLength == 0 && _isLastChunk) + _chunkLength = END_OF_DATA; + + return read(); + } + else if (_chunkLength == END_OF_DATA) { + _chunkLength = 0; + return -1; + } + + int tag = read(); + + switch (tag) { + case 'N': + return -1; + + case 'B': + case 'b': + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + + int value = parseByte(); + + // special code so successive read byte won't + // be read as a single object. + if (_chunkLength == 0 && _isLastChunk) + _chunkLength = END_OF_DATA; + + return value; + + default: + throw new IOException("expected 'B' at " + (char) tag); + } + } + + /** + * Reads a byte array from the stream. + */ + public int readBytes(byte []buffer, int offset, int length) + throws IOException + { + int readLength = 0; + + if (_chunkLength == END_OF_DATA) { + _chunkLength = 0; + return -1; + } + else if (_chunkLength == 0) { + int tag = read(); + + switch (tag) { + case 'N': + return -1; + + case 'B': + case 'b': + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + break; + + default: + throw new IOException("expected 'B' at " + (char) tag); + } + } + + while (length > 0) { + if (_chunkLength > 0) { + buffer[offset++] = (byte) read(); + _chunkLength--; + length--; + readLength++; + } + else if (_isLastChunk) { + if (readLength == 0) + return -1; + else { + _chunkLength = END_OF_DATA; + return readLength; + } + } + else { + int tag = read(); + + switch (tag) { + case 'B': + case 'b': + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + break; + + default: + throw new IOException("expected 'B' at " + (char) tag); + } + } + } + + if (readLength == 0) + return -1; + else if (_chunkLength > 0 || ! _isLastChunk) + return readLength; + else { + _chunkLength = END_OF_DATA; + return readLength; + } + } + + /** + * Reads a fault. + */ + private HashMap readFault() + throws IOException + { + HashMap map = new HashMap(); + + int code = read(); + for (; code > 0 && code != 'z'; code = read()) { + _peek = code; + + Object key = readObject(); + Object value = readObject(); + + if (key != null && value != null) + map.put(key, value); + } + + if (code != 'z') + throw expect("fault", code); + + return map; + } + + /** + * Reads an object from the input stream with an expected type. + */ + public Object readObject(Class cl) + throws IOException + { + if (cl == null || cl == Object.class) + return readObject(); + + int tag = read(); + + switch (tag) { + case 'N': + return null; + + case 'M': + { + String type = readType(); + + // hessian/3386 + if ("".equals(type)) { + Deserializer reader; + reader = _serializerFactory.getDeserializer(cl); + + return reader.readMap(this); + } + else { + Deserializer reader; + reader = _serializerFactory.getObjectDeserializer(type,cl); + + return reader.readMap(this); + } + } + + case 'V': + { + String type = readType(); + int length = readLength(); + + Deserializer reader; + reader = _serializerFactory.getObjectDeserializer(type); + + if (cl != reader.getType() && cl.isAssignableFrom(reader.getType())) + return reader.readList(this, length); + + reader = _serializerFactory.getDeserializer(cl); + + Object v = reader.readList(this, length); + + return v; + } + + case 'R': + { + int ref = parseInt(); + + return _refs.get(ref); + } + + case 'r': + { + String type = readType(); + String url = readString(); + + return resolveRemote(type, url); + } + } + + _peek = tag; + + // hessian/332i vs hessian/3406 + //return readObject(); + + Object value = _serializerFactory.getDeserializer(cl).readObject(this); + + return value; + } + + /** + * Reads an arbitrary object from the input stream when the type + * is unknown. + */ + public Object readObject() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': + return null; + + case 'T': + return Boolean.valueOf(true); + + case 'F': + return Boolean.valueOf(false); + + case 'I': + return Integer.valueOf(parseInt()); + + case 'L': + return Long.valueOf(parseLong()); + + case 'D': + return Double.valueOf(parseDouble()); + + case 'd': + return new Date(parseLong()); + + case 'x': + case 'X': { + _isLastChunk = tag == 'X'; + _chunkLength = (read() << 8) + read(); + + return parseXML(); + } + + case 's': + case 'S': { + _isLastChunk = tag == 'S'; + _chunkLength = (read() << 8) + read(); + + int data; + _sbuf.setLength(0); + + while ((data = parseChar()) >= 0) + _sbuf.append((char) data); + + return _sbuf.toString(); + } + + case 'b': + case 'B': { + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + + int data; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + while ((data = parseByte()) >= 0) + bos.write(data); + + return bos.toByteArray(); + } + + case 'V': { + String type = readType(); + int length = readLength(); + + return _serializerFactory.readList(this, length, type); + } + + case 'M': { + String type = readType(); + + return _serializerFactory.readMap(this, type); + } + + case 'R': { + int ref = parseInt(); + + return _refs.get(ref); + } + + case 'r': { + String type = readType(); + String url = readString(); + + return resolveRemote(type, url); + } + + default: + throw error("unknown code for readObject at " + codeName(tag)); + } + } + + /** + * Reads a remote object. + */ + public Object readRemote() + throws IOException + { + String type = readType(); + String url = readString(); + + return resolveRemote(type, url); + } + + /** + * Reads a reference. + */ + public Object readRef() + throws IOException + { + return _refs.get(parseInt()); + } + + /** + * Reads the start of a list. + */ + public int readListStart() + throws IOException + { + return read(); + } + + /** + * Reads the start of a list. + */ + public int readMapStart() + throws IOException + { + return read(); + } + + /** + * Returns true if this is the end of a list or a map. + */ + public boolean isEnd() + throws IOException + { + int code = read(); + + _peek = code; + + return (code < 0 || code == 'z'); + } + + /** + * Reads the end byte. + */ + public void readEnd() + throws IOException + { + int code = read(); + + if (code != 'z') + throw error("unknown code at " + codeName(code)); + } + + /** + * Reads the end byte. + */ + public void readMapEnd() + throws IOException + { + int code = read(); + + if (code != 'z') + throw error("expected end of map ('z') at " + codeName(code)); + } + + /** + * Reads the end byte. + */ + public void readListEnd() + throws IOException + { + int code = read(); + + if (code != 'z') + throw error("expected end of list ('z') at " + codeName(code)); + } + + /** + * Adds a list/map reference. + */ + public int addRef(Object ref) + { + if (_refs == null) + _refs = new ArrayList(); + + _refs.add(ref); + + return _refs.size() - 1; + } + + /** + * Adds a list/map reference. + */ + public void setRef(int i, Object ref) + { + _refs.set(i, ref); + } + + /** + * Resets the references for streaming. + */ + public void resetReferences() + { + if (_refs != null) + _refs.clear(); + } + + /** + * Resolves a remote object. + */ + public Object resolveRemote(String type, String url) + throws IOException + { + HessianRemoteResolver resolver = getRemoteResolver(); + + if (resolver != null) + return resolver.lookup(type, url); + else + return new HessianRemote(type, url); + } + + /** + * Parses a type from the stream. + * + *
+   * t b16 b8
+   * 
+ */ + public String readType() + throws IOException + { + int code = read(); + + if (code != 't') { + _peek = code; + return ""; + } + + _isLastChunk = true; + _chunkLength = (read() << 8) + read(); + + _sbuf.setLength(0); + int ch; + while ((ch = parseChar()) >= 0) + _sbuf.append((char) ch); + + return _sbuf.toString(); + } + + /** + * Parses the length for an array + * + *
+   * l b32 b24 b16 b8
+   * 
+ */ + public int readLength() + throws IOException + { + int code = read(); + + if (code != 'l') { + _peek = code; + return -1; + } + + return parseInt(); + } + + /** + * Parses a 32-bit integer value from the stream. + * + *
+   * b32 b24 b16 b8
+   * 
+ */ + private int parseInt() + throws IOException + { + int b32 = read(); + int b24 = read(); + int b16 = read(); + int b8 = read(); + + return (b32 << 24) + (b24 << 16) + (b16 << 8) + b8; + } + + /** + * Parses a 64-bit long value from the stream. + * + *
+   * b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + private long parseLong() + throws IOException + { + long b64 = read(); + long b56 = read(); + long b48 = read(); + long b40 = read(); + long b32 = read(); + long b24 = read(); + long b16 = read(); + long b8 = read(); + + return ((b64 << 56) + + (b56 << 48) + + (b48 << 40) + + (b40 << 32) + + (b32 << 24) + + (b24 << 16) + + (b16 << 8) + + b8); + } + + /** + * Parses a 64-bit double value from the stream. + * + *
+   * b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ */ + private double parseDouble() + throws IOException + { + long b64 = read(); + long b56 = read(); + long b48 = read(); + long b40 = read(); + long b32 = read(); + long b24 = read(); + long b16 = read(); + long b8 = read(); + + long bits = ((b64 << 56) + + (b56 << 48) + + (b48 << 40) + + (b40 << 32) + + (b32 << 24) + + (b24 << 16) + + (b16 << 8) + + b8); + + return Double.longBitsToDouble(bits); + } + + org.w3c.dom.Node parseXML() + throws IOException + { + throw new UnsupportedOperationException(); + } + + /** + * Reads a character from the underlying stream. + */ + private int parseChar() + throws IOException + { + while (_chunkLength <= 0) { + if (_isLastChunk) + return -1; + + int code = read(); + + switch (code) { + case 's': + case 'x': + _isLastChunk = false; + + _chunkLength = (read() << 8) + read(); + break; + + case 'S': + case 'X': + _isLastChunk = true; + + _chunkLength = (read() << 8) + read(); + break; + + default: + throw expect("string", code); + } + + } + + _chunkLength--; + + return parseUTF8Char(); + } + + /** + * Parses a single UTF8 character. + */ + private int parseUTF8Char() + throws IOException + { + int ch = read(); + + if (ch < 0x80) + return ch; + else if ((ch & 0xe0) == 0xc0) { + int ch1 = read(); + int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); + + return v; + } + else if ((ch & 0xf0) == 0xe0) { + int ch1 = read(); + int ch2 = read(); + int v = ((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f); + + return v; + } + else + throw error("bad utf-8 encoding at " + codeName(ch)); + } + + /** + * Reads a byte from the underlying stream. + */ + private int parseByte() + throws IOException + { + while (_chunkLength <= 0) { + if (_isLastChunk) { + return -1; + } + + int code = read(); + + switch (code) { + case 'b': + _isLastChunk = false; + + _chunkLength = (read() << 8) + read(); + break; + + case 'B': + _isLastChunk = true; + + _chunkLength = (read() << 8) + read(); + break; + + default: + throw expect("byte[]", code); + } + } + + _chunkLength--; + + return read(); + } + + /** + * Reads bytes based on an input stream. + */ + public InputStream readInputStream() + throws IOException + { + int tag = read(); + + switch (tag) { + case 'N': + return null; + + case 'B': + case 'b': + _isLastChunk = tag == 'B'; + _chunkLength = (read() << 8) + read(); + break; + + default: + throw expect("inputStream", tag); + } + + return new InputStream() { + boolean _isClosed = false; + + public int read() + throws IOException + { + if (_isClosed || _is == null) + return -1; + + int ch = parseByte(); + if (ch < 0) + _isClosed = true; + + return ch; + } + + public int read(byte []buffer, int offset, int length) + throws IOException + { + if (_isClosed || _is == null) + return -1; + + int len = HessianInput.this.read(buffer, offset, length); + if (len < 0) + _isClosed = true; + + return len; + } + + public void close() + throws IOException + { + while (read() >= 0) { + } + + _isClosed = true; + } + }; + } + + /** + * Reads bytes from the underlying stream. + */ + int read(byte []buffer, int offset, int length) + throws IOException + { + int readLength = 0; + + while (length > 0) { + while (_chunkLength <= 0) { + if (_isLastChunk) + return readLength == 0 ? -1 : readLength; + + int code = read(); + + switch (code) { + case 'b': + _isLastChunk = false; + + _chunkLength = (read() << 8) + read(); + break; + + case 'B': + _isLastChunk = true; + + _chunkLength = (read() << 8) + read(); + break; + + default: + throw expect("byte[]", code); + } + } + + int sublen = _chunkLength; + if (length < sublen) + sublen = length; + + sublen = _is.read(buffer, offset, sublen); + offset += sublen; + readLength += sublen; + length -= sublen; + _chunkLength -= sublen; + } + + return readLength; + } + + final int read() + throws IOException + { + if (_peek >= 0) { + int value = _peek; + _peek = -1; + return value; + } + + int ch = _is.read(); + + return ch; + } + + public void close() + { + _is = null; + } + + public Reader getReader() + { + return null; + } + + protected IOException expect(String expect, int ch) + { + return error("expected " + expect + " at " + codeName(ch)); + } + + protected String codeName(int ch) + { + if (ch < 0) + return "end of file"; + else + return "0x" + Integer.toHexString(ch & 0xff) + " (" + (char) + ch + ")"; + } + + protected IOException error(String message) + { + if (_method != null) + return new HessianProtocolException(_method + ": " + message); + else + return new HessianProtocolException(message); + } + + static { + try { + _detailMessageField = Throwable.class.getDeclaredField("detailMessage"); + _detailMessageField.setAccessible(true); + } catch (Throwable e) { + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianInputFactory.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianInputFactory.java new file mode 100644 index 000000000000..d5a24d1fd1cf --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianInputFactory.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.util.logging.*; +import java.io.*; + +public class HessianInputFactory +{ + public static final Logger log + = Logger.getLogger(HessianInputFactory.class.getName()); + + private SerializerFactory _serializerFactory; + + public void setSerializerFactory(SerializerFactory factory) + { + _serializerFactory = factory; + } + + public SerializerFactory getSerializerFactory() + { + return _serializerFactory; + } + + public AbstractHessianInput open(InputStream is) + throws IOException + { + int code = is.read(); + + int major = is.read(); + int minor = is.read(); + + switch (code) { + case 'c': + case 'C': + case 'r': + case 'R': + if (major >= 2) { + AbstractHessianInput in = new Hessian2Input(is); + in.setSerializerFactory(_serializerFactory); + return in; + } + else { + AbstractHessianInput in = new HessianInput(is); + in.setSerializerFactory(_serializerFactory); + return in; + } + + default: + throw new IOException((char) code + " is an unknown Hessian message code."); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianOutput.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianOutput.java new file mode 100644 index 000000000000..6807f3db0f5c --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianOutput.java @@ -0,0 +1,949 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.IdentityHashMap; + +/** + * Output stream for Hessian requests, compatible with microedition + * Java. It only uses classes and types available in JDK. + * + *

Since HessianOutput does not depend on any classes other than + * in the JDK, it can be extracted independently into a smaller package. + * + *

HessianOutput is unbuffered, so any client needs to provide + * its own buffering. + * + *

+ * OutputStream os = ...; // from http connection
+ * HessianOutput out = new HessianOutput(os);
+ * String value;
+ *
+ * out.startCall("hello");  // start hello call
+ * out.writeString("arg1"); // write a string argument
+ * out.completeCall();      // complete the call
+ * 
+ */ +public class HessianOutput extends AbstractHessianOutput { + // the output stream/ + protected OutputStream os; + // map of references + private IdentityHashMap _refs; + private int _version = 1; + + /** + * Creates a new Hessian output stream, initialized with an + * underlying output stream. + * + * @param os the underlying output stream. + */ + public HessianOutput(OutputStream os) + { + init(os); + } + + /** + * Creates an uninitialized Hessian output stream. + */ + public HessianOutput() + { + } + + /** + * Initializes the output + */ + public void init(OutputStream os) + { + this.os = os; + + _refs = null; + + if (_serializerFactory == null) + _serializerFactory = new SerializerFactory(); + } + + /** + * Sets the client's version. + */ + public void setVersion(int version) + { + _version = version; + } + + /** + * Writes a complete method call. + */ + public void call(String method, Object []args) + throws IOException + { + int length = args != null ? args.length : 0; + + startCall(method, length); + + for (int i = 0; i < length; i++) + writeObject(args[i]); + + completeCall(); + } + + /** + * Starts the method call. Clients would use startCall + * instead of call if they wanted finer control over + * writing the arguments, or needed to write headers. + * + *
+   * c major minor
+   * m b16 b8 method-name
+   * 
+ * + * @param method the method name to call. + */ + public void startCall(String method, int length) + throws IOException + { + os.write('c'); + os.write(_version); + os.write(0); + + os.write('m'); + int len = method.length(); + os.write(len >> 8); + os.write(len); + printString(method, 0, len); + } + + /** + * Writes the call tag. This would be followed by the + * headers and the method tag. + * + *
+   * c major minor
+   * 
+ * + * @param method the method name to call. + */ + public void startCall() + throws IOException + { + os.write('c'); + os.write(0); + os.write(1); + } + + /** + * Writes the method tag. + * + *
+   * m b16 b8 method-name
+   * 
+ * + * @param method the method name to call. + */ + public void writeMethod(String method) + throws IOException + { + os.write('m'); + int len = method.length(); + os.write(len >> 8); + os.write(len); + printString(method, 0, len); + } + + /** + * Completes. + * + *
+   * z
+   * 
+ */ + public void completeCall() + throws IOException + { + os.write('z'); + } + + /** + * Starts the reply + * + *

A successful completion will have a single value: + * + *

+   * r
+   * 
+ */ + public void startReply() + throws IOException + { + os.write('r'); + os.write(1); + os.write(0); + } + + /** + * Completes reading the reply + * + *

A successful completion will have a single value: + * + *

+   * z
+   * 
+ */ + public void completeReply() + throws IOException + { + os.write('z'); + } + + /** + * Writes a header name. The header value must immediately follow. + * + *
+   * H b16 b8 foo value
+   * 
+ */ + public void writeHeader(String name) + throws IOException + { + int len = name.length(); + + os.write('H'); + os.write(len >> 8); + os.write(len); + + printString(name); + } + + /** + * Writes a fault. The fault will be written + * as a descriptive string followed by an object: + * + *
+   * f
+   * <string>code
+   * <string>the fault code
+   *
+   * <string>message
+   * <string>the fault mesage
+   *
+   * <string>detail
+   * mt\x00\xnnjavax.ejb.FinderException
+   *     ...
+   * z
+   * z
+   * 
+ * + * @param code the fault code, a three digit + */ + public void writeFault(String code, String message, Object detail) + throws IOException + { + os.write('f'); + writeString("code"); + writeString(code); + + writeString("message"); + writeString(message); + + if (detail != null) { + writeString("detail"); + writeObject(detail); + } + os.write('z'); + } + + /** + * Writes any object to the output stream. + */ + public void writeObject(Object object) + throws IOException + { + if (object == null) { + writeNull(); + return; + } + + Serializer serializer; + + serializer = _serializerFactory.getSerializer(object.getClass()); + + serializer.writeObject(object, this); + } + + /** + * Writes the list header to the stream. List writers will call + * writeListBegin followed by the list contents and then + * call writeListEnd. + * + *
+   * V
+   * t b16 b8 type
+   * l b32 b24 b16 b8
+   * 
+ */ + public boolean writeListBegin(int length, String type) + throws IOException + { + os.write('V'); + + if (type != null) { + os.write('t'); + printLenString(type); + } + + if (length >= 0) { + os.write('l'); + os.write(length >> 24); + os.write(length >> 16); + os.write(length >> 8); + os.write(length); + } + + return true; + } + + /** + * Writes the tail of the list to the stream. + */ + public void writeListEnd() + throws IOException + { + os.write('z'); + } + + /** + * Writes the map header to the stream. Map writers will call + * writeMapBegin followed by the map contents and then + * call writeMapEnd. + * + *
+   * Mt b16 b8 ( )z
+   * 
+ */ + public void writeMapBegin(String type) + throws IOException + { + os.write('M'); + os.write('t'); + printLenString(type); + } + + /** + * Writes the tail of the map to the stream. + */ + public void writeMapEnd() + throws IOException + { + os.write('z'); + } + + /** + * Writes a remote object reference to the stream. The type is the + * type of the remote interface. + * + *
+   * 'r' 't' b16 b8 type url
+   * 
+ */ + public void writeRemote(String type, String url) + throws IOException + { + os.write('r'); + os.write('t'); + printLenString(type); + os.write('S'); + printLenString(url); + } + + /** + * Writes a boolean value to the stream. The boolean will be written + * with the following syntax: + * + *
+   * T
+   * F
+   * 
+ * + * @param value the boolean value to write. + */ + public void writeBoolean(boolean value) + throws IOException + { + if (value) + os.write('T'); + else + os.write('F'); + } + + /** + * Writes an integer value to the stream. The integer will be written + * with the following syntax: + * + *
+   * I b32 b24 b16 b8
+   * 
+ * + * @param value the integer value to write. + */ + public void writeInt(int value) + throws IOException + { + os.write('I'); + os.write(value >> 24); + os.write(value >> 16); + os.write(value >> 8); + os.write(value); + } + + /** + * Writes a long value to the stream. The long will be written + * with the following syntax: + * + *
+   * L b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ * + * @param value the long value to write. + */ + public void writeLong(long value) + throws IOException + { + os.write('L'); + os.write((byte) (value >> 56)); + os.write((byte) (value >> 48)); + os.write((byte) (value >> 40)); + os.write((byte) (value >> 32)); + os.write((byte) (value >> 24)); + os.write((byte) (value >> 16)); + os.write((byte) (value >> 8)); + os.write((byte) (value)); + } + + /** + * Writes a double value to the stream. The double will be written + * with the following syntax: + * + *
+   * D b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ * + * @param value the double value to write. + */ + public void writeDouble(double value) + throws IOException + { + long bits = Double.doubleToLongBits(value); + + os.write('D'); + os.write((byte) (bits >> 56)); + os.write((byte) (bits >> 48)); + os.write((byte) (bits >> 40)); + os.write((byte) (bits >> 32)); + os.write((byte) (bits >> 24)); + os.write((byte) (bits >> 16)); + os.write((byte) (bits >> 8)); + os.write((byte) (bits)); + } + + /** + * Writes a date to the stream. + * + *
+   * T  b64 b56 b48 b40 b32 b24 b16 b8
+   * 
+ * + * @param time the date in milliseconds from the epoch in UTC + */ + public void writeUTCDate(long time) + throws IOException + { + os.write('d'); + os.write((byte) (time >> 56)); + os.write((byte) (time >> 48)); + os.write((byte) (time >> 40)); + os.write((byte) (time >> 32)); + os.write((byte) (time >> 24)); + os.write((byte) (time >> 16)); + os.write((byte) (time >> 8)); + os.write((byte) (time)); + } + + /** + * Writes a null value to the stream. + * The null will be written with the following syntax + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + public void writeNull() + throws IOException + { + os.write('N'); + } + + /** + * Writes a string value to the stream using UTF-8 encoding. + * The string will be written with the following syntax: + * + *
+   * S b16 b8 string-value
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + public void writeString(String value) + throws IOException + { + if (value == null) { + os.write('N'); + } + else { + int length = value.length(); + int offset = 0; + + while (length > 0x8000) { + int sublen = 0x8000; + + // chunk can't end in high surrogate + char tail = value.charAt(offset + sublen - 1); + + if (0xd800 <= tail && tail <= 0xdbff) + sublen--; + + os.write('s'); + os.write(sublen >> 8); + os.write(sublen); + + printString(value, offset, sublen); + + length -= sublen; + offset += sublen; + } + + os.write('S'); + os.write(length >> 8); + os.write(length); + + printString(value, offset, length); + } + } + + /** + * Writes a string value to the stream using UTF-8 encoding. + * The string will be written with the following syntax: + * + *
+   * S b16 b8 string-value
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + public void writeString(char []buffer, int offset, int length) + throws IOException + { + if (buffer == null) { + os.write('N'); + } + else { + while (length > 0x8000) { + int sublen = 0x8000; + + // chunk can't end in high surrogate + char tail = buffer[offset + sublen - 1]; + + if (0xd800 <= tail && tail <= 0xdbff) + sublen--; + + os.write('s'); + os.write(sublen >> 8); + os.write(sublen); + + printString(buffer, offset, sublen); + + length -= sublen; + offset += sublen; + } + + os.write('S'); + os.write(length >> 8); + os.write(length); + + printString(buffer, offset, length); + } + } + + /** + * Writes a byte array to the stream. + * The array will be written with the following syntax: + * + *
+   * B b16 b18 bytes
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + public void writeBytes(byte []buffer) + throws IOException + { + if (buffer == null) + os.write('N'); + else + writeBytes(buffer, 0, buffer.length); + } + + /** + * Writes a byte array to the stream. + * The array will be written with the following syntax: + * + *
+   * B b16 b18 bytes
+   * 
+ * + * If the value is null, it will be written as + * + *
+   * N
+   * 
+ * + * @param value the string value to write. + */ + public void writeBytes(byte []buffer, int offset, int length) + throws IOException + { + if (buffer == null) { + os.write('N'); + } + else { + while (length > 0x8000) { + int sublen = 0x8000; + + os.write('b'); + os.write(sublen >> 8); + os.write(sublen); + + os.write(buffer, offset, sublen); + + length -= sublen; + offset += sublen; + } + + os.write('B'); + os.write(length >> 8); + os.write(length); + os.write(buffer, offset, length); + } + } + + /** + * Writes a byte buffer to the stream. + * + *
+   * 
+ */ + public void writeByteBufferStart() + throws IOException + { + } + + /** + * Writes a byte buffer to the stream. + * + *
+   * b b16 b18 bytes
+   * 
+ */ + public void writeByteBufferPart(byte []buffer, int offset, int length) + throws IOException + { + while (length > 0) { + int sublen = length; + + if (0x8000 < sublen) + sublen = 0x8000; + + os.write('b'); + os.write(sublen >> 8); + os.write(sublen); + + os.write(buffer, offset, sublen); + + length -= sublen; + offset += sublen; + } + } + + /** + * Writes a byte buffer to the stream. + * + *
+   * b b16 b18 bytes
+   * 
+ */ + public void writeByteBufferEnd(byte []buffer, int offset, int length) + throws IOException + { + writeBytes(buffer, offset, length); + } + + /** + * Writes a reference. + * + *
+   * R b32 b24 b16 b8
+   * 
+ * + * @param value the integer value to write. + */ + public void writeRef(int value) + throws IOException + { + os.write('R'); + os.write(value >> 24); + os.write(value >> 16); + os.write(value >> 8); + os.write(value); + } + + /** + * Writes a placeholder. + * + *
+   * P
+   * 
+ */ + public void writePlaceholder() + throws IOException + { + os.write('P'); + } + + /** + * If the object has already been written, just write its ref. + * + * @return true if we're writing a ref. + */ + public boolean addRef(Object object) + throws IOException + { + if (_refs == null) + _refs = new IdentityHashMap(); + + Integer ref = (Integer) _refs.get(object); + + if (ref != null) { + int value = ref.intValue(); + + writeRef(value); + return true; + } + else { + _refs.put(object, new Integer(_refs.size())); + + return false; + } + } + + /** + * Resets the references for streaming. + */ + public void resetReferences() + { + if (_refs != null) + _refs.clear(); + } + + /** + * Removes a reference. + */ + public boolean removeRef(Object obj) + throws IOException + { + if (_refs != null) { + _refs.remove(obj); + + return true; + } + else + return false; + } + + /** + * Replaces a reference from one object to another. + */ + public boolean replaceRef(Object oldRef, Object newRef) + throws IOException + { + Integer value = (Integer) _refs.remove(oldRef); + + if (value != null) { + _refs.put(newRef, value); + return true; + } + else + return false; + } + + /** + * Prints a string to the stream, encoded as UTF-8 with preceeding length + * + * @param v the string to print. + */ + public void printLenString(String v) + throws IOException + { + if (v == null) { + os.write(0); + os.write(0); + } + else { + int len = v.length(); + os.write(len >> 8); + os.write(len); + + printString(v, 0, len); + } + } + + /** + * Prints a string to the stream, encoded as UTF-8 + * + * @param v the string to print. + */ + public void printString(String v) + throws IOException + { + printString(v, 0, v.length()); + } + + /** + * Prints a string to the stream, encoded as UTF-8 + * + * @param v the string to print. + */ + public void printString(String v, int offset, int length) + throws IOException + { + for (int i = 0; i < length; i++) { + char ch = v.charAt(i + offset); + + if (ch < 0x80) + os.write(ch); + else if (ch < 0x800) { + os.write(0xc0 + ((ch >> 6) & 0x1f)); + os.write(0x80 + (ch & 0x3f)); + } + else { + os.write(0xe0 + ((ch >> 12) & 0xf)); + os.write(0x80 + ((ch >> 6) & 0x3f)); + os.write(0x80 + (ch & 0x3f)); + } + } + } + + /** + * Prints a string to the stream, encoded as UTF-8 + * + * @param v the string to print. + */ + public void printString(char []v, int offset, int length) + throws IOException + { + for (int i = 0; i < length; i++) { + char ch = v[i + offset]; + + if (ch < 0x80) + os.write(ch); + else if (ch < 0x800) { + os.write(0xc0 + ((ch >> 6) & 0x1f)); + os.write(0x80 + (ch & 0x3f)); + } + else { + os.write(0xe0 + ((ch >> 12) & 0xf)); + os.write(0x80 + ((ch >> 6) & 0x3f)); + os.write(0x80 + (ch & 0x3f)); + } + } + } + + public void flush() + throws IOException + { + if (this.os != null) + this.os.flush(); + } + + public void close() + throws IOException + { + if (this.os != null) + this.os.flush(); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianProtocolException.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianProtocolException.java new file mode 100644 index 000000000000..e3f023e3edbe --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianProtocolException.java @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Exception for faults when the fault doesn't return a java exception. + * This exception is required for MicroHessianInput. + */ +public class HessianProtocolException extends IOException { + private Throwable rootCause; + + /** + * Zero-arg constructor. + */ + public HessianProtocolException() + { + } + + /** + * Create the exception. + */ + public HessianProtocolException(String message) + { + super(message); + } + + /** + * Create the exception. + */ + public HessianProtocolException(String message, Throwable rootCause) + { + super(message); + + this.rootCause = rootCause; + } + + /** + * Create the exception. + */ + public HessianProtocolException(Throwable rootCause) + { + super(String.valueOf(rootCause)); + + this.rootCause = rootCause; + } + + /** + * Returns the underlying cause. + */ + public Throwable getRootCause() + { + return rootCause; + } + + /** + * Returns the underlying cause. + */ + public Throwable getCause() + { + return getRootCause(); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemote.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemote.java new file mode 100644 index 000000000000..bef32aba9392 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemote.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +/** + * Encapsulates a remote address when no stub is available, e.g. for + * Java MicroEdition. + */ +public class HessianRemote { + private String type; + private String url; + + /** + * Creates a new Hessian remote object. + * + * @param type the remote stub interface + * @param url the remote url + */ + public HessianRemote(String type, String url) + { + this.type = type; + this.url = url; + } + + /** + * Creates an uninitialized Hessian remote. + */ + public HessianRemote() + { + } + + /** + * Returns the remote api class name. + */ + public String getType() + { + return type; + } + + /** + * Returns the remote URL. + */ + public String getURL() + { + return url; + } + + /** + * Sets the remote URL. + */ + public void setURL(String url) + { + this.url = url; + } + + /** + * Defines the hashcode. + */ + public int hashCode() + { + return url.hashCode(); + } + + /** + * Defines equality + */ + public boolean equals(Object obj) + { + if (! (obj instanceof HessianRemote)) + return false; + + HessianRemote remote = (HessianRemote) obj; + + return url.equals(remote.url); + } + + /** + * Readable version of the remote. + */ + public String toString() + { + return "[HessianRemote " + url + "]"; + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemoteObject.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemoteObject.java new file mode 100644 index 000000000000..d33f47de32bc --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemoteObject.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +/** + * Interface for any hessian remote object. + */ +public interface HessianRemoteObject { + public String getHessianType(); + public String getHessianURL(); +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemoteResolver.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemoteResolver.java new file mode 100644 index 000000000000..c14b0f1e1dc0 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianRemoteResolver.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Looks up remote objects. The default just returns a HessianRemote object. + */ +public interface HessianRemoteResolver { + /** + * Looks up a proxy object. + */ + public Object lookup(String type, String url) + throws IOException; +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianSerializerInput.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianSerializerInput.java new file mode 100644 index 000000000000..9651f1353e88 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianSerializerInput.java @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.HashMap; + +/** + * Input stream for Hessian requests, deserializing objects using the + * java.io.Serialization protocol. + * + *

HessianSerializerInput is unbuffered, so any client needs to provide + * its own buffering. + * + *

Serialization

+ * + *
+ * InputStream is = new FileInputStream("test.xml");
+ * HessianOutput in = new HessianSerializerOutput(is);
+ *
+ * Object obj = in.readObject();
+ * is.close();
+ * 
+ * + *

Parsing a Hessian reply

+ * + *
+ * InputStream is = ...; // from http connection
+ * HessianInput in = new HessianSerializerInput(is);
+ * String value;
+ *
+ * in.startReply();         // read reply header
+ * value = in.readString(); // read string value
+ * in.completeReply();      // read reply footer
+ * 
+ */ +public class HessianSerializerInput extends HessianInput { + /** + * Creates a new Hessian input stream, initialized with an + * underlying input stream. + * + * @param is the underlying input stream. + */ + public HessianSerializerInput(InputStream is) + { + super(is); + } + + /** + * Creates an uninitialized Hessian input stream. + */ + public HessianSerializerInput() + { + } + + /** + * Reads an object from the input stream. cl is known not to be + * a Map. + */ + protected Object readObjectImpl(Class cl) + throws IOException + { + try { + Object obj = cl.newInstance(); + + if (_refs == null) + _refs = new ArrayList(); + _refs.add(obj); + + HashMap fieldMap = getFieldMap(cl); + + int code = read(); + for (; code >= 0 && code != 'z'; code = read()) { + _peek = code; + + Object key = readObject(); + + Field field = (Field) fieldMap.get(key); + + if (field != null) { + Object value = readObject(field.getType()); + field.set(obj, value); + } + else { + Object value = readObject(); + } + } + + if (code != 'z') + throw expect("map", code); + + // if there's a readResolve method, call it + try { + Method method = cl.getMethod("readResolve", new Class[0]); + return method.invoke(obj, new Object[0]); + } catch (Exception e) { + } + + return obj; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOExceptionWrapper(e); + } + } + + /** + * Creates a map of the classes fields. + */ + protected HashMap getFieldMap(Class cl) + { + HashMap fieldMap = new HashMap(); + + for (; cl != null; cl = cl.getSuperclass()) { + Field []fields = cl.getDeclaredFields(); + for (int i = 0; i < fields.length; i++) { + Field field = fields[i]; + + if (Modifier.isTransient(field.getModifiers()) || + Modifier.isStatic(field.getModifiers())) + continue; + + // XXX: could parameterize the handler to only deal with public + field.setAccessible(true); + + fieldMap.put(field.getName(), field); + } + } + + return fieldMap; + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianSerializerOutput.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianSerializerOutput.java new file mode 100644 index 000000000000..5b570b33b54f --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianSerializerOutput.java @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +/** + * Output stream for Hessian requests. + * + *

HessianOutput is unbuffered, so any client needs to provide + * its own buffering. + * + *

Serialization

+ * + *
+ * OutputStream os = new FileOutputStream("test.xml");
+ * HessianOutput out = new HessianSerializerOutput(os);
+ *
+ * out.writeObject(obj);
+ * os.close();
+ * 
+ * + *

Writing an RPC Call

+ * + *
+ * OutputStream os = ...; // from http connection
+ * HessianOutput out = new HessianSerializerOutput(os);
+ * String value;
+ *
+ * out.startCall("hello");  // start hello call
+ * out.writeString("arg1"); // write a string argument
+ * out.completeCall();      // complete the call
+ * 
+ */ +public class HessianSerializerOutput extends HessianOutput { + /** + * Creates a new Hessian output stream, initialized with an + * underlying output stream. + * + * @param os the underlying output stream. + */ + public HessianSerializerOutput(OutputStream os) + { + super(os); + } + + /** + * Creates an uninitialized Hessian output stream. + */ + public HessianSerializerOutput() + { + } + + /** + * Applications which override this can do custom serialization. + * + * @param object the object to write. + */ + public void writeObjectImpl(Object obj) + throws IOException + { + Class cl = obj.getClass(); + + try { + Method method = cl.getMethod("writeReplace", new Class[0]); + Object repl = method.invoke(obj, new Object[0]); + + writeObject(repl); + return; + } catch (Exception e) { + } + + try { + writeMapBegin(cl.getName()); + for (; cl != null; cl = cl.getSuperclass()) { + Field []fields = cl.getDeclaredFields(); + for (int i = 0; i < fields.length; i++) { + Field field = fields[i]; + + if (Modifier.isTransient(field.getModifiers()) || + Modifier.isStatic(field.getModifiers())) + continue; + + // XXX: could parameterize the handler to only deal with public + field.setAccessible(true); + + writeString(field.getName()); + writeObject(field.get(obj)); + } + } + writeMapEnd(); + } catch (IllegalAccessException e) { + throw new IOExceptionWrapper(e); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianServiceException.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianServiceException.java new file mode 100644 index 000000000000..248e58f53234 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/HessianServiceException.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +/** + * Exception for faults when the fault doesn't return a java exception. + * This exception is required for MicroHessianInput. + */ +public class HessianServiceException extends Exception { + private String code; + private Object detail; + + /** + * Zero-arg constructor. + */ + public HessianServiceException() + { + } + + /** + * Create the exception. + */ + public HessianServiceException(String message, String code, Object detail) + { + super(message); + this.code = code; + this.detail = detail; + } + + /** + * Returns the code. + */ + public String getCode() + { + return code; + } + + /** + * Returns the detail. + */ + public Object getDetail() + { + return detail; + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/IOExceptionWrapper.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/IOExceptionWrapper.java new file mode 100644 index 000000000000..bee3cf531e16 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/IOExceptionWrapper.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Exception wrapper for IO. + */ +public class IOExceptionWrapper extends IOException { + private Throwable _cause; + + public IOExceptionWrapper(Throwable cause) + { + super(cause.toString()); + + _cause = cause; + } + + public IOExceptionWrapper(String msg, Throwable cause) + { + super(msg); + + _cause = cause; + } + + public Throwable getCause() + { + return _cause; + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/InputStreamDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/InputStreamDeserializer.java new file mode 100644 index 000000000000..d4247945507d --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/InputStreamDeserializer.java @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Serializing a stream object. + */ +public class InputStreamDeserializer extends AbstractDeserializer { + public InputStreamDeserializer() + { + } + + public Object readObject(AbstractHessianInput in) + throws IOException + { + return in.readInputStream(); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/InputStreamSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/InputStreamSerializer.java new file mode 100644 index 000000000000..9ac9d66cec7b --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/InputStreamSerializer.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.InputStream; + +/** + * Serializing a stream object. + */ +public class InputStreamSerializer extends AbstractSerializer { + public InputStreamSerializer() + { + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + InputStream is = (InputStream) obj; + + if (is == null) + out.writeNull(); + else { + byte []buf = new byte[1024]; + int len; + + while ((len = is.read(buf, 0, buf.length)) > 0) { + out.writeByteBufferPart(buf, 0, len); + } + + out.writeByteBufferEnd(buf, 0, 0); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/IteratorSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/IteratorSerializer.java new file mode 100644 index 000000000000..b3bff92379d1 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/IteratorSerializer.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.Iterator; + +/** + * Serializing a JDK 1.2 Iterator. + */ +public class IteratorSerializer extends AbstractSerializer { + private static IteratorSerializer _serializer; + + public static IteratorSerializer create() + { + if (_serializer == null) + _serializer = new IteratorSerializer(); + + return _serializer; + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + Iterator iter = (Iterator) obj; + + boolean hasEnd = out.writeListBegin(-1, null); + + while (iter.hasNext()) { + Object value = iter.next(); + + out.writeObject(value); + } + + if (hasEnd) + out.writeListEnd(); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/JavaDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/JavaDeserializer.java new file mode 100644 index 000000000000..bd217c4e2bcc --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/JavaDeserializer.java @@ -0,0 +1,679 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.HashMap; + +import java.util.logging.*; + +/** + * Serializing an object for known object types. + */ +public class JavaDeserializer extends AbstractMapDeserializer { + private static final Logger log + = Logger.getLogger(JavaDeserializer.class.getName()); + + private Class _type; + private HashMap _fieldMap; + private Method _readResolve; + private Constructor _constructor; + private Object []_constructorArgs; + + public JavaDeserializer(Class cl) + { + _type = cl; + _fieldMap = getFieldMap(cl); + + _readResolve = getReadResolve(cl); + + if (_readResolve != null) { + _readResolve.setAccessible(true); + } + + Constructor []constructors = cl.getDeclaredConstructors(); + long bestCost = Long.MAX_VALUE; + + for (int i = 0; i < constructors.length; i++) { + Class []param = constructors[i].getParameterTypes(); + long cost = 0; + + for (int j = 0; j < param.length; j++) { + cost = 4 * cost; + + if (Object.class.equals(param[j])) + cost += 1; + else if (String.class.equals(param[j])) + cost += 2; + else if (int.class.equals(param[j])) + cost += 3; + else if (long.class.equals(param[j])) + cost += 4; + else if (param[j].isPrimitive()) + cost += 5; + else + cost += 6; + } + + if (cost < 0 || cost > (1 << 48)) + cost = 1 << 48; + + cost += (long) param.length << 48; + + if (cost < bestCost) { + _constructor = constructors[i]; + bestCost = cost; + } + } + + if (_constructor != null) { + _constructor.setAccessible(true); + Class []params = _constructor.getParameterTypes(); + _constructorArgs = new Object[params.length]; + for (int i = 0; i < params.length; i++) { + _constructorArgs[i] = getParamArg(params[i]); + } + } + } + + public Class getType() + { + return _type; + } + + public Object readMap(AbstractHessianInput in) + throws IOException + { + try { + Object obj = instantiate(); + + return readMap(in, obj); + } catch (IOException e) { + throw e; + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new IOExceptionWrapper(_type.getName() + ":" + e.getMessage(), e); + } + } + + public Object readObject(AbstractHessianInput in, String []fieldNames) + throws IOException + { + try { + Object obj = instantiate(); + + return readObject(in, obj, fieldNames); + } catch (IOException e) { + throw e; + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new IOExceptionWrapper(_type.getName() + ":" + e.getMessage(), e); + } + } + + /** + * Returns the readResolve method + */ + protected Method getReadResolve(Class cl) + { + for (; cl != null; cl = cl.getSuperclass()) { + Method []methods = cl.getDeclaredMethods(); + + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + + if (method.getName().equals("readResolve") && + method.getParameterTypes().length == 0) + return method; + } + } + + return null; + } + + public Object readMap(AbstractHessianInput in, Object obj) + throws IOException + { + try { + int ref = in.addRef(obj); + + while (! in.isEnd()) { + Object key = in.readObject(); + + FieldDeserializer deser = (FieldDeserializer) _fieldMap.get(key); + + if (deser != null) + deser.deserialize(in, obj); + else + in.readObject(); + } + + in.readMapEnd(); + + Object resolve = resolve(obj); + + if (obj != resolve) + in.setRef(ref, resolve); + + return resolve; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOExceptionWrapper(e); + } + } + + public Object readObject(AbstractHessianInput in, + Object obj, + String []fieldNames) + throws IOException + { + try { + int ref = in.addRef(obj); + + for (int i = 0; i < fieldNames.length; i++) { + String name = fieldNames[i]; + + FieldDeserializer deser = (FieldDeserializer) _fieldMap.get(name); + + if (deser != null) + deser.deserialize(in, obj); + else + in.readObject(); + } + + Object resolve = resolve(obj); + + if (obj != resolve) + in.setRef(ref, resolve); + + return resolve; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOExceptionWrapper(obj.getClass().getName() + ":" + e, e); + } + } + + private Object resolve(Object obj) + throws Exception + { + // if there's a readResolve method, call it + try { + if (_readResolve != null) + return _readResolve.invoke(obj, new Object[0]); + } catch (InvocationTargetException e) { + if (e.getTargetException() != null) + throw e; + } + + return obj; + } + + protected Object instantiate() + throws Exception + { + try { + if (_constructor != null) + return _constructor.newInstance(_constructorArgs); + else + return _type.newInstance(); + } catch (Exception e) { + throw new HessianProtocolException("'" + _type.getName() + "' could not be instantiated", e); + } + } + + /** + * Creates a map of the classes fields. + */ + protected HashMap getFieldMap(Class cl) + { + HashMap fieldMap = new HashMap(); + + for (; cl != null; cl = cl.getSuperclass()) { + Field []fields = cl.getDeclaredFields(); + for (int i = 0; i < fields.length; i++) { + Field field = fields[i]; + + if (Modifier.isTransient(field.getModifiers()) + || Modifier.isStatic(field.getModifiers())) + continue; + else if (fieldMap.get(field.getName()) != null) + continue; + + // XXX: could parameterize the handler to only deal with public + try { + field.setAccessible(true); + } catch (Throwable e) { + e.printStackTrace(); + } + + Class type = field.getType(); + FieldDeserializer deser; + + if (String.class.equals(type)) + deser = new StringFieldDeserializer(field); + else if (byte.class.equals(type)) { + deser = new ByteFieldDeserializer(field); + } + else if (short.class.equals(type)) { + deser = new ShortFieldDeserializer(field); + } + else if (int.class.equals(type)) { + deser = new IntFieldDeserializer(field); + } + else if (long.class.equals(type)) { + deser = new LongFieldDeserializer(field); + } + else if (float.class.equals(type)) { + deser = new FloatFieldDeserializer(field); + } + else if (double.class.equals(type)) { + deser = new DoubleFieldDeserializer(field); + } + else if (boolean.class.equals(type)) { + deser = new BooleanFieldDeserializer(field); + } + else if (java.sql.Date.class.equals(type)) { + deser = new SqlDateFieldDeserializer(field); + } + else if (java.sql.Timestamp.class.equals(type)) { + deser = new SqlTimestampFieldDeserializer(field); + } + else if (java.sql.Time.class.equals(type)) { + deser = new SqlTimeFieldDeserializer(field); + } + else { + deser = new ObjectFieldDeserializer(field); + } + + fieldMap.put(field.getName(), deser); + } + } + + return fieldMap; + } + + /** + * Creates a map of the classes fields. + */ + protected static Object getParamArg(Class cl) + { + if (! cl.isPrimitive()) + return null; + else if (boolean.class.equals(cl)) + return Boolean.FALSE; + else if (byte.class.equals(cl)) + return new Byte((byte) 0); + else if (short.class.equals(cl)) + return new Short((short) 0); + else if (char.class.equals(cl)) + return new Character((char) 0); + else if (int.class.equals(cl)) + return Integer.valueOf(0); + else if (long.class.equals(cl)) + return Long.valueOf(0); + else if (float.class.equals(cl)) + return Float.valueOf(0); + else if (double.class.equals(cl)) + return Double.valueOf(0); + else + throw new UnsupportedOperationException(); + } + + abstract static class FieldDeserializer { + abstract void deserialize(AbstractHessianInput in, Object obj) + throws IOException; + } + + static class ObjectFieldDeserializer extends FieldDeserializer { + private final Field _field; + + ObjectFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + Object value = null; + + try { + value = in.readObject(_field.getType()); + + _field.set(obj, value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static class BooleanFieldDeserializer extends FieldDeserializer { + private final Field _field; + + BooleanFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + boolean value = false; + + try { + value = in.readBoolean(); + + _field.setBoolean(obj, value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static class ByteFieldDeserializer extends FieldDeserializer { + private final Field _field; + + ByteFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + int value = 0; + + try { + value = in.readInt(); + + _field.setByte(obj, (byte) value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static class ShortFieldDeserializer extends FieldDeserializer { + private final Field _field; + + ShortFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + int value = 0; + + try { + value = in.readInt(); + + _field.setShort(obj, (short) value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static class IntFieldDeserializer extends FieldDeserializer { + private final Field _field; + + IntFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + int value = 0; + + try { + value = in.readInt(); + + _field.setInt(obj, value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static class LongFieldDeserializer extends FieldDeserializer { + private final Field _field; + + LongFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + long value = 0; + + try { + value = in.readLong(); + + _field.setLong(obj, value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static class FloatFieldDeserializer extends FieldDeserializer { + private final Field _field; + + FloatFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + double value = 0; + + try { + value = in.readDouble(); + + _field.setFloat(obj, (float) value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static class DoubleFieldDeserializer extends FieldDeserializer { + private final Field _field; + + DoubleFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + double value = 0; + + try { + value = in.readDouble(); + + _field.setDouble(obj, value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static class StringFieldDeserializer extends FieldDeserializer { + private final Field _field; + + StringFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + String value = null; + + try { + value = in.readString(); + + _field.set(obj, value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static class SqlDateFieldDeserializer extends FieldDeserializer { + private final Field _field; + + SqlDateFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + java.sql.Date value = null; + + try { + java.util.Date date = (java.util.Date) in.readObject(); + value = new java.sql.Date(date.getTime()); + + _field.set(obj, value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static class SqlTimestampFieldDeserializer extends FieldDeserializer { + private final Field _field; + + SqlTimestampFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + java.sql.Timestamp value = null; + + try { + java.util.Date date = (java.util.Date) in.readObject(); + if (date != null) value = new java.sql.Timestamp(date.getTime()); + + _field.set(obj, value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static class SqlTimeFieldDeserializer extends FieldDeserializer { + private final Field _field; + + SqlTimeFieldDeserializer(Field field) + { + _field = field; + } + + void deserialize(AbstractHessianInput in, Object obj) + throws IOException + { + java.sql.Time value = null; + + try { + java.util.Date date = (java.util.Date) in.readObject(); + value = new java.sql.Time(date.getTime()); + + _field.set(obj, value); + } catch (Exception e) { + logDeserializeError(_field, obj, value, e); + } + } + } + + static void logDeserializeError(Field field, Object obj, Object value, + Throwable e) + throws IOException + { + String fieldName = (field.getDeclaringClass().getName() + + "." + field.getName()); + + if (e instanceof HessianFieldException) + throw (HessianFieldException) e; + else if (e instanceof IOException) + throw new HessianFieldException(fieldName + ": " + e.getMessage(), e); + + if (value != null) + throw new HessianFieldException(fieldName + ": " + value.getClass().getName() + " (" + value + ")" + + " cannot be assigned to '" + field.getType().getName() + "'", e); + else + throw new HessianFieldException(fieldName + ": " + field.getType().getName() + " cannot be assigned from null", e); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/JavaSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/JavaSerializer.java new file mode 100644 index 000000000000..0103358b2b33 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/JavaSerializer.java @@ -0,0 +1,434 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.io.Serializable; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Serializing an object for known object types. + */ +public class JavaSerializer extends AbstractSerializer +{ + private static final Logger log + = Logger.getLogger(JavaSerializer.class.getName()); + + private static Object []NULL_ARGS = new Object[0]; + + private Field []_fields; + private FieldSerializer []_fieldSerializers; + + private Object _writeReplaceFactory; + private Method _writeReplace; + + public JavaSerializer(Class cl, ClassLoader loader) + { + introspectWriteReplace(cl, loader); + + if (_writeReplace != null) + _writeReplace.setAccessible(true); + + ArrayList primitiveFields = new ArrayList(); + ArrayList compoundFields = new ArrayList(); + + for (; cl != null; cl = cl.getSuperclass()) { + Field []fields = cl.getDeclaredFields(); + for (int i = 0; i < fields.length; i++) { + Field field = fields[i]; + + if (Modifier.isTransient(field.getModifiers()) + || Modifier.isStatic(field.getModifiers())) + continue; + + // XXX: could parameterize the handler to only deal with public + field.setAccessible(true); + + if (field.getType().isPrimitive() + || (field.getType().getName().startsWith("java.lang.") + && ! field.getType().equals(Object.class))) + primitiveFields.add(field); + else + compoundFields.add(field); + } + } + + ArrayList fields = new ArrayList(); + fields.addAll(primitiveFields); + fields.addAll(compoundFields); + + _fields = new Field[fields.size()]; + fields.toArray(_fields); + + _fieldSerializers = new FieldSerializer[_fields.length]; + + for (int i = 0; i < _fields.length; i++) { + _fieldSerializers[i] = getFieldSerializer(_fields[i].getType()); + } + } + + private void introspectWriteReplace(Class cl, ClassLoader loader) + { + try { + String className = cl.getName() + "HessianSerializer"; + + Class serializerClass = Class.forName(className, false, loader); + + Object serializerObject = serializerClass.newInstance(); + + Method writeReplace = getWriteReplace(serializerClass, cl); + + if (writeReplace != null) { + _writeReplaceFactory = serializerObject; + _writeReplace = writeReplace; + + return; + } + } catch (ClassNotFoundException e) { + } catch (Exception e) { + log.log(Level.FINER, e.toString(), e); + } + + _writeReplace = getWriteReplace(cl); + } + + /** + * Returns the writeReplace method + */ + protected static Method getWriteReplace(Class cl) + { + for (; cl != null; cl = cl.getSuperclass()) { + Method []methods = cl.getDeclaredMethods(); + + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + + if (method.getName().equals("writeReplace") && + method.getParameterTypes().length == 0) + return method; + } + } + + return null; + } + + /** + * Returns the writeReplace method + */ + protected Method getWriteReplace(Class cl, Class param) + { + for (; cl != null; cl = cl.getSuperclass()) { + for (Method method : cl.getDeclaredMethods()) { + if (method.getName().equals("writeReplace") + && method.getParameterTypes().length == 1 + && param.equals(method.getParameterTypes()[0])) + return method; + } + } + + return null; + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + if (out.addRef(obj)) { + return; + } + + Class cl = obj.getClass(); + + try { + if (_writeReplace != null) { + Object repl; + + if (_writeReplaceFactory != null) + repl = _writeReplace.invoke(_writeReplaceFactory, obj); + else + repl = _writeReplace.invoke(obj); + + out.removeRef(obj); + + out.writeObject(repl); + + out.replaceRef(repl, obj); + + return; + } + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + // log.log(Level.FINE, e.toString(), e); + throw new RuntimeException(e); + } + + int ref = out.writeObjectBegin(cl.getName()); + + if (ref < -1) { + writeObject10(obj, out); + } + else { + if (ref == -1) { + writeDefinition20(out); + out.writeObjectBegin(cl.getName()); + } + + writeInstance(obj, out); + } + } + + private void writeObject10(Object obj, AbstractHessianOutput out) + throws IOException + { + for (int i = 0; i < _fields.length; i++) { + Field field = _fields[i]; + + out.writeString(field.getName()); + + _fieldSerializers[i].serialize(out, obj, field); + } + + out.writeMapEnd(); + } + + private void writeDefinition20(AbstractHessianOutput out) + throws IOException + { + out.writeClassFieldLength(_fields.length); + + for (int i = 0; i < _fields.length; i++) { + Field field = _fields[i]; + + out.writeString(field.getName()); + } + } + + public void writeInstance(Object obj, AbstractHessianOutput out) + throws IOException + { + for (int i = 0; i < _fields.length; i++) { + Field field = _fields[i]; + + _fieldSerializers[i].serialize(out, obj, field); + } + } + + private static FieldSerializer getFieldSerializer(Class type) + { + if (int.class.equals(type) + || byte.class.equals(type) + || short.class.equals(type) + || int.class.equals(type)) { + return IntFieldSerializer.SER; + } + else if (long.class.equals(type)) { + return LongFieldSerializer.SER; + } + else if (double.class.equals(type) || + float.class.equals(type)) { + return DoubleFieldSerializer.SER; + } + else if (boolean.class.equals(type)) { + return BooleanFieldSerializer.SER; + } + else if (String.class.equals(type)) { + return StringFieldSerializer.SER; + } + else if (java.util.Date.class.equals(type) + || java.sql.Date.class.equals(type) + || java.sql.Timestamp.class.equals(type) + || java.sql.Time.class.equals(type)) { + return DateFieldSerializer.SER; + } + else + return FieldSerializer.SER; + } + + static class FieldSerializer { + static final FieldSerializer SER = new FieldSerializer(); + + void serialize(AbstractHessianOutput out, Object obj, Field field) + throws IOException + { + Object value = null; + + try { + value = field.get(obj); + } catch (IllegalAccessException e) { + log.log(Level.FINE, e.toString(), e); + } + + try { + out.writeObject(value); + } catch (RuntimeException e) { + throw new RuntimeException(e.getMessage() + "\n Java field: " + field, + e); + } catch (IOException e) { + throw new IOExceptionWrapper(e.getMessage() + "\n Java field: " + field, + e); + } + } + } + + static class BooleanFieldSerializer extends FieldSerializer { + static final FieldSerializer SER = new BooleanFieldSerializer(); + + void serialize(AbstractHessianOutput out, Object obj, Field field) + throws IOException + { + boolean value = false; + + try { + value = field.getBoolean(obj); + } catch (IllegalAccessException e) { + log.log(Level.FINE, e.toString(), e); + } + + out.writeBoolean(value); + } + } + + static class IntFieldSerializer extends FieldSerializer { + static final FieldSerializer SER = new IntFieldSerializer(); + + void serialize(AbstractHessianOutput out, Object obj, Field field) + throws IOException + { + int value = 0; + + try { + value = field.getInt(obj); + } catch (IllegalAccessException e) { + log.log(Level.FINE, e.toString(), e); + } + + out.writeInt(value); + } + } + + static class LongFieldSerializer extends FieldSerializer { + static final FieldSerializer SER = new LongFieldSerializer(); + + void serialize(AbstractHessianOutput out, Object obj, Field field) + throws IOException + { + long value = 0; + + try { + value = field.getLong(obj); + } catch (IllegalAccessException e) { + log.log(Level.FINE, e.toString(), e); + } + + out.writeLong(value); + } + } + + static class DoubleFieldSerializer extends FieldSerializer { + static final FieldSerializer SER = new DoubleFieldSerializer(); + + void serialize(AbstractHessianOutput out, Object obj, Field field) + throws IOException + { + double value = 0; + + try { + value = field.getDouble(obj); + } catch (IllegalAccessException e) { + log.log(Level.FINE, e.toString(), e); + } + + out.writeDouble(value); + } + } + + static class StringFieldSerializer extends FieldSerializer { + static final FieldSerializer SER = new StringFieldSerializer(); + + void serialize(AbstractHessianOutput out, Object obj, Field field) + throws IOException + { + String value = null; + + try { + value = (String) field.get(obj); + } catch (IllegalAccessException e) { + log.log(Level.FINE, e.toString(), e); + } + + out.writeString(value); + } + } + + static class DateFieldSerializer extends FieldSerializer { + static final FieldSerializer SER = new DateFieldSerializer(); + + void serialize(AbstractHessianOutput out, Object obj, Field field) + throws IOException + { + java.util.Date value = null; + + try { + value = (java.util.Date) field.get(obj); + } catch (IllegalAccessException e) { + log.log(Level.FINE, e.toString(), e); + } + + if (value == null) + out.writeNull(); + else + out.writeUTCDate(value.getTime()); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/LocaleHandle.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/LocaleHandle.java new file mode 100644 index 000000000000..21454cf6c8c9 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/LocaleHandle.java @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.util.Locale; + +/** + * Handle for a locale object. + */ +public class LocaleHandle implements java.io.Serializable, HessianHandle { + private String value; + + public LocaleHandle(String locale) + { + this.value = locale; + } + + private Object readResolve() + { + String s = this.value; + + if (s == null) + return null; + + int len = s.length(); + char ch = ' '; + + int i = 0; + for (; + i < len && ('a' <= (ch = s.charAt(i)) && ch <= 'z' + || 'A' <= ch && ch <= 'Z' + || '0' <= ch && ch <= '9'); + i++) { + } + + String language = s.substring(0, i); + String country = null; + String var = null; + + if (ch == '-' || ch == '_') { + int head = ++i; + + for (; + i < len && ('a' <= (ch = s.charAt(i)) && ch <= 'z' + || 'A' <= ch && ch <= 'Z' + || '0' <= ch && ch <= '9'); + i++) { + } + + country = s.substring(head, i); + } + + if (ch == '-' || ch == '_') { + int head = ++i; + + for (; + i < len && ('a' <= (ch = s.charAt(i)) && ch <= 'z' + || 'A' <= ch && ch <= 'Z' + || '0' <= ch && ch <= '9'); + i++) { + } + + var = s.substring(head, i); + } + + if (var != null) + return new Locale(language, country, var); + else if (country != null) + return new Locale(language, country); + else + return new Locale(language); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/LocaleSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/LocaleSerializer.java new file mode 100644 index 000000000000..367c98667167 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/LocaleSerializer.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.Locale; + +/** + * Serializing a locale. + */ +public class LocaleSerializer extends AbstractSerializer { + private static LocaleSerializer SERIALIZER = new LocaleSerializer(); + + public static LocaleSerializer create() + { + return SERIALIZER; + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + if (obj == null) + out.writeNull(); + else { + Locale locale = (Locale) obj; + + out.writeObject(new LocaleHandle(locale.toString())); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/MapDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/MapDeserializer.java new file mode 100644 index 000000000000..5c51d9a70761 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/MapDeserializer.java @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.*; +import java.lang.reflect.*; + +/** + * Deserializing a JDK 1.2 Map. + */ +public class MapDeserializer extends AbstractMapDeserializer { + private Class _type; + private Constructor _ctor; + + public MapDeserializer(Class type) + { + if (type == null) + type = HashMap.class; + + _type = type; + + Constructor []ctors = type.getConstructors(); + for (int i = 0; i < ctors.length; i++) { + if (ctors[i].getParameterTypes().length == 0) + _ctor = ctors[i]; + } + + if (_ctor == null) { + try { + _ctor = HashMap.class.getConstructor(new Class[0]); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + } + + public Class getType() + { + if (_type != null) + return _type; + else + return HashMap.class; + } + + public Object readMap(AbstractHessianInput in) + throws IOException + { + Map map; + + if (_type == null) + map = new HashMap(); + else if (_type.equals(Map.class)) + map = new HashMap(); + else if (_type.equals(SortedMap.class)) + map = new TreeMap(); + else { + try { + map = (Map) _ctor.newInstance(); + } catch (Exception e) { + throw new IOExceptionWrapper(e); + } + } + + in.addRef(map); + + while (! in.isEnd()) { + map.put(in.readObject(), in.readObject()); + } + + in.readEnd(); + + return map; + } + + @Override + public Object readObject(AbstractHessianInput in, + String []fieldNames) + throws IOException + { + Map map = createMap(); + + int ref = in.addRef(map); + + for (int i = 0; i < fieldNames.length; i++) { + String name = fieldNames[i]; + + map.put(name, in.readObject()); + } + + return map; + } + + private Map createMap() + throws IOException + { + + if (_type == null) + return new HashMap(); + else if (_type.equals(Map.class)) + return new HashMap(); + else if (_type.equals(SortedMap.class)) + return new TreeMap(); + else { + try { + return (Map) _ctor.newInstance(); + } catch (Exception e) { + throw new IOExceptionWrapper(e); + } + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/MapSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/MapSerializer.java new file mode 100644 index 000000000000..c166060ab29b --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/MapSerializer.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * Serializing a JDK 1.2 java.util.Map. + */ +public class MapSerializer extends AbstractSerializer { + private boolean _isSendJavaType = true; + + /** + * Set true if the java type of the collection should be sent. + */ + public void setSendJavaType(boolean sendJavaType) + { + _isSendJavaType = sendJavaType; + } + + /** + * Return true if the java type of the collection should be sent. + */ + public boolean getSendJavaType() + { + return _isSendJavaType; + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + if (out.addRef(obj)) + return; + + Map map = (Map) obj; + + Class cl = obj.getClass(); + + if (cl.equals(HashMap.class) + || ! _isSendJavaType + || ! (obj instanceof java.io.Serializable)) + out.writeMapBegin(null); + else + out.writeMapBegin(obj.getClass().getName()); + + Iterator iter = map.entrySet().iterator(); + while (iter.hasNext()) { + Map.Entry entry = (Map.Entry) iter.next(); + + out.writeObject(entry.getKey()); + out.writeObject(entry.getValue()); + } + out.writeMapEnd(); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ObjectDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ObjectDeserializer.java new file mode 100644 index 000000000000..5f554d1a54a8 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ObjectDeserializer.java @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; + +/** + * Serializing an object for known object types. + */ +public class ObjectDeserializer extends AbstractDeserializer { + private Class _cl; + + public ObjectDeserializer(Class cl) + { + _cl = cl; + } + + public Class getType() + { + return _cl; + } + + public Object readObject(AbstractHessianInput in) + throws IOException + { + return in.readObject(); + } + + public Object readObject(AbstractHessianInput in, String []fieldNames) + throws IOException + { + throw new UnsupportedOperationException(String.valueOf(this)); + } + + public Object readList(AbstractHessianInput in, int length) + throws IOException + { + throw new UnsupportedOperationException(String.valueOf(this)); + } + + public Object readLengthList(AbstractHessianInput in, int length) + throws IOException + { + throw new UnsupportedOperationException(String.valueOf(this)); + } + + @Override + public String toString() + { + return getClass().getSimpleName() + "[" + _cl + "]"; + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/RemoteSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/RemoteSerializer.java new file mode 100644 index 000000000000..3d7e0d88d62e --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/RemoteSerializer.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Serializing a remote object. + */ +public class RemoteSerializer extends AbstractSerializer { + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + // XXX: needs to be handled as a separate class + throw new UnsupportedOperationException(getClass().getName()); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Serializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Serializer.java new file mode 100644 index 000000000000..67060d9a8f2b --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/Serializer.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Serializing an object. + */ +public interface Serializer { + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException; +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SerializerFactory.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SerializerFactory.java new file mode 100644 index 000000000000..46a16fbceb8c --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SerializerFactory.java @@ -0,0 +1,649 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.*; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.management.*; + +/** + * Factory for returning serialization methods. + */ +public class SerializerFactory extends AbstractSerializerFactory +{ + private static final Logger log + = Logger.getLogger(SerializerFactory.class.getName()); + + private static Deserializer OBJECT_DESERIALIZER + = new BasicDeserializer(BasicDeserializer.OBJECT); + + private static HashMap _staticSerializerMap; + private static HashMap _staticDeserializerMap; + private static HashMap _staticTypeMap; + + private ClassLoader _loader; + + protected Serializer _defaultSerializer; + + // Additional factories + protected ArrayList _factories = new ArrayList(); + + protected CollectionSerializer _collectionSerializer; + protected MapSerializer _mapSerializer; + + private Deserializer _hashMapDeserializer; + private Deserializer _arrayListDeserializer; + private HashMap _cachedSerializerMap; + private HashMap _cachedDeserializerMap; + private HashMap _cachedTypeDeserializerMap; + + private boolean _isAllowNonSerializable; + + public SerializerFactory() + { + this(Thread.currentThread().getContextClassLoader()); + } + + public SerializerFactory(ClassLoader loader) + { + _loader = loader; + } + + public ClassLoader getClassLoader() + { + return _loader; + } + + /** + * Set true if the collection serializer should send the java type. + */ + public void setSendCollectionType(boolean isSendType) + { + if (_collectionSerializer == null) + _collectionSerializer = new CollectionSerializer(); + + _collectionSerializer.setSendJavaType(isSendType); + + if (_mapSerializer == null) + _mapSerializer = new MapSerializer(); + + _mapSerializer.setSendJavaType(isSendType); + } + + /** + * Adds a factory. + */ + public void addFactory(AbstractSerializerFactory factory) + { + _factories.add(factory); + } + + /** + * If true, non-serializable objects are allowed. + */ + public void setAllowNonSerializable(boolean allow) + { + _isAllowNonSerializable = allow; + } + + /** + * If true, non-serializable objects are allowed. + */ + public boolean isAllowNonSerializable() + { + return _isAllowNonSerializable; + } + + /** + * Returns the serializer for a class. + * + * @param cl the class of the object that needs to be serialized. + * + * @return a serializer object for the serialization. + */ + public Serializer getSerializer(Class cl) + throws HessianProtocolException + { + Serializer serializer; + + serializer = (Serializer) _staticSerializerMap.get(cl); + if (serializer != null) + return serializer; + + if (_cachedSerializerMap != null) { + synchronized (_cachedSerializerMap) { + serializer = (Serializer) _cachedSerializerMap.get(cl); + } + + if (serializer != null) + return serializer; + } + + for (int i = 0; + serializer == null && _factories != null && i < _factories.size(); + i++) { + AbstractSerializerFactory factory; + + factory = (AbstractSerializerFactory) _factories.get(i); + + serializer = factory.getSerializer(cl); + } + + if (serializer != null) { + } + + else if (JavaSerializer.getWriteReplace(cl) != null) + serializer = new JavaSerializer(cl, _loader); + + else if (HessianRemoteObject.class.isAssignableFrom(cl)) + serializer = new RemoteSerializer(); + +// else if (BurlapRemoteObject.class.isAssignableFrom(cl)) +// serializer = new RemoteSerializer(); + + else if (Map.class.isAssignableFrom(cl)) { + if (_mapSerializer == null) + _mapSerializer = new MapSerializer(); + + serializer = _mapSerializer; + } + else if (Collection.class.isAssignableFrom(cl)) { + if (_collectionSerializer == null) { + _collectionSerializer = new CollectionSerializer(); + } + + serializer = _collectionSerializer; + } + + else if (cl.isArray()) + serializer = new ArraySerializer(); + + else if (Throwable.class.isAssignableFrom(cl)) + serializer = new ThrowableSerializer(cl, getClassLoader()); + + else if (InputStream.class.isAssignableFrom(cl)) + serializer = new InputStreamSerializer(); + + else if (Iterator.class.isAssignableFrom(cl)) + serializer = IteratorSerializer.create(); + + else if (Enumeration.class.isAssignableFrom(cl)) + serializer = EnumerationSerializer.create(); + + else if (Calendar.class.isAssignableFrom(cl)) + serializer = CalendarSerializer.create(); + + else if (Locale.class.isAssignableFrom(cl)) + serializer = LocaleSerializer.create(); + + else if (Enum.class.isAssignableFrom(cl)) + serializer = new EnumSerializer(cl); + + if (serializer == null) + serializer = getDefaultSerializer(cl); + + if (_cachedSerializerMap == null) + _cachedSerializerMap = new HashMap(8); + + synchronized (_cachedSerializerMap) { + _cachedSerializerMap.put(cl, serializer); + } + + return serializer; + } + + /** + * Returns the default serializer for a class that isn't matched + * directly. Application can override this method to produce + * bean-style serialization instead of field serialization. + * + * @param cl the class of the object that needs to be serialized. + * + * @return a serializer object for the serialization. + */ + protected Serializer getDefaultSerializer(Class cl) + { + if (_defaultSerializer != null) + return _defaultSerializer; + + if (! Serializable.class.isAssignableFrom(cl) + && ! _isAllowNonSerializable) { + throw new IllegalStateException("Serialized class " + cl.getName() + " must implement java.io.Serializable"); + } + + return new JavaSerializer(cl, _loader); + } + + /** + * Returns the deserializer for a class. + * + * @param cl the class of the object that needs to be deserialized. + * + * @return a deserializer object for the serialization. + */ + public Deserializer getDeserializer(Class cl) + throws HessianProtocolException + { + Deserializer deserializer; + + deserializer = (Deserializer) _staticDeserializerMap.get(cl); + if (deserializer != null) + return deserializer; + + if (_cachedDeserializerMap != null) { + synchronized (_cachedDeserializerMap) { + deserializer = (Deserializer) _cachedDeserializerMap.get(cl); + } + + if (deserializer != null) + return deserializer; + } + + + for (int i = 0; + deserializer == null && _factories != null && i < _factories.size(); + i++) { + AbstractSerializerFactory factory; + factory = (AbstractSerializerFactory) _factories.get(i); + + deserializer = factory.getDeserializer(cl); + } + + if (deserializer != null) { + } + + else if (Collection.class.isAssignableFrom(cl)) + deserializer = new CollectionDeserializer(cl); + + else if (Map.class.isAssignableFrom(cl)) + deserializer = new MapDeserializer(cl); + + else if (cl.isInterface()) + deserializer = new ObjectDeserializer(cl); + + else if (cl.isArray()) + deserializer = new ArrayDeserializer(cl.getComponentType()); + + else if (Enumeration.class.isAssignableFrom(cl)) + deserializer = EnumerationDeserializer.create(); + + else if (Enum.class.isAssignableFrom(cl)) + deserializer = new EnumDeserializer(cl); + + else if (Class.class.equals(cl)) + deserializer = new ClassDeserializer(_loader); + + else + deserializer = getDefaultDeserializer(cl); + + if (_cachedDeserializerMap == null) + _cachedDeserializerMap = new HashMap(8); + + synchronized (_cachedDeserializerMap) { + _cachedDeserializerMap.put(cl, deserializer); + } + + return deserializer; + } + + /** + * Returns the default serializer for a class that isn't matched + * directly. Application can override this method to produce + * bean-style serialization instead of field serialization. + * + * @param cl the class of the object that needs to be serialized. + * + * @return a serializer object for the serialization. + */ + protected Deserializer getDefaultDeserializer(Class cl) + { + return new JavaDeserializer(cl); + } + + /** + * Reads the object as a list. + */ + public Object readList(AbstractHessianInput in, int length, String type) + throws HessianProtocolException, IOException + { + Deserializer deserializer = getDeserializer(type); + + if (deserializer != null) + return deserializer.readList(in, length); + else + return new CollectionDeserializer(ArrayList.class).readList(in, length); + } + + /** + * Reads the object as a map. + */ + public Object readMap(AbstractHessianInput in, String type) + throws HessianProtocolException, IOException + { + Deserializer deserializer = getDeserializer(type); + + if (deserializer != null) + return deserializer.readMap(in); + else if (_hashMapDeserializer != null) + return _hashMapDeserializer.readMap(in); + else { + _hashMapDeserializer = new MapDeserializer(HashMap.class); + + return _hashMapDeserializer.readMap(in); + } + } + + /** + * Reads the object as a map. + */ + public Object readObject(AbstractHessianInput in, + String type, + String []fieldNames) + throws HessianProtocolException, IOException + { + Deserializer deserializer = getDeserializer(type); + + if (deserializer != null) + return deserializer.readObject(in, fieldNames); + else if (_hashMapDeserializer != null) + return _hashMapDeserializer.readObject(in, fieldNames); + else { + _hashMapDeserializer = new MapDeserializer(HashMap.class); + + return _hashMapDeserializer.readObject(in, fieldNames); + } + } + + /** + * Reads the object as a map. + */ + public Deserializer getObjectDeserializer(String type, Class cl) + throws HessianProtocolException + { + Deserializer reader = getObjectDeserializer(type); + + if (cl == null + || cl.equals(reader.getType()) + || cl.isAssignableFrom(reader.getType()) + || HessianHandle.class.isAssignableFrom(reader.getType())) { + return reader; + } + + if (log.isLoggable(Level.FINE)) { + log.fine("hessian: expected '" + cl.getName() + "' at '" + type + "' (" + + reader.getType().getName() + ")"); + } + + return getDeserializer(cl); + } + + /** + * Reads the object as a map. + */ + public Deserializer getObjectDeserializer(String type) + throws HessianProtocolException + { + Deserializer deserializer = getDeserializer(type); + + if (deserializer != null) + return deserializer; + else if (_hashMapDeserializer != null) + return _hashMapDeserializer; + else { + _hashMapDeserializer = new MapDeserializer(HashMap.class); + + return _hashMapDeserializer; + } + } + + /** + * Reads the object as a map. + */ + public Deserializer getListDeserializer(String type, Class cl) + throws HessianProtocolException + { + Deserializer reader = getListDeserializer(type); + + if (cl == null + || cl.equals(reader.getType()) + || cl.isAssignableFrom(reader.getType())) { + return reader; + } + + if (log.isLoggable(Level.FINE)) { + log.fine("hessian: expected '" + cl.getName() + "' at '" + type + "' (" + + reader.getType().getName() + ")"); + } + + return getDeserializer(cl); + } + + /** + * Reads the object as a map. + */ + public Deserializer getListDeserializer(String type) + throws HessianProtocolException + { + Deserializer deserializer = getDeserializer(type); + + if (deserializer != null) + return deserializer; + else if (_arrayListDeserializer != null) + return _arrayListDeserializer; + else { + _arrayListDeserializer = new CollectionDeserializer(ArrayList.class); + + return _arrayListDeserializer; + } + } + + /** + * Returns a deserializer based on a string type. + */ + public Deserializer getDeserializer(String type) + throws HessianProtocolException + { + if (type == null || type.equals("")) + return null; + + Deserializer deserializer; + + if (_cachedTypeDeserializerMap != null) { + synchronized (_cachedTypeDeserializerMap) { + deserializer = (Deserializer) _cachedTypeDeserializerMap.get(type); + } + + if (deserializer != null) + return deserializer; + } + + + deserializer = (Deserializer) _staticTypeMap.get(type); + if (deserializer != null) + return deserializer; + + if (type.startsWith("[")) { + Deserializer subDeserializer = getDeserializer(type.substring(1)); + + if (subDeserializer != null) + deserializer = new ArrayDeserializer(subDeserializer.getType()); + else + deserializer = new ArrayDeserializer(Object.class); + } + else { + try { + Class cl = Class.forName(type, false, _loader); + deserializer = getDeserializer(cl); + } catch (Exception e) { + log.warning("Hessian/Burlap: '" + type + "' is an unknown class in " + _loader + ":\n" + e); + + log.log(Level.FINER, e.toString(), e); + } + } + + if (deserializer != null) { + if (_cachedTypeDeserializerMap == null) + _cachedTypeDeserializerMap = new HashMap(8); + + synchronized (_cachedTypeDeserializerMap) { + _cachedTypeDeserializerMap.put(type, deserializer); + } + } + + return deserializer; + } + + private static void addBasic(Class cl, String typeName, int type) + { + _staticSerializerMap.put(cl, new BasicSerializer(type)); + + Deserializer deserializer = new BasicDeserializer(type); + _staticDeserializerMap.put(cl, deserializer); + _staticTypeMap.put(typeName, deserializer); + } + + static { + _staticSerializerMap = new HashMap(); + _staticDeserializerMap = new HashMap(); + _staticTypeMap = new HashMap(); + + addBasic(void.class, "void", BasicSerializer.NULL); + + addBasic(Boolean.class, "boolean", BasicSerializer.BOOLEAN); + addBasic(Byte.class, "byte", BasicSerializer.BYTE); + addBasic(Short.class, "short", BasicSerializer.SHORT); + addBasic(Integer.class, "int", BasicSerializer.INTEGER); + addBasic(Long.class, "long", BasicSerializer.LONG); + addBasic(Float.class, "float", BasicSerializer.FLOAT); + addBasic(Double.class, "double", BasicSerializer.DOUBLE); + addBasic(Character.class, "char", BasicSerializer.CHARACTER_OBJECT); + addBasic(String.class, "string", BasicSerializer.STRING); + addBasic(Object.class, "object", BasicSerializer.OBJECT); + addBasic(java.util.Date.class, "date", BasicSerializer.DATE); + + addBasic(boolean.class, "boolean", BasicSerializer.BOOLEAN); + addBasic(byte.class, "byte", BasicSerializer.BYTE); + addBasic(short.class, "short", BasicSerializer.SHORT); + addBasic(int.class, "int", BasicSerializer.INTEGER); + addBasic(long.class, "long", BasicSerializer.LONG); + addBasic(float.class, "float", BasicSerializer.FLOAT); + addBasic(double.class, "double", BasicSerializer.DOUBLE); + addBasic(char.class, "char", BasicSerializer.CHARACTER); + + addBasic(boolean[].class, "[boolean", BasicSerializer.BOOLEAN_ARRAY); + addBasic(byte[].class, "[byte", BasicSerializer.BYTE_ARRAY); + addBasic(short[].class, "[short", BasicSerializer.SHORT_ARRAY); + addBasic(int[].class, "[int", BasicSerializer.INTEGER_ARRAY); + addBasic(long[].class, "[long", BasicSerializer.LONG_ARRAY); + addBasic(float[].class, "[float", BasicSerializer.FLOAT_ARRAY); + addBasic(double[].class, "[double", BasicSerializer.DOUBLE_ARRAY); + addBasic(char[].class, "[char", BasicSerializer.CHARACTER_ARRAY); + addBasic(String[].class, "[string", BasicSerializer.STRING_ARRAY); + addBasic(Object[].class, "[object", BasicSerializer.OBJECT_ARRAY); + + _staticSerializerMap.put(Class.class, new ClassSerializer()); + + _staticDeserializerMap.put(Number.class, new BasicDeserializer(BasicSerializer.NUMBER)); + + _staticSerializerMap.put(BigDecimal.class, new StringValueSerializer()); + try { + _staticDeserializerMap.put(BigDecimal.class, + new StringValueDeserializer(BigDecimal.class)); + _staticDeserializerMap.put(BigInteger.class, + new BigIntegerDeserializer()); + } catch (Throwable e) { + } + + _staticSerializerMap.put(File.class, new StringValueSerializer()); + try { + _staticDeserializerMap.put(File.class, + new StringValueDeserializer(File.class)); + } catch (Throwable e) { + } + + _staticSerializerMap.put(ObjectName.class, new StringValueSerializer()); + try { + _staticDeserializerMap.put(ObjectName.class, + new StringValueDeserializer(ObjectName.class)); + } catch (Throwable e) { + } + + _staticSerializerMap.put(java.sql.Date.class, new SqlDateSerializer()); + _staticSerializerMap.put(java.sql.Time.class, new SqlDateSerializer()); + _staticSerializerMap.put(java.sql.Timestamp.class, new SqlDateSerializer()); + + _staticSerializerMap.put(java.io.InputStream.class, + new InputStreamSerializer()); + _staticDeserializerMap.put(java.io.InputStream.class, + new InputStreamDeserializer()); + + try { + _staticDeserializerMap.put(java.sql.Date.class, + new SqlDateDeserializer(java.sql.Date.class)); + _staticDeserializerMap.put(java.sql.Time.class, + new SqlDateDeserializer(java.sql.Time.class)); + _staticDeserializerMap.put(java.sql.Timestamp.class, + new SqlDateDeserializer(java.sql.Timestamp.class)); + } catch (Throwable e) { + e.printStackTrace(); + } + + // hessian/3bb5 + try { + Class stackTrace = StackTraceElement.class; + + _staticDeserializerMap.put(stackTrace, new StackTraceElementDeserializer()); + } catch (Throwable e) { + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SqlDateDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SqlDateDeserializer.java new file mode 100644 index 000000000000..b23c7bb18dcb --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SqlDateDeserializer.java @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.lang.reflect.Constructor; + +/** + * Deserializing a string valued object + */ +public class SqlDateDeserializer extends AbstractDeserializer { + private Class _cl; + private Constructor _constructor; + + public SqlDateDeserializer(Class cl) + throws NoSuchMethodException + { + _cl = cl; + _constructor = cl.getConstructor(new Class[] { long.class }); + } + + public Class getType() + { + return _cl; + } + + public Object readMap(AbstractHessianInput in) + throws IOException + { + int ref = in.addRef(null); + + long initValue = Long.MIN_VALUE; + + while (! in.isEnd()) { + String key = in.readString(); + + if (key.equals("value")) + initValue = in.readUTCDate(); + else + in.readString(); + } + + in.readMapEnd(); + + Object value = create(initValue); + + in.setRef(ref, value); + + return value; + } + + public Object readObject(AbstractHessianInput in, String []fieldNames) + throws IOException + { + int ref = in.addRef(null); + + long initValue = Long.MIN_VALUE; + + for (int i = 0; i < fieldNames.length; i++) { + String key = fieldNames[i]; + + if (key.equals("value")) + initValue = in.readUTCDate(); + else + in.readObject(); + } + + Object value = create(initValue); + + in.setRef(ref, value); + + return value; + } + + private Object create(long initValue) + throws IOException + { + if (initValue == Long.MIN_VALUE) + throw new IOException(_cl.getName() + " expects name."); + + try { + return _constructor.newInstance(new Object[] { new Long(initValue) }); + } catch (Exception e) { + throw new IOExceptionWrapper(e); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SqlDateSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SqlDateSerializer.java new file mode 100644 index 000000000000..76bae3157108 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/SqlDateSerializer.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.util.Date; + +/** + * Serializing a sql date object. + */ +public class SqlDateSerializer extends AbstractSerializer +{ + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + if (obj == null) + out.writeNull(); + else { + Class cl = obj.getClass(); + + if (out.addRef(obj)) + return; + + int ref = out.writeObjectBegin(cl.getName()); + + if (ref < -1) { + out.writeString("value"); + out.writeUTCDate(((Date) obj).getTime()); + out.writeMapEnd(); + } + else { + if (ref == -1) { + out.writeInt(1); + out.writeString("value"); + out.writeObjectBegin(cl.getName()); + } + + out.writeUTCDate(((Date) obj).getTime()); + } + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StackTraceElementDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StackTraceElementDeserializer.java new file mode 100644 index 000000000000..1918d7321ed4 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StackTraceElementDeserializer.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.*; +import java.util.HashMap; + +/** + * Deserializing a JDK 1.4 StackTraceElement + */ +public class StackTraceElementDeserializer extends JavaDeserializer { + public StackTraceElementDeserializer() + { + super(StackTraceElement.class); + } + + @Override + protected Object instantiate() + throws Exception + { + return new StackTraceElement("", "", "", 0); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StringValueDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StringValueDeserializer.java new file mode 100644 index 000000000000..f142def6d80c --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StringValueDeserializer.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; +import java.lang.reflect.Constructor; + +/** + * Deserializing a string valued object + */ +public class StringValueDeserializer extends AbstractDeserializer { + private Class _cl; + private Constructor _constructor; + + public StringValueDeserializer(Class cl) + { + try { + _cl = cl; + _constructor = cl.getConstructor(new Class[] { String.class }); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public Class getType() + { + return _cl; + } + + public Object readMap(AbstractHessianInput in) + throws IOException + { + String value = null; + + while (! in.isEnd()) { + String key = in.readString(); + + if (key.equals("value")) + value = in.readString(); + else + in.readObject(); + } + + in.readMapEnd(); + + Object object = create(value); + + in.addRef(object); + + return object; + } + + public Object readObject(AbstractHessianInput in, String []fieldNames) + throws IOException + { + String value = null; + + for (int i = 0; i < fieldNames.length; i++) { + if ("value".equals(fieldNames[i])) + value = in.readString(); + else + in.readObject(); + } + + Object object = create(value); + + in.addRef(object); + + return object; + } + + private Object create(String value) + throws IOException + { + if (value == null) + throw new IOException(_cl.getName() + " expects name."); + + try { + return _constructor.newInstance(new Object[] { value }); + } catch (Exception e) { + throw new IOExceptionWrapper(e); + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StringValueSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StringValueSerializer.java new file mode 100644 index 000000000000..0e04b0778828 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/StringValueSerializer.java @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Serializing a remote object. + */ +public class StringValueSerializer extends AbstractSerializer { + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + if (obj == null) + out.writeNull(); + else { + if (out.addRef(obj)) + return; + + Class cl = obj.getClass(); + + int ref = out.writeObjectBegin(cl.getName()); + + if (ref < -1) { + out.writeString("value"); + out.writeString(obj.toString()); + out.writeMapEnd(); + } + else { + if (ref == -1) { + out.writeInt(1); + out.writeString("value"); + out.writeObjectBegin(cl.getName()); + } + + out.writeString(obj.toString()); + } + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ThrowableSerializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ThrowableSerializer.java new file mode 100644 index 000000000000..391dc1bb0ff2 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ThrowableSerializer.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Serializing an object for known object types. + */ +public class ThrowableSerializer extends JavaSerializer { + public ThrowableSerializer(Class cl, ClassLoader loader) + { + super(cl, loader); + } + + public void writeObject(Object obj, AbstractHessianOutput out) + throws IOException + { + Throwable e = (Throwable) obj; + + e.getStackTrace(); + + super.writeObject(obj, out); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ValueDeserializer.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ValueDeserializer.java new file mode 100644 index 000000000000..ba05a47c5d61 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/io/ValueDeserializer.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.io; + +import java.io.IOException; + +/** + * Deserializing a string valued object + */ +abstract public class ValueDeserializer extends AbstractDeserializer { + public Object readMap(AbstractHessianInput in) + throws IOException + { + String initValue = null; + + while (! in.isEnd()) { + String key = in.readString(); + + if (key.equals("value")) + initValue = in.readString(); + else + in.readObject(); + } + + in.readMapEnd(); + + return create(initValue); + } + + public Object readObject(AbstractHessianInput in, String []fieldNames) + throws IOException + { + String initValue = null; + + for (int i = 0; i < fieldNames.length; i++) { + if ("value".equals(fieldNames[i])) + initValue = in.readString(); + else + in.readObject(); + } + + return create(initValue); + } + + abstract Object create(String value) + throws IOException; +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/security/X509Encryption.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/security/X509Encryption.java new file mode 100644 index 000000000000..6a0b62211c11 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/security/X509Encryption.java @@ -0,0 +1,380 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.security; + +import java.security.*; +import java.security.cert.*; +import java.util.*; +import javax.crypto.*; + +import java.io.*; + +import com.alibaba.com.caucho.hessian.io.*; + +public class X509Encryption extends HessianEnvelope { + private String _algorithm = "AES"; + + // certificate for encryption/decryption + private X509Certificate _cert; + + // private key for decryption + private PrivateKey _privateKey; + + private SecureRandom _secureRandom; + + public X509Encryption() + { + } + + /** + * Sets the encryption algorithm for the content. + */ + public void setAlgorithm(String algorithm) + { + if (algorithm == null) + throw new NullPointerException(); + + _algorithm = algorithm; + } + + /** + * Gets the encryption algorithm for the content. + */ + public String getAlgorithm() + { + return _algorithm; + } + + /** + * The X509 certificate to obtain the public key of the recipient. + */ + public X509Certificate getCertificate() + { + return _cert; + } + + /** + * The X509 certificate to obtain the public key of the recipient. + */ + public void setCertificate(X509Certificate cert) + { + _cert = cert; + } + + /** + * The private key for decryption. + */ + public PrivateKey getPrivateKey() + { + return _privateKey; + } + + /** + * The X509 certificate to obtain the public key of the recipient. + */ + public void setPrivateKey(PrivateKey privateKey) + { + _privateKey = privateKey; + } + + /** + * The random number generator for the shared secrets. + */ + public SecureRandom getSecureRandom() + { + return _secureRandom; + } + + /** + * The random number generator for the shared secrets. + */ + public void setSecureRandom(SecureRandom random) + { + _secureRandom = random; + } + + public Hessian2Output wrap(Hessian2Output out) + throws IOException + { + if (_cert == null) + throw new IOException("X509Encryption.wrap requires a certificate"); + + OutputStream os = new EncryptOutputStream(out); + + Hessian2Output filterOut = new Hessian2Output(os); + + filterOut.setCloseStreamOnClose(true); + + return filterOut; + } + + public Hessian2Input unwrap(Hessian2Input in) + throws IOException + { + if (_privateKey == null) + throw new IOException("X509Encryption.unwrap requires a private key"); + + if (_cert == null) + throw new IOException("X509Encryption.unwrap requires a certificate"); + + int version = in.readEnvelope(); + + String method = in.readMethod(); + + if (! method.equals(getClass().getName())) + throw new IOException("expected hessian Envelope method '" + + getClass().getName() + "' at '" + method + "'"); + + return unwrapHeaders(in); + } + + public Hessian2Input unwrapHeaders(Hessian2Input in) + throws IOException + { + if (_privateKey == null) + throw new IOException("X509Encryption.unwrap requires a private key"); + + if (_cert == null) + throw new IOException("X509Encryption.unwrap requires a certificate"); + + InputStream is = new EncryptInputStream(in); + + Hessian2Input filter = new Hessian2Input(is); + + filter.setCloseStreamOnClose(true); + + return filter; + } + + class EncryptOutputStream extends OutputStream { + private Hessian2Output _out; + + private Cipher _cipher; + private OutputStream _bodyOut; + private CipherOutputStream _cipherOut; + + EncryptOutputStream(Hessian2Output out) + throws IOException + { + try { + _out = out; + + KeyGenerator keyGen = KeyGenerator.getInstance(_algorithm); + + if (_secureRandom != null) + keyGen.init(_secureRandom); + + SecretKey sharedKey = keyGen.generateKey(); + + _out = out; + + _out.startEnvelope(X509Encryption.class.getName()); + + PublicKey publicKey = _cert.getPublicKey(); + + byte []encoded = publicKey.getEncoded(); + MessageDigest md = MessageDigest.getInstance("SHA1"); + md.update(encoded); + byte []fingerprint = md.digest(); + + String keyAlgorithm = publicKey.getAlgorithm(); + Cipher keyCipher = Cipher.getInstance(keyAlgorithm); + if (_secureRandom != null) + keyCipher.init(Cipher.WRAP_MODE, _cert, _secureRandom); + else + keyCipher.init(Cipher.WRAP_MODE, _cert); + + byte []encKey = keyCipher.wrap(sharedKey); + + _out.writeInt(4); + + _out.writeString("algorithm"); + _out.writeString(_algorithm); + _out.writeString("fingerprint"); + _out.writeBytes(fingerprint); + _out.writeString("key-algorithm"); + _out.writeString(keyAlgorithm); + _out.writeString("key"); + _out.writeBytes(encKey); + + _bodyOut = _out.getBytesOutputStream(); + + _cipher = Cipher.getInstance(_algorithm); + if (_secureRandom != null) + _cipher.init(Cipher.ENCRYPT_MODE, sharedKey, _secureRandom); + else + _cipher.init(Cipher.ENCRYPT_MODE, sharedKey); + + _cipherOut = new CipherOutputStream(_bodyOut, _cipher); + } catch (RuntimeException e) { + throw e; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public void write(int ch) + throws IOException + { + _cipherOut.write(ch); + } + + public void write(byte []buffer, int offset, int length) + throws IOException + { + _cipherOut.write(buffer, offset, length); + } + + public void close() + throws IOException + { + Hessian2Output out = _out; + _out = null; + + if (out != null) { + _cipherOut.close(); + _bodyOut.close(); + + out.writeInt(0); + out.completeEnvelope(); + out.close(); + } + } + } + + class EncryptInputStream extends InputStream { + private Hessian2Input _in; + + private Cipher _cipher; + private InputStream _bodyIn; + private CipherInputStream _cipherIn; + + EncryptInputStream(Hessian2Input in) + throws IOException + { + try { + _in = in; + + byte []fingerprint = null; + String keyAlgorithm = null; + String algorithm = null; + byte []encKey = null; + + int len = in.readInt(); + + for (int i = 0; i < len; i++) { + String header = in.readString(); + + if ("fingerprint".equals(header)) + fingerprint = in.readBytes(); + else if ("key-algorithm".equals(header)) + keyAlgorithm = in.readString(); + else if ("algorithm".equals(header)) + algorithm = in.readString(); + else if ("key".equals(header)) + encKey = in.readBytes(); + else + throw new IOException("'" + header + "' is an unexpected header"); + } + + Cipher keyCipher = Cipher.getInstance(keyAlgorithm); + keyCipher.init(Cipher.UNWRAP_MODE, _privateKey); + + Key key = keyCipher.unwrap(encKey, algorithm, Cipher.SECRET_KEY); + _bodyIn = _in.readInputStream(); + + _cipher = Cipher.getInstance(algorithm); + _cipher.init(Cipher.DECRYPT_MODE, key); + + _cipherIn = new CipherInputStream(_bodyIn, _cipher); + } catch (RuntimeException e) { + throw e; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public int read() + throws IOException + { + return _cipherIn.read(); + } + + public int read(byte []buffer, int offset, int length) + throws IOException + { + return _cipherIn.read(buffer, offset, length); + } + + public void close() + throws IOException + { + Hessian2Input in = _in; + _in = null; + + if (in != null) { + _cipherIn.close(); + _bodyIn.close(); + + int len = in.readInt(); + + if (len != 0) + throw new IOException("Unexpected footer"); + + in.completeEnvelope(); + + in.close(); + } + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/security/X509Signature.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/security/X509Signature.java new file mode 100644 index 000000000000..77b19bb0435e --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/security/X509Signature.java @@ -0,0 +1,397 @@ +/* + * Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Hessian", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.security; + +import java.security.*; +import java.security.cert.*; +import java.util.*; +import javax.crypto.*; + +import java.io.*; + +import com.alibaba.com.caucho.hessian.io.*; + +public class X509Signature extends HessianEnvelope { + private String _algorithm = "HmacSHA256"; + private X509Certificate _cert; + private PrivateKey _privateKey; + private SecureRandom _secureRandom; + + public X509Signature() + { + } + + /** + * Sets the encryption algorithm for the content. + */ + public void setAlgorithm(String algorithm) + { + if (algorithm == null) + throw new NullPointerException(); + + _algorithm = algorithm; + } + + /** + * Gets the encryption algorithm for the content. + */ + public String getAlgorithm() + { + return _algorithm; + } + + /** + * The X509 certificate to obtain the public key of the recipient. + */ + public X509Certificate getCertificate() + { + return _cert; + } + + /** + * The X509 certificate to obtain the public key of the recipient. + */ + public void setCertificate(X509Certificate cert) + { + _cert = cert; + } + + /** + * The key to obtain the private key of the recipient. + */ + public PrivateKey getPrivateKey() + { + return _privateKey; + } + + /** + * The private key. + */ + public void setPrivateKey(PrivateKey key) + { + _privateKey = key; + } + + /** + * The random number generator for the shared secrets. + */ + public SecureRandom getSecureRandom() + { + return _secureRandom; + } + + /** + * The random number generator for the shared secrets. + */ + public void setSecureRandom(SecureRandom random) + { + _secureRandom = random; + } + + public Hessian2Output wrap(Hessian2Output out) + throws IOException + { + if (_privateKey == null) + throw new IOException("X509Signature.wrap requires a private key"); + + if (_cert == null) + throw new IOException("X509Signature.wrap requires a certificate"); + + OutputStream os = new SignatureOutputStream(out); + + Hessian2Output filterOut = new Hessian2Output(os); + + filterOut.setCloseStreamOnClose(true); + + return filterOut; + } + + public Hessian2Input unwrap(Hessian2Input in) + throws IOException + { + if (_cert == null) + throw new IOException("X509Signature.unwrap requires a certificate"); + + int version = in.readEnvelope(); + + String method = in.readMethod(); + + if (! method.equals(getClass().getName())) + throw new IOException("expected hessian Envelope method '" + + getClass().getName() + "' at '" + method + "'"); + + return unwrapHeaders(in); + } + + public Hessian2Input unwrapHeaders(Hessian2Input in) + throws IOException + { + if (_cert == null) + throw new IOException("X509Signature.unwrap requires a certificate"); + + InputStream is = new SignatureInputStream(in); + + Hessian2Input filter = new Hessian2Input(is); + + filter.setCloseStreamOnClose(true); + + return filter; + } + + class SignatureOutputStream extends OutputStream { + private Hessian2Output _out; + private OutputStream _bodyOut; + private Mac _mac; + + SignatureOutputStream(Hessian2Output out) + throws IOException + { + try { + KeyGenerator keyGen = KeyGenerator.getInstance(_algorithm); + + if (_secureRandom != null) + keyGen.init(_secureRandom); + + SecretKey sharedKey = keyGen.generateKey(); + + _out = out; + + _out.startEnvelope(X509Signature.class.getName()); + + PublicKey publicKey = _cert.getPublicKey(); + + byte []encoded = publicKey.getEncoded(); + MessageDigest md = MessageDigest.getInstance("SHA1"); + md.update(encoded); + byte []fingerprint = md.digest(); + + String keyAlgorithm = _privateKey.getAlgorithm(); + Cipher keyCipher = Cipher.getInstance(keyAlgorithm); + keyCipher.init(Cipher.WRAP_MODE, _privateKey); + + byte []encKey = keyCipher.wrap(sharedKey); + + _out.writeInt(4); + _out.writeString("algorithm"); + _out.writeString(_algorithm); + _out.writeString("fingerprint"); + _out.writeBytes(fingerprint); + _out.writeString("key-algorithm"); + _out.writeString(keyAlgorithm); + _out.writeString("key"); + _out.writeBytes(encKey); + + _mac = Mac.getInstance(_algorithm); + _mac.init(sharedKey); + + _bodyOut = _out.getBytesOutputStream(); + } catch (RuntimeException e) { + throw e; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public void write(int ch) + throws IOException + { + _bodyOut.write(ch); + _mac.update((byte) ch); + } + + public void write(byte []buffer, int offset, int length) + throws IOException + { + _bodyOut.write(buffer, offset, length); + _mac.update(buffer, offset, length); + } + + public void close() + throws IOException + { + Hessian2Output out = _out; + _out = null; + + if (out == null) + return; + + _bodyOut.close(); + + byte []sig = _mac.doFinal(); + + out.writeInt(1); + out.writeString("signature"); + out.writeBytes(sig); + + out.completeEnvelope(); + out.close(); + } + } + + class SignatureInputStream extends InputStream { + private Hessian2Input _in; + + private Mac _mac; + private InputStream _bodyIn; + private CipherInputStream _cipherIn; + + SignatureInputStream(Hessian2Input in) + throws IOException + { + try { + _in = in; + + byte []fingerprint = null; + String keyAlgorithm = null; + String algorithm = null; + byte []encKey = null; + + int len = in.readInt(); + + for (int i = 0; i < len; i++) { + String header = in.readString(); + + if ("fingerprint".equals(header)) + fingerprint = in.readBytes(); + else if ("key-algorithm".equals(header)) + keyAlgorithm = in.readString(); + else if ("algorithm".equals(header)) + algorithm = in.readString(); + else if ("key".equals(header)) + encKey = in.readBytes(); + else + throw new IOException("'" + header + "' is an unexpected header"); + } + + Cipher keyCipher = Cipher.getInstance(keyAlgorithm); + keyCipher.init(Cipher.UNWRAP_MODE, _cert); + + Key key = keyCipher.unwrap(encKey, algorithm, Cipher.SECRET_KEY); + _bodyIn = _in.readInputStream(); + + _mac = Mac.getInstance(algorithm); + _mac.init(key); + } catch (RuntimeException e) { + throw e; + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public int read() + throws IOException + { + int ch = _bodyIn.read(); + + if (ch < 0) + return ch; + + _mac.update((byte) ch); + + return ch; + } + + public int read(byte []buffer, int offset, int length) + throws IOException + { + int len = _bodyIn.read(buffer, offset, length); + + if (len < 0) + return len; + + _mac.update(buffer, offset, len); + + return len; + } + + public void close() + throws IOException + { + Hessian2Input in = _in; + _in = null; + + if (in != null) { + _bodyIn.close(); + + int len = in.readInt(); + byte []signature = null; + + for (int i = 0; i < len; i++) { + String header = in.readString(); + + if ("signature".equals(header)) + signature = in.readBytes(); + } + + in.completeEnvelope(); + in.close(); + + + if (signature == null) + throw new IOException("Expected signature"); + + byte []sig = _mac.doFinal(); + + if (sig.length != signature.length) + throw new IOException("mismatched signature"); + + for (int i = 0; i < sig.length; i++) { + if (signature[i] != sig[i]) + throw new IOException("mismatched signature"); + } + + // XXX: save principal + } + } + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/util/IdentityIntMap.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/util/IdentityIntMap.java new file mode 100644 index 000000000000..a17908952c7d --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/util/IdentityIntMap.java @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.util; + +/** + * The IntMap provides a simple hashmap from keys to integers. The API is + * an abbreviation of the HashMap collection API. + * + *

The convenience of IntMap is avoiding all the silly wrapping of + * integers. + */ +public class IdentityIntMap { + /** + * Encoding of a null entry. Since NULL is equal to Integer.MIN_VALUE, + * it's impossible to distinguish between the two. + */ + public final static int NULL = 0xdeadbeef; // Integer.MIN_VALUE + 1; + + private static final Object DELETED = new Object(); + + private Object []_keys; + private int []_values; + + private int _size; + private int _mask; + + /** + * Create a new IntMap. Default size is 16. + */ + public IdentityIntMap() + { + _keys = new Object[256]; + _values = new int[256]; + + _mask = _keys.length - 1; + _size = 0; + } + + /** + * Clear the hashmap. + */ + public void clear() + { + Object []keys = _keys; + int []values = _values; + + for (int i = keys.length - 1; i >= 0; i--) { + keys[i] = null; + values[i] = 0; + } + + _size = 0; + } + /** + * Returns the current number of entries in the map. + */ + public int size() + { + return _size; + } + + /** + * Puts a new value in the property table with the appropriate flags + */ + public int get(Object key) + { + int mask = _mask; + int hash = System.identityHashCode(key) % mask & mask; + + Object []keys = _keys; + + while (true) { + Object mapKey = keys[hash]; + + if (mapKey == null) + return NULL; + else if (mapKey == key) + return _values[hash]; + + hash = (hash + 1) % mask; + } + } + + /** + * Expands the property table + */ + private void resize(int newSize) + { + Object []newKeys = new Object[newSize]; + int []newValues = new int[newSize]; + + int mask = _mask = newKeys.length - 1; + + Object []keys = _keys; + int values[] = _values; + + for (int i = keys.length - 1; i >= 0; i--) { + Object key = keys[i]; + + if (key == null || key == DELETED) + continue; + + int hash = System.identityHashCode(key) % mask & mask; + + while (true) { + if (newKeys[hash] == null) { + newKeys[hash] = key; + newValues[hash] = values[i]; + break; + } + + hash = (hash + 1) % mask; + } + } + + _keys = newKeys; + _values = newValues; + } + + /** + * Puts a new value in the property table with the appropriate flags + */ + public int put(Object key, int value) + { + int mask = _mask; + int hash = System.identityHashCode(key) % mask & mask; + + Object []keys = _keys; + + while (true) { + Object testKey = keys[hash]; + + if (testKey == null || testKey == DELETED) { + keys[hash] = key; + _values[hash] = value; + + _size++; + + if (keys.length <= 4 * _size) + resize(4 * keys.length); + + return NULL; + } + else if (key != testKey) { + hash = (hash + 1) % mask; + + continue; + } + else { + int old = _values[hash]; + + _values[hash] = value; + + return old; + } + } + } + + /** + * Deletes the entry. Returns true if successful. + */ + public int remove(Object key) + { + int mask = _mask; + int hash = System.identityHashCode(key) % mask & mask; + + while (true) { + Object mapKey = _keys[hash]; + + if (mapKey == null) + return NULL; + else if (mapKey == key) { + _keys[hash] = DELETED; + + _size--; + + return _values[hash]; + } + + hash = (hash + 1) % mask; + } + } + + public String toString() + { + StringBuffer sbuf = new StringBuffer(); + + sbuf.append("IntMap["); + boolean isFirst = true; + + for (int i = 0; i <= _mask; i++) { + if (_keys[i] != null && _keys[i] != DELETED) { + if (! isFirst) + sbuf.append(", "); + + isFirst = false; + sbuf.append(_keys[i]); + sbuf.append(":"); + sbuf.append(_values[i]); + } + } + sbuf.append("]"); + + return sbuf.toString(); + } +} diff --git a/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/util/IntMap.java b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/util/IntMap.java new file mode 100644 index 000000000000..c84bbd4dc571 --- /dev/null +++ b/hessian-lite/src/main/java/com/alibaba/com/caucho/hessian/util/IntMap.java @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved. + * + * The Apache Software License, Version 1.1 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. The end-user documentation included with the redistribution, if + * any, must include the following acknowlegement: + * "This product includes software developed by the + * Caucho Technology (http://www.caucho.com/)." + * Alternately, this acknowlegement may appear in the software itself, + * if and wherever such third-party acknowlegements normally appear. + * + * 4. The names "Burlap", "Resin", and "Caucho" must not be used to + * endorse or promote products derived from this software without prior + * written permission. For written permission, please contact + * info@caucho.com. + * + * 5. Products derived from this software may not be called "Resin" + * nor may "Resin" appear in their names without prior written + * permission of Caucho Technology. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN + * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * @author Scott Ferguson + */ + +package com.alibaba.com.caucho.hessian.util; + +/** + * The IntMap provides a simple hashmap from keys to integers. The API is + * an abbreviation of the HashMap collection API. + * + *

The convenience of IntMap is avoiding all the silly wrapping of + * integers. + */ +public class IntMap { + /** + * Encoding of a null entry. Since NULL is equal to Integer.MIN_VALUE, + * it's impossible to distinguish between the two. + */ + public final static int NULL = 0xdeadbeef; // Integer.MIN_VALUE + 1; + + private static final Object DELETED = new Object(); + + private Object []_keys; + private int []_values; + + private int _size; + private int _mask; + + /** + * Create a new IntMap. Default size is 16. + */ + public IntMap() + { + _keys = new Object[256]; + _values = new int[256]; + + _mask = _keys.length - 1; + _size = 0; + } + + /** + * Clear the hashmap. + */ + public void clear() + { + Object []keys = _keys; + int []values = _values; + + for (int i = keys.length - 1; i >= 0; i--) { + keys[i] = null; + values[i] = 0; + } + + _size = 0; + } + /** + * Returns the current number of entries in the map. + */ + public int size() + { + return _size; + } + + /** + * Puts a new value in the property table with the appropriate flags + */ + public int get(Object key) + { + int mask = _mask; + int hash = key.hashCode() % mask & mask; + + Object []keys = _keys; + + while (true) { + Object mapKey = keys[hash]; + + if (mapKey == null) + return NULL; + else if (mapKey == key || mapKey.equals(key)) + return _values[hash]; + + hash = (hash + 1) % mask; + } + } + + /** + * Expands the property table + */ + private void resize(int newSize) + { + Object []newKeys = new Object[newSize]; + int []newValues = new int[newSize]; + + int mask = _mask = newKeys.length - 1; + + Object []keys = _keys; + int values[] = _values; + + for (int i = keys.length - 1; i >= 0; i--) { + Object key = keys[i]; + + if (key == null || key == DELETED) + continue; + + int hash = key.hashCode() % mask & mask; + + while (true) { + if (newKeys[hash] == null) { + newKeys[hash] = key; + newValues[hash] = values[i]; + break; + } + + hash = (hash + 1) % mask; + } + } + + _keys = newKeys; + _values = newValues; + } + + /** + * Puts a new value in the property table with the appropriate flags + */ + public int put(Object key, int value) + { + int mask = _mask; + int hash = key.hashCode() % mask & mask; + + Object []keys = _keys; + + while (true) { + Object testKey = keys[hash]; + + if (testKey == null || testKey == DELETED) { + keys[hash] = key; + _values[hash] = value; + + _size++; + + if (keys.length <= 4 * _size) + resize(4 * keys.length); + + return NULL; + } + else if (key != testKey && ! key.equals(testKey)) { + hash = (hash + 1) % mask; + + continue; + } + else { + int old = _values[hash]; + + _values[hash] = value; + + return old; + } + } + } + + /** + * Deletes the entry. Returns true if successful. + */ + public int remove(Object key) + { + int mask = _mask; + int hash = key.hashCode() % mask & mask; + + while (true) { + Object mapKey = _keys[hash]; + + if (mapKey == null) + return NULL; + else if (mapKey == key) { + _keys[hash] = DELETED; + + _size--; + + return _values[hash]; + } + + hash = (hash + 1) % mask; + } + } + + public String toString() + { + StringBuffer sbuf = new StringBuffer(); + + sbuf.append("IntMap["); + boolean isFirst = true; + + for (int i = 0; i <= _mask; i++) { + if (_keys[i] != null && _keys[i] != DELETED) { + if (! isFirst) + sbuf.append(", "); + + isFirst = false; + sbuf.append(_keys[i]); + sbuf.append(":"); + sbuf.append(_values[i]); + } + } + sbuf.append("]"); + + return sbuf.toString(); + } +} diff --git a/pom.xml b/pom.xml index 308901ddcfa4..7cdbfb61a0f8 100644 --- a/pom.xml +++ b/pom.xml @@ -16,11 +16,12 @@ 4.0.0 - + + com.alibaba dubbo-parent 2.5.4-SNAPSHOT pom @@ -54,6 +55,7 @@ dubbo-simple dubbo-admin dubbo-demo + hessian-lite @@ -131,6 +133,18 @@ Copyright 1999-2012 Alibaba Group. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. oss + + + 2.3.2 + 1.5 + 1.5 + UTF-8 + + 2.1.1 + 2.3.2 + 2.1.1 + 2.3.1 + 2.7 @@ -450,19 +464,44 @@ + + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven_jar_plugin_version} + + + org.apache.maven.plugins + maven-war-plugin + ${maven_war_plugin_version} + + + org.apache.maven.plugins + maven-install-plugin + ${maven_install_plugin_version} + + + org.apache.maven.plugins + maven-deploy-plugin + ${maven_deploy_plugin_version} + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven_compiler_plugin_version} + + ${java_source_version} + ${java_target_version} + ${file_encoding} + + + + + - - - opensesame.releases - http://code.alibabatech.com/mvn/releases - - true - - - false - - - + jira http://code.alibabatech.com/jira/browse/DUBBO From 2dcf4189c305f52ab1cb25b3cf44b07ec3828458 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Fri, 17 Oct 2014 19:14:24 +0800 Subject: [PATCH 105/200] initial check-in for RESTful remoting, Kryo/FST serialization, Spring/ZkClient upgrade, etc --- dubbo-admin/pom.xml | 8 +- dubbo-cluster/pom.xml | 2 +- dubbo-common/pom.xml | 111 +++--- .../com/alibaba/dubbo/common/Constants.java | 12 + .../alibaba/dubbo/common/json/J2oVisitor.java | 24 +- ...ibaba.dubbo.common.serialize.Serialization | 4 +- dubbo-config/dubbo-config-api/pom.xml | 37 +- .../alibaba/dubbo/config/ProtocolConfig.java | 34 ++ .../alibaba/dubbo/config/ServiceConfig.java | 2 + dubbo-config/dubbo-config-spring/pom.xml | 53 ++- .../src/main/resources/META-INF/dubbo.xsd | 22 ++ dubbo-config/pom.xml | 2 +- dubbo-container/dubbo-container-api/pom.xml | 6 +- dubbo-container/dubbo-container-jetty/pom.xml | 2 +- dubbo-container/dubbo-container-log4j/pom.xml | 2 +- .../dubbo-container-logback/pom.xml | 2 +- .../dubbo-container-spring/pom.xml | 12 +- dubbo-container/pom.xml | 2 +- dubbo-demo/dubbo-demo-api/pom.xml | 18 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 322 +++++++++--------- .../dubbo/demo/consumer/DemoAction.java | 77 ++++- .../META-INF/spring/dubbo-demo-action.xml | 5 +- .../META-INF/spring/dubbo-demo-consumer.xml | 27 +- dubbo-demo/dubbo-demo-provider/pom.xml | 290 ++++++++-------- .../META-INF/spring/dubbo-demo-provider.xml | 64 +++- .../dubbo/demo/provider/DemoProvider.java | 14 +- dubbo-demo/pom.xml | 2 +- dubbo-filter/dubbo-filter-cache/pom.xml | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 2 +- dubbo-filter/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +- dubbo-monitor/pom.xml | 2 +- dubbo-registry/dubbo-registry-api/pom.xml | 2 +- dubbo-registry/dubbo-registry-default/pom.xml | 2 +- .../dubbo-registry-multicast/pom.xml | 2 +- dubbo-registry/dubbo-registry-redis/pom.xml | 12 +- .../dubbo-registry-zookeeper/pom.xml | 2 +- dubbo-registry/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +- .../exchange/codec/ExchangeCodec.java | 50 ++- .../transport/codec/TransportCodec.java | 17 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 2 +- .../remoting/http/jetty/JettyHttpServer.java | 33 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-p2p/pom.xml | 2 +- .../dubbo-remoting-zookeeper/pom.xml | 4 +- .../curator/CuratorZookeeperClient.java | 92 ++--- dubbo-remoting/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-default/pom.xml | 2 +- .../dubbo/DecodeableRpcInvocation.java | 108 ++++-- .../protocol/dubbo/DecodeableRpcResult.java | 62 ++-- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 12 +- .../rpc/protocol/dubbo/DubboProtocol.java | 50 ++- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 14 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +- .../internal/com.alibaba.dubbo.rpc.Protocol | 2 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 12 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 12 +- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 8 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 8 +- dubbo-rpc/pom.xml | 3 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 8 +- .../src/test/resources/dubbo.properties | 4 +- dubbo-simple/dubbo-registry-simple/pom.xml | 2 +- dubbo-simple/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark/pom.xml | 2 +- dubbo-test/dubbo-test-compatibility/pom.xml | 2 +- dubbo-test/dubbo-test-examples/pom.xml | 2 +- dubbo-test/dubbo-test-integration/pom.xml | 2 +- dubbo-test/pom.xml | 7 +- dubbo/pom.xml | 10 +- hessian-lite/pom.xml | 2 +- pom.xml | 172 ++++++---- 79 files changed, 1163 insertions(+), 753 deletions(-) diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index 44ce306a6943..85a271ced58d 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.4-SNAPSHOT + 2.8.0 dubbo-admin war @@ -41,10 +41,6 @@ com.alibaba.citrus citrus-webx-all - - org.springframework - spring - org.javassist javassist @@ -86,7 +82,7 @@ zkclient - com.netflix.curator + org.apache.curator curator-framework diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index 1e9edf86e747..ae5cb68f1263 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.4-SNAPSHOT + 2.8.0 dubbo-cluster jar diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index 26e31c1e7c2e..9189c0c77307 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -14,57 +14,72 @@ - limitations under the License. --> - 4.0.0 - - com.alibaba - dubbo-parent - 2.5.4-SNAPSHOT - - dubbo-common - jar - ${project.artifactId} - The common module of dubbo project - - true - - - - org.slf4j - slf4j-api - provided - - - commons-logging - commons-logging-api - provided - - - log4j - log4j - - - org.javassist - javassist - - - com.alibaba - hessian-lite - - - com.alibaba - fastjson - provided - - - org.jvnet.sorcerer - sorcerer-javac - provided - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + + com.alibaba + dubbo-parent + 2.8.0 + + dubbo-common + jar + ${project.artifactId} + The common module of dubbo project + + true + + + + org.slf4j + slf4j-api + provided + + + commons-logging + commons-logging-api + provided + + + log4j + log4j + + + org.javassist + javassist + + + com.alibaba + hessian-lite + + + com.alibaba + fastjson + provided + + + org.jvnet.sorcerer + sorcerer-javac + provided + cglib cglib-nodep test - + + com.esotericsoftware.kryo + kryo + 2.24.0 + + + de.javakaffee + kryo-serializers + 0.26 + + + de.ruedigermoeller + fst + 1.55 + + \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java index 7909a7e59e2e..cf80fae5da8f 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -118,6 +118,8 @@ public class Constants { public static final int DEFAULT_THREADS = 200; + public static final boolean DEFAULT_KEEP_ALIVE = true; + public static final int DEFAULT_QUEUES = 0; public static final int DEFAULT_ALIVE = 60 * 1000; @@ -260,6 +262,16 @@ public class Constants { public static final String SERIALIZATION_KEY = "serialization"; + // modified by lishen + public static final String EXTENSION_KEY = "extension"; + + // modified by lishen + public static final String KEEP_ALIVE_KEY = "keepalive"; + + // modified by lishen + // TODO change to a better name + public static final String OPTIMIZER_KEY = "optimizer"; + public static final String EXCHANGER_KEY = "exchanger"; public static final String TRANSPORTER_KEY = "transporter"; diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/J2oVisitor.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/J2oVisitor.java index 132d5eff2f40..1b378e09af0c 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/J2oVisitor.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/J2oVisitor.java @@ -165,17 +165,19 @@ public void objectItemValue(Object obj, boolean isValue) throws ParseException } } if (mValue instanceof Throwable && "message".equals(name)) { - try { - Field field = Throwable.class.getDeclaredField("detailMessage"); - if (! field.isAccessible()) { - field.setAccessible(true); - } - field.set(mValue, obj); - } catch (NoSuchFieldException e) { - throw new ParseException(StringUtils.toString(e)); - } catch (IllegalAccessException e) { - throw new ParseException(StringUtils.toString(e)); - } + try { + Field field = Throwable.class.getDeclaredField("detailMessage"); + if (!field.isAccessible()) { + field.setAccessible(true); + } + field.set(mValue, obj); + } catch (NoSuchFieldException e) { + throw new ParseException(StringUtils.toString(e)); + } catch (IllegalAccessException e) { + throw new ParseException(StringUtils.toString(e)); + } + } else if (mValue instanceof Throwable && "suppressed".equals(name)) { // modified by lishen + // simply ignore this field for jdk 1.7+ } else if (! CLASS_PROPERTY.equals(name)) { mWrapper.setPropertyValue(mValue, name, obj); } diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization b/dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization index ca493e457992..c47c91c40bae 100644 --- a/dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization +++ b/dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization @@ -4,4 +4,6 @@ java=com.alibaba.dubbo.common.serialize.support.java.JavaSerialization compactedjava=com.alibaba.dubbo.common.serialize.support.java.CompactedJavaSerialization json=com.alibaba.dubbo.common.serialize.support.json.JsonSerialization fastjson=com.alibaba.dubbo.common.serialize.support.json.FastJsonSerialization -nativejava=com.alibaba.dubbo.common.serialize.support.nativejava.NativeJavaSerialization \ No newline at end of file +nativejava=com.alibaba.dubbo.common.serialize.support.nativejava.NativeJavaSerialization +kryo=com.alibaba.dubbo.common.serialize.support.kryo.KryoSerialization +fst=com.alibaba.dubbo.common.serialize.support.fst.FstSerialization \ No newline at end of file diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 4affbcc72a91..06cfd4be0631 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -1,12 +1,12 @@ - + + \ No newline at end of file diff --git a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd index 65df01c96ff9..d0168856cd42 100644 --- a/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd +++ b/dubbo-config/dubbo-config-spring/src/main/resources/META-INF/dubbo.xsd @@ -778,6 +778,28 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index ed2a84959cc9..ee05f2f2a41f 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.4-SNAPSHOT + 2.8.0 dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index 342964ed50a6..df12441401f5 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.4-SNAPSHOT + 2.8.0 dubbo-container-api jar @@ -38,10 +38,6 @@ org.mortbay.jetty jetty - - org.springframework - spring - diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index 31811b18ed2d..197043c8b216 100644 --- a/dubbo-container/dubbo-container-jetty/pom.xml +++ b/dubbo-container/dubbo-container-jetty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.4-SNAPSHOT + 2.8.0 dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index adea3aa7e96a..b43cc72bb2a2 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.4-SNAPSHOT + 2.8.0 dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index 20493bae530b..013ffe08e337 100644 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ b/dubbo-container/dubbo-container-logback/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.5.4-SNAPSHOT + 2.8.0 dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index 30a7a299d68b..e87dda5a01a2 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -1,12 +1,12 @@ - 4.0.0 - - com.alibaba - dubbo-demo - 2.5.4-SNAPSHOT - - dubbo-demo-consumer - jar - ${project.artifactId} - The demo consumer module of dubbo project - - false - - - - com.alibaba - dubbo-demo-api - ${project.parent.version} - - - com.alibaba - dubbo - ${project.parent.version} - - - org.springframework - spring - - - org.javassist - javassist - - - org.jboss.netty - netty - - - org.apache.mina - mina-core - - - org.glassfish.grizzly - grizzly-core - - - org.apache.httpcomponents - httpclient - - - com.alibaba - fastjson - - - com.thoughtworks.xstream - xstream - - - org.apache.bsf - bsf-api - - - org.apache.zookeeper - zookeeper - - - com.github.sgroschupf - zkclient - - - com.netflix.curator - curator-framework - - - com.googlecode.xmemcached - xmemcached - - - org.apache.cxf - cxf-rt-frontend-simple - - - org.apache.cxf - cxf-rt-transports-http - - - org.apache.thrift - libthrift - - - com.caucho - hessian - - - javax.servlet - servlet-api - - - org.mortbay.jetty - jetty - - - log4j - log4j - - - org.slf4j - slf4j-api - - - redis.clients - jedis - - - javax.validation - validation-api - - - org.hibernate - hibernate-validator - - - javax.cache - cache-api - - - - - - maven-dependency-plugin - - - unpack - package - - unpack - - - - - com.alibaba - dubbo - ${project.parent.version} - ${project.build.directory}/dubbo - META-INF/assembly/** - - - - - - - - maven-assembly-plugin + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + + com.alibaba + dubbo-demo + 2.8.0 + + dubbo-demo-consumer + jar + ${project.artifactId} + The demo consumer module of dubbo project + + false + + + + com.alibaba + dubbo-demo-api + ${project.parent.version} + + + com.alibaba + dubbo + ${project.parent.version} + + + org.javassist + javassist + + + org.jboss.netty + netty + + + org.apache.mina + mina-core + + + org.glassfish.grizzly + grizzly-core + + + org.apache.httpcomponents + httpclient + + + com.alibaba + fastjson + + + com.thoughtworks.xstream + xstream + + + org.apache.bsf + bsf-api + + + org.apache.zookeeper + zookeeper + + + com.github.sgroschupf + zkclient + + + org.apache.curator + curator-framework + + + com.googlecode.xmemcached + xmemcached + + + org.apache.cxf + cxf-rt-frontend-simple + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.thrift + libthrift + + + com.caucho + hessian + + + javax.servlet + servlet-api + + + org.mortbay.jetty + jetty + + + log4j + log4j + + + org.slf4j + slf4j-api + + + redis.clients + jedis + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + javax.cache + cache-api + + + + + + maven-dependency-plugin + + + unpack + package + + unpack + + + + + com.alibaba + dubbo + ${project.parent.version} + ${project.build.directory}/dubbo + META-INF/assembly/** + + + + + + + + maven-assembly-plugin src/main/assembly/assembly.xml - - make-assembly - package - - single - - - + + make-assembly + package + + single + + + - - + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java index 5258feb6e78f..f71b5761c39b 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java +++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java @@ -15,29 +15,72 @@ */ package com.alibaba.dubbo.demo.consumer; -import java.text.SimpleDateFormat; -import java.util.Date; +import java.util.ArrayList; +import java.util.List; -import com.alibaba.dubbo.demo.DemoService; +import com.alibaba.dubbo.demo.bid.*; +import com.alibaba.dubbo.demo.user.User; +import com.alibaba.dubbo.demo.user.facade.AnotherUserRestService; public class DemoAction { - - private DemoService demoService; - public void setDemoService(DemoService demoService) { - this.demoService = demoService; + private BidService bidService; + + private AnotherUserRestService anotherUserRestService; + + public void setBidService(BidService bidService) { + this.bidService = bidService; + } + + public void setAnotherUserRestService(AnotherUserRestService anotherUserRestService) { + this.anotherUserRestService = anotherUserRestService; } - public void start() throws Exception { - for (int i = 0; i < Integer.MAX_VALUE; i ++) { - try { - String hello = demoService.sayHello("world" + i); - System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] " + hello); - } catch (Exception e) { - e.printStackTrace(); - } - Thread.sleep(2000); + public void start() throws Exception { + BidRequest request = new BidRequest(); + + Impression imp = new Impression(); + imp.setBidFloor(1.1); + imp.setId("abc"); + List imps = new ArrayList(1); + imps.add(imp); + request.setImpressions(imps); + + Geo geo = new Geo(); + geo.setCity("beijing"); + geo.setCountry("china"); + geo.setLat(100.1f); + geo.setLon(100.1f); + + Device device = new Device(); + device.setMake("apple"); + device.setOs("ios"); + device.setVersion("7.0"); + device.setLang("zh_CN"); + device.setModel("iphone"); + device.setGeo(geo); + request.setDevice(device); + +// long start = System.currentTimeMillis(); + +// for (int i = 0; i < 10000; i ++) { +// System.out.println(bidService.bid(request).getId()); + System.out.println("SUCESS: got bid response id: " + bidService.bid(request).getId()); +// } + +// System.out.println(">>>>> Total time consumed:" + (System.currentTimeMillis() - start)); + + try { + bidService.throwNPE(); + System.out.println("ERROR: no exception found"); + } catch (NullPointerException e) { + System.out.println("SUCCESS: caught exception " + e.getClass()); } - } + + User user = new User(1L, "dang"); + System.out.println("SUCESS: registered user with id " + anotherUserRestService.registerUser(user).getId()); + + System.out.println("SUCESS: got user " + anotherUserRestService.getUser(1L)); + } } \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-action.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-action.xml index 365bafb80a67..fb7662ca0002 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-action.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-action.xml @@ -20,8 +20,9 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> - - + + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index 981599fb175d..49ff527e1fe5 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -1,25 +1,20 @@ - - + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml index c7970f1239e8..9a74589aa796 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -19,10 +19,10 @@ com.alibaba dubbo-demo - 2.5.4-SNAPSHOT + 2.8.0 dubbo-demo-provider - jar + war ${project.artifactId} The demo provider module of dubbo project @@ -39,147 +39,149 @@ dubbo ${project.parent.version} - - org.springframework - spring - - - org.javassist - javassist - - - org.jboss.netty - netty - - - org.apache.mina - mina-core - - - org.glassfish.grizzly - grizzly-core - - - org.apache.httpcomponents - httpclient - - - com.alibaba - fastjson - - - com.thoughtworks.xstream - xstream - - - org.apache.bsf - bsf-api - - - org.apache.zookeeper - zookeeper - - - com.github.sgroschupf - zkclient - - - com.netflix.curator - curator-framework - - - com.googlecode.xmemcached - xmemcached - - - org.apache.cxf - cxf-rt-frontend-simple - - - org.apache.cxf - cxf-rt-transports-http - - - org.apache.thrift - libthrift - - - com.caucho - hessian - - - javax.servlet - servlet-api - - - org.mortbay.jetty - jetty - - - log4j - log4j - - - org.slf4j - slf4j-api - - - redis.clients - jedis - - - javax.validation - validation-api - - - org.hibernate - hibernate-validator - - - javax.cache - cache-api - + + org.javassist + javassist + + + org.jboss.netty + netty + + + org.apache.mina + mina-core + + + org.glassfish.grizzly + grizzly-core + + + org.apache.httpcomponents + httpclient + + + com.alibaba + fastjson + + + com.thoughtworks.xstream + xstream + + + org.apache.bsf + bsf-api + + + org.apache.zookeeper + zookeeper + + + com.github.sgroschupf + zkclient + + + org.apache.curator + curator-framework + + + com.googlecode.xmemcached + xmemcached + + + org.apache.cxf + cxf-rt-frontend-simple + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.thrift + libthrift + + + com.caucho + hessian + + + javax.servlet + servlet-api + + + org.mortbay.jetty + jetty + + + log4j + log4j + + + org.slf4j + slf4j-api + + + redis.clients + jedis + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + javax.cache + cache-api + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + - - - - maven-dependency-plugin - - - unpack - package - - unpack - - - - - com.alibaba - dubbo - ${project.parent.version} - ${project.build.directory}/dubbo - META-INF/assembly/** - - - - - - - - maven-assembly-plugin - - src/main/assembly/assembly.xml - - - - make-assembly - package - - single - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index ea8026b6ed86..d9ce8dc42a9a 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -19,9 +19,63 @@ xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/test/java/com/alibaba/dubbo/demo/provider/DemoProvider.java b/dubbo-demo/dubbo-demo-provider/src/test/java/com/alibaba/dubbo/demo/provider/DemoProvider.java index 31850ef4bfcc..b00688c9efc3 100644 --- a/dubbo-demo/dubbo-demo-provider/src/test/java/com/alibaba/dubbo/demo/provider/DemoProvider.java +++ b/dubbo-demo/dubbo-demo-provider/src/test/java/com/alibaba/dubbo/demo/provider/DemoProvider.java @@ -15,10 +15,22 @@ */ package com.alibaba.dubbo.demo.provider; +import com.alibaba.dubbo.config.ProtocolConfig; + public class DemoProvider { public static void main(String[] args) { +// new Thread(new Runnable() { +// public void run() { +// try { +// Thread.sleep(20000); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// ProtocolConfig.destroyAll(); +// } +// }).start(); com.alibaba.dubbo.container.Main.main(args); - } + } } \ No newline at end of file diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index 05b065c72193..cb6a89d08cb0 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.4-SNAPSHOT + 2.8.0 dubbo-demo pom diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index c5fb69531609..972ec28d5990 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.4-SNAPSHOT + 2.8.0 dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index 43af3825095a..502a38d8ead4 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.5.4-SNAPSHOT + 2.8.0 dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index 8a50206a4dbe..f943e4b7b9b0 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.4-SNAPSHOT + 2.8.0 dubbo-filter pom diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index 19df1ae264a0..e251779d84ff 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.4-SNAPSHOT + 2.8.0 dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index a4e398bcd3fd..2f3a96937208 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.5.4-SNAPSHOT + 2.8.0 dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index a5c516f6aeea..522dbd72981a 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.5.4-SNAPSHOT + 2.8.0 dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 21e51e1df39c..8bccba3b8a7b 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.4-SNAPSHOT + 2.8.0 dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index 616cd82a01a3..d7b902b861f9 100644 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ b/dubbo-registry/dubbo-registry-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.4-SNAPSHOT + 2.8.0 dubbo-registry-default jar diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index 31f9e46bf7c7..149035f3cb2d 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.5.4-SNAPSHOT + 2.8.0 dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index 89480310c53c..5ecb5b09aecd 100644 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ b/dubbo-registry/dubbo-registry-redis/pom.xml @@ -1,12 +1,12 @@ - com.alibaba + + com.alibaba dubbo-parent - 2.5.4-SNAPSHOT + 2.8.0 pom ${project.artifactId} The parent project of dubbo @@ -52,10 +49,10 @@ dubbo-monitor dubbo-config dubbo - dubbo-simple - dubbo-admin - dubbo-demo - hessian-lite + dubbo-simple + dubbo-admin + dubbo-demo + hessian-lite @@ -86,12 +83,12 @@ - 2.5.6.SEC03 + 3.2.9.RELEASE 3.15.0-GA 3.2.5.Final 1.1.7 2.1.4 - 4.1.2 + 4.2.1 3.2.1-fixed-2 1.4.1 1.1.39 @@ -99,7 +96,7 @@ 0.8 3.3.3 0.1 - 1.1.16 + 2.5.0 2.1.0 1.3.6 2.6.1 @@ -125,34 +122,36 @@ 3.0 0.999.8 - + false true ${file_encoding} - + Copyright 1999-2012 Alibaba Group. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. oss - - 2.3.2 - 1.5 - 1.5 - UTF-8 + + 2.3.2 + 1.6 + 1.6 + UTF-8 - 2.1.1 - 2.3.2 - 2.1.1 - 2.3.1 - 2.7 + 2.1.1 + 2.3.2 + 2.1.1 + 2.3.1 + 2.7 org.springframework - spring - ${spring_version} + spring-framework-bom + ${spring.bom.version} + pom + import org.javassist @@ -215,7 +214,7 @@ ${zkclient_version} - com.netflix.curator + org.apache.curator curator-framework ${curator_version} @@ -350,6 +349,11 @@ cglib-nodep ${cglib_version} + + commons-pool + commons-pool + 1.6 + @@ -365,7 +369,7 @@ org.easymock easymockclassextension - + com.googlecode.jmockit jmockit @@ -465,40 +469,72 @@ - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven_jar_plugin_version} - - - org.apache.maven.plugins - maven-war-plugin - ${maven_war_plugin_version} - - - org.apache.maven.plugins - maven-install-plugin - ${maven_install_plugin_version} - - - org.apache.maven.plugins - maven-deploy-plugin - ${maven_deploy_plugin_version} - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven_compiler_plugin_version} - - ${java_source_version} - ${java_target_version} - ${file_encoding} - - - - + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven_jar_plugin_version} + + + org.apache.maven.plugins + maven-war-plugin + ${maven_war_plugin_version} + + + org.apache.maven.plugins + maven-install-plugin + ${maven_install_plugin_version} + + + org.apache.maven.plugins + maven-deploy-plugin + ${maven_deploy_plugin_version} + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven_compiler_plugin_version} + + ${java_source_version} + ${java_target_version} + ${file_encoding} + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + + org.apache.maven.plugins + + + maven-dependency-plugin + + + [2.1,) + + + unpack + + + + + + + + + + + + From 280e77bd973185bd88f8cdf68705be42550be5e1 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Fri, 17 Oct 2014 19:24:12 +0800 Subject: [PATCH 106/200] initial check-in for RESTful remoting, Kryo/FST serialization, Spring/ZkClient upgrade, etc --- .../dubbo/common/serialize/Cleanable.java | 24 + .../serialize/OptimizedSerialization.java | 24 + .../support/SerializableClassRegistry.java | 23 + .../support/SerializationOptimizer.java | 13 + .../serialize/support/fst/FstFactory.java | 53 + .../serialize/support/fst/FstObjectInput.java | 95 + .../support/fst/FstObjectOutput.java | 92 + .../support/fst/FstSerialization.java | 47 + .../support/kryo/CompatibleKryo.java | 45 + .../serialize/support/kryo/KryoFactory.java | 142 + .../support/kryo/KryoObjectInput.java | 158 + .../support/kryo/KryoObjectOutput.java | 102 + .../support/kryo/KryoSerialization.java | 49 + .../support/kryo/PooledKryoFactory.java | 47 + .../support/kryo/PrototypeKryoFactory.java | 28 + .../support/kryo/ReflectionUtils.java | 31 + .../support/kryo/SingletonKryoFactory.java | 37 + .../support/kryo/ThreadLocalKryoFactory.java | 35 + .../serialization/FstSerializationTest.java | 13 + .../serialization/KyroSerializationTest.java | 13 + .../serialization/ReflectionUtilsTest.java | 34 + .../demo/SerializationOptimizerImpl.java | 49 + .../alibaba/dubbo/demo/bid/BidRequest.java | 55 + .../alibaba/dubbo/demo/bid/BidResponse.java | 44 + .../alibaba/dubbo/demo/bid/BidService.java | 23 + .../com/alibaba/dubbo/demo/bid/Device.java | 79 + .../java/com/alibaba/dubbo/demo/bid/Geo.java | 61 + .../alibaba/dubbo/demo/bid/Impression.java | 43 + .../com/alibaba/dubbo/demo/bid/SeatBid.java | 44 + .../demo/extension/ClientTraceFilter.java | 36 + .../demo/extension/DynamicTraceBinding.java | 30 + .../extension/DynamicTraceInterceptor.java | 42 + .../dubbo/demo/extension/TraceFilter.java | 39 + .../demo/extension/TraceInterceptor.java | 42 + .../dubbo/demo/hello/HelloService.java | 23 + .../com/alibaba/dubbo/demo/user/User.java | 67 + .../alibaba/dubbo/demo/user/UserService.java | 25 + .../user/facade/AnotherUserRestService.java | 43 + .../demo/user/facade/RegistrationResult.java | 45 + .../demo/user/facade/UserRestService.java | 38 + .../dubbo/demo/consumer/RestClient.java | 104 + .../dubbo/demo/bid/BidServiceImpl.java | 43 + .../dubbo/demo/hello/HelloServiceImpl.java | 26 + .../dubbo/demo/user/UserServiceImpl.java | 36 + .../AnnotationDrivenUserRestServiceImpl.java | 63 + .../facade/AnotherUserRestServiceImpl.java | 39 + .../demo/user/facade/UserRestServiceImpl.java | 61 + .../src/main/resources/log4j.xml | 28 + .../src/main/webapp/WEB-INF/web.xml | 30 + .../http/servlet/BootstrapListener.java | 35 + .../remoting/http/servlet/ServletManager.java | 51 + .../dubbo/rpc/protocol/ServiceImplHolder.java | 30 + dubbo-rpc/dubbo-rpc-rest/pom.xml | 121 + .../src/main/java/Acme/Serve/Serve.java | 5549 +++++++++++++++++ .../rpc/protocol/rest/BaseRestServer.java | 62 + .../rpc/protocol/rest/DubboHttpServer.java | 123 + .../protocol/rest/DubboResourceFactory.java | 71 + .../dubbo/rpc/protocol/rest/NettyServer.java | 47 + .../dubbo/rpc/protocol/rest/RestProtocol.java | 146 + .../dubbo/rpc/protocol/rest/RestServer.java | 35 + .../rpc/protocol/rest/RestServerFactory.java | 48 + .../rpc/protocol/rest/RpcContextFilter.java | 38 + .../rpc/protocol/rest/SunHttpServer.java | 41 + .../dubbo/rpc/protocol/rest/TjwsServer.java | 43 + .../rpc/protocol/rest/UndertowServer.java | 53 + .../resources/Acme/Resource/mime.properties | 104 + .../internal/com.alibaba.dubbo.rpc.Protocol | 1 + dubbo-test/dubbo-test-benchmark-api/pom.xml | 32 + .../dubbo/rpc/benchmark/BidRequest.java | 57 + .../dubbo/rpc/benchmark/BidResponse.java | 46 + .../alibaba/dubbo/rpc/benchmark/Device.java | 81 + .../dubbo/rpc/benchmark/EchoService.java | 40 + .../com/alibaba/dubbo/rpc/benchmark/Geo.java | 63 + .../dubbo/rpc/benchmark/Impression.java | 45 + .../alibaba/dubbo/rpc/benchmark/SeatBid.java | 46 + .../benchmark/SerializationOptimizerImpl.java | 41 + .../com/alibaba/dubbo/rpc/benchmark/Text.java | 43 + .../dubbo-test-benchmark-client/pom.xml | 200 + .../src/assembly/assembly.xml | 23 + .../src/cli/run.bat | 1 + .../src/cli/run.sh | 1 + .../benchmark/AbstractBenchmarkClient.java | 251 + .../rpc/benchmark/AbstractClientRunnable.java | 176 + .../rpc/benchmark/BidClientRunnable.java | 64 + .../dubbo/rpc/benchmark/ClientRunnable.java | 20 + .../rpc/benchmark/RpcBenchmarkClient.java | 24 + .../dubbo/rpc/benchmark/ServiceFactory.java | 118 + .../rpc/benchmark/TextClientRunnable.java | 46 + .../META-INF/cxf/org.apache.cxf.Logger | 1 + .../src/main/resources/dubbo.properties | 30 + .../src/main/resources/log4j.xml | 14 + .../dubbo-test-benchmark-server/pom.xml | 195 + .../src/assembly/assembly.xml | 23 + .../src/cli/run.bat | 1 + .../src/cli/run.sh | 1 + .../dubbo/rpc/benchmark/EchoServiceImpl.java | 41 + .../com/alibaba/dubbo/rpc/benchmark/Main.java | 24 + .../META-INF/cxf/org.apache.cxf.Logger | 1 + .../META-INF/spring/dubbo-provider.xml | 42 + .../src/main/resources/log4j.xml | 14 + .../src/main/webapp/WEB-INF/web.xml | 30 + 101 files changed, 10796 insertions(+) create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/Cleanable.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/OptimizedSerialization.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/SerializableClassRegistry.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/SerializationOptimizer.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstFactory.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstObjectInput.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstObjectOutput.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstSerialization.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/CompatibleKryo.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoFactory.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoObjectInput.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoObjectOutput.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoSerialization.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/PooledKryoFactory.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/PrototypeKryoFactory.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/ReflectionUtils.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/SingletonKryoFactory.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/ThreadLocalKryoFactory.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/FstSerializationTest.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/KyroSerializationTest.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/ReflectionUtilsTest.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/SerializationOptimizerImpl.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidRequest.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidResponse.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidService.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Device.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Geo.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Impression.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/SeatBid.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/ClientTraceFilter.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/DynamicTraceBinding.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/DynamicTraceInterceptor.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/TraceFilter.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/TraceInterceptor.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/hello/HelloService.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/User.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/UserService.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/RegistrationResult.java create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestService.java create mode 100644 dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/RestClient.java create mode 100644 dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/bid/BidServiceImpl.java create mode 100644 dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/hello/HelloServiceImpl.java create mode 100644 dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/UserServiceImpl.java create mode 100644 dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java create mode 100644 dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestServiceImpl.java create mode 100644 dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java create mode 100644 dubbo-demo/dubbo-demo-provider/src/main/resources/log4j.xml create mode 100644 dubbo-demo/dubbo-demo-provider/src/main/webapp/WEB-INF/web.xml create mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/BootstrapListener.java create mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/ServletManager.java create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceImplHolder.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/pom.xml create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/Acme/Serve/Serve.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/BaseRestServer.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboResourceFactory.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/NettyServer.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServer.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/SunHttpServer.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/TjwsServer.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/resources/Acme/Resource/mime.properties create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol create mode 100644 dubbo-test/dubbo-test-benchmark-api/pom.xml create mode 100644 dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidRequest.java create mode 100644 dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidResponse.java create mode 100644 dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Device.java create mode 100644 dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/EchoService.java create mode 100644 dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Geo.java create mode 100644 dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Impression.java create mode 100644 dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/SeatBid.java create mode 100644 dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/SerializationOptimizerImpl.java create mode 100644 dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Text.java create mode 100644 dubbo-test/dubbo-test-benchmark-client/pom.xml create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/assembly/assembly.xml create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/cli/run.bat create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/cli/run.sh create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractClientRunnable.java create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidClientRunnable.java create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/ClientRunnable.java create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcBenchmarkClient.java create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/ServiceFactory.java create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/TextClientRunnable.java create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/main/resources/META-INF/cxf/org.apache.cxf.Logger create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/main/resources/dubbo.properties create mode 100644 dubbo-test/dubbo-test-benchmark-client/src/main/resources/log4j.xml create mode 100644 dubbo-test/dubbo-test-benchmark-server/pom.xml create mode 100644 dubbo-test/dubbo-test-benchmark-server/src/assembly/assembly.xml create mode 100644 dubbo-test/dubbo-test-benchmark-server/src/cli/run.bat create mode 100644 dubbo-test/dubbo-test-benchmark-server/src/cli/run.sh create mode 100644 dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/EchoServiceImpl.java create mode 100644 dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/Main.java create mode 100644 dubbo-test/dubbo-test-benchmark-server/src/main/resources/META-INF/cxf/org.apache.cxf.Logger create mode 100644 dubbo-test/dubbo-test-benchmark-server/src/main/resources/META-INF/spring/dubbo-provider.xml create mode 100644 dubbo-test/dubbo-test-benchmark-server/src/main/resources/log4j.xml create mode 100644 dubbo-test/dubbo-test-benchmark-server/src/main/webapp/WEB-INF/web.xml diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/Cleanable.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/Cleanable.java new file mode 100644 index 000000000000..1b69c56b4f94 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/Cleanable.java @@ -0,0 +1,24 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize; + +/** + * @author lishen + */ +public interface Cleanable { + + void cleanup(); +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/OptimizedSerialization.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/OptimizedSerialization.java new file mode 100644 index 000000000000..9216327502ad --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/OptimizedSerialization.java @@ -0,0 +1,24 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize; + +/** + * Just a marker interface for now + * + * @author lishen + */ +public interface OptimizedSerialization extends Serialization { +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/SerializableClassRegistry.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/SerializableClassRegistry.java new file mode 100644 index 000000000000..3a09d41fe19b --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/SerializableClassRegistry.java @@ -0,0 +1,23 @@ +package com.alibaba.dubbo.common.serialize.support; + +import java.util.LinkedHashSet; +import java.util.Set; + +/** + * @author lishen + */ +public abstract class SerializableClassRegistry { + + private static final Set registrations = new LinkedHashSet(); + + /** + * only supposed to be called at startup time + */ + public static void registerClass(Class clazz) { + registrations.add(clazz); + } + + public static Set getRegisteredClasses() { + return registrations; + } +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/SerializationOptimizer.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/SerializationOptimizer.java new file mode 100644 index 000000000000..0f6f7a10cdfe --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/SerializationOptimizer.java @@ -0,0 +1,13 @@ +package com.alibaba.dubbo.common.serialize.support; + +import java.util.Collection; + +/** + * This class can be replaced with the contents in config file, but for now I think the class is easier to write + * + * @author lishen + */ +public interface SerializationOptimizer { + + Collection getSerializableClasses(); +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstFactory.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstFactory.java new file mode 100644 index 000000000000..38b531eadb3c --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstFactory.java @@ -0,0 +1,53 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.fst; + +import com.alibaba.dubbo.common.serialize.support.SerializableClassRegistry; +import de.ruedigermoeller.serialization.FSTConfiguration; +import de.ruedigermoeller.serialization.FSTObjectInput; +import de.ruedigermoeller.serialization.FSTObjectOutput; + +import java.io.InputStream; +import java.io.OutputStream; + +/** + * @author lishen + */ +public class FstFactory { + + private static final FstFactory factory = new FstFactory(); + + private final FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration(); + + + public static FstFactory getDefaultFactory() { + return factory; + } + + public FstFactory() { + for (Class clazz : SerializableClassRegistry.getRegisteredClasses()) { + conf.registerClass(clazz); + } + } + + public FSTObjectOutput getObjectOutput(OutputStream outputStream) { + return conf.getObjectOutput(outputStream); + } + + public FSTObjectInput getObjectInput(InputStream inputStream) { + return conf.getObjectInput(inputStream); + } +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstObjectInput.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstObjectInput.java new file mode 100644 index 000000000000..01fd6ea8dee9 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstObjectInput.java @@ -0,0 +1,95 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.fst; + +import com.alibaba.dubbo.common.serialize.ObjectInput; +import de.ruedigermoeller.serialization.FSTObjectInput; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; + +/** + * @author lishen + */ +public class FstObjectInput implements ObjectInput { + + private FSTObjectInput input; + + public FstObjectInput(InputStream inputStream) { + input = FstFactory.getDefaultFactory().getObjectInput(inputStream); + } + + public boolean readBool() throws IOException { + return input.readBoolean(); + } + + public byte readByte() throws IOException { + return input.readByte(); + } + + public short readShort() throws IOException { + return input.readShort(); + } + + public int readInt() throws IOException { + return input.readInt(); + } + + public long readLong() throws IOException { + return input.readLong(); + } + + public float readFloat() throws IOException { + return input.readFloat(); + } + + public double readDouble() throws IOException { + return input.readDouble(); + } + + public byte[] readBytes() throws IOException { + int len = input.readInt(); + if (len < 0) { + return null; + } else if (len == 0) { + return new byte[]{}; + } else { + byte[] b = new byte[len]; + input.readFully(b); + return b; + } + } + + public String readUTF() throws IOException { + return input.readUTF(); + } + + public Object readObject() throws IOException, ClassNotFoundException { + return input.readObject(); + } + + + @SuppressWarnings("unchecked") + public T readObject(Class clazz) throws IOException, ClassNotFoundException { + return (T) readObject(); + } + + @SuppressWarnings("unchecked") + public T readObject(Class clazz, Type type) throws IOException, ClassNotFoundException { + return (T) readObject(); + } +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstObjectOutput.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstObjectOutput.java new file mode 100644 index 000000000000..ba14f041bbd0 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstObjectOutput.java @@ -0,0 +1,92 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.fst; + +import com.alibaba.dubbo.common.serialize.ObjectOutput; +import de.ruedigermoeller.serialization.FSTObjectOutput; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * @author lishen + */ +public class FstObjectOutput implements ObjectOutput { + + private FSTObjectOutput output; + + public FstObjectOutput(OutputStream outputStream) { + output = FstFactory.getDefaultFactory().getObjectOutput(outputStream); + } + + public void writeBool(boolean v) throws IOException { + output.writeBoolean(v); + } + + public void writeByte(byte v) throws IOException { + output.writeByte(v); + } + + public void writeShort(short v) throws IOException { + output.writeShort(v); + } + + public void writeInt(int v) throws IOException { + output.writeInt(v); + } + + public void writeLong(long v) throws IOException { + output.writeLong(v); + } + + public void writeFloat(float v) throws IOException { + output.writeFloat(v); + } + + public void writeDouble(double v) throws IOException { + output.writeDouble(v); + } + + public void writeBytes(byte[] v) throws IOException { + if (v == null) { + output.writeInt(-1); + } else { + writeBytes(v, 0, v.length); + } + } + + public void writeBytes(byte[] v, int off, int len) throws IOException { + if (v == null) { + output.writeInt(-1); + } else { + output.writeInt(len); + output.write(v, off, len); + } + } + + + public void writeUTF(String v) throws IOException { + output.writeUTF(v); + } + + public void writeObject(Object v) throws IOException { + output.writeObject(v); + } + + public void flushBuffer() throws IOException { + output.flush(); + } +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstSerialization.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstSerialization.java new file mode 100644 index 000000000000..dff215b60bb5 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/fst/FstSerialization.java @@ -0,0 +1,47 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.fst; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.serialize.ObjectInput; +import com.alibaba.dubbo.common.serialize.ObjectOutput; +import com.alibaba.dubbo.common.serialize.OptimizedSerialization; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * @author lishen + */ +public class FstSerialization implements OptimizedSerialization { + + public byte getContentTypeId() { + return 9; + } + + public String getContentType() { + return "x-application/fst"; + } + + public ObjectOutput serialize(URL url, OutputStream out) throws IOException { + return new FstObjectOutput(out); + } + + public ObjectInput deserialize(URL url, InputStream is) throws IOException { + return new FstObjectInput(is); + } +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/CompatibleKryo.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/CompatibleKryo.java new file mode 100644 index 000000000000..8ab2a9ecfdbf --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/CompatibleKryo.java @@ -0,0 +1,45 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.kryo; + +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.Serializer; +import com.esotericsoftware.kryo.serializers.JavaSerializer; + +/** + * @author lishen + */ +public class CompatibleKryo extends Kryo { + + private static final Logger logger = LoggerFactory.getLogger(CompatibleKryo.class); + + @Override + public Serializer getDefaultSerializer(Class type) { + if (type == null) { + throw new IllegalArgumentException("type cannot be null."); + } + + if (!type.isArray() && !ReflectionUtils.checkZeroArgConstructor(type)) { + if (logger.isWarnEnabled()) { + logger.warn(type + " has no zero-arg constructor and this will affect the serialization performance"); + } + return new JavaSerializer(); + } + return super.getDefaultSerializer(type); + } +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoFactory.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoFactory.java new file mode 100644 index 000000000000..a06efef1c457 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoFactory.java @@ -0,0 +1,142 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.kryo; + +import com.alibaba.dubbo.common.serialize.support.SerializableClassRegistry; +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.serializers.DefaultSerializers; +import de.javakaffee.kryoserializers.*; + +import java.lang.reflect.InvocationHandler; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.URI; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +/** + * @author lishen + */ +public abstract class KryoFactory { + +// private static final KryoFactory factory = new PrototypeKryoFactory(); +// private static final KryoFactory factory = new SingletonKryoFactory(); + private static final KryoFactory factory = new PooledKryoFactory(); + + private final Set registrations = new LinkedHashSet(); + + private boolean registrationRequired; + + private volatile boolean kryoCreated; + + protected KryoFactory() { + // TODO configurable +// Log.DEBUG(); + } + + public static KryoFactory getDefaultFactory() { + return factory; + } + + /** + * only supposed to be called at startup time + * + * later may consider adding support for custom serializer, custom id, etc + */ + public void registerClass(Class clazz) { + + if (kryoCreated) { + throw new IllegalStateException("Can't register class after creating kryo instance"); + } + registrations.add(clazz); + } + + protected Kryo createKryo() { + if (!kryoCreated) { + kryoCreated = true; + } + + Kryo kryo = new CompatibleKryo(); + + // TODO +// kryo.setReferences(false); + kryo.setRegistrationRequired(registrationRequired); + + kryo.register(Arrays.asList("").getClass(), new ArraysAsListSerializer()); + kryo.register(GregorianCalendar.class, new GregorianCalendarSerializer()); + kryo.register(InvocationHandler.class, new JdkProxySerializer()); + kryo.register(BigDecimal.class, new DefaultSerializers.BigDecimalSerializer()); + kryo.register(BigInteger.class, new DefaultSerializers.BigIntegerSerializer()); + kryo.register(Pattern.class, new RegexSerializer()); + kryo.register(BitSet.class, new BitSetSerializer()); + kryo.register(URI.class, new URISerializer()); + kryo.register(UUID.class, new UUIDSerializer()); + UnmodifiableCollectionsSerializer.registerSerializers(kryo); + SynchronizedCollectionsSerializer.registerSerializers(kryo); + + // now just added some very common classes + // TODO optimization + kryo.register(HashMap.class); + kryo.register(ArrayList.class); + kryo.register(LinkedList.class); + kryo.register(HashSet.class); + kryo.register(TreeSet.class); + kryo.register(Hashtable.class); + kryo.register(Date.class); + kryo.register(Calendar.class); + kryo.register(ConcurrentHashMap.class); + kryo.register(SimpleDateFormat.class); + kryo.register(GregorianCalendar.class); + kryo.register(Vector.class); + kryo.register(BitSet.class); + kryo.register(StringBuffer.class); + kryo.register(StringBuilder.class); + kryo.register(Object.class); + kryo.register(Object[].class); + kryo.register(String[].class); + kryo.register(byte[].class); + kryo.register(char[].class); + kryo.register(int[].class); + kryo.register(float[].class); + kryo.register(double[].class); + + for (Class clazz : registrations) { + kryo.register(clazz); + } + + for (Class clazz : SerializableClassRegistry.getRegisteredClasses()) { + kryo.register(clazz); + } + + return kryo; + } + + public void returnKryo(Kryo kryo) { + // do nothing by default + } + + public void setRegistrationRequired(boolean registrationRequired) { + this.registrationRequired = registrationRequired; + } + + public void close() { + // do nothing by default + } + + public abstract Kryo getKryo(); +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoObjectInput.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoObjectInput.java new file mode 100644 index 000000000000..e441a64c212a --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoObjectInput.java @@ -0,0 +1,158 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.kryo; + +import com.alibaba.dubbo.common.serialize.Cleanable; +import com.alibaba.dubbo.common.serialize.ObjectInput; +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.KryoException; +import com.esotericsoftware.kryo.io.Input; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; + +/** + * @author lishen + */ +public class KryoObjectInput implements ObjectInput, Cleanable { + + private Kryo kryo = KryoFactory.getDefaultFactory().getKryo(); + private Input input; + + public KryoObjectInput(InputStream inputStream) { + input = new Input(inputStream); + } + + public boolean readBool() throws IOException { + try { + return input.readBoolean(); + } catch (KryoException e) { + throw new IOException(e); + } + } + + public byte readByte() throws IOException { + try { + return input.readByte(); + } catch (KryoException e) { + throw new IOException(e); + } + } + + public short readShort() throws IOException { + try { + return input.readShort(); + } catch (KryoException e) { + throw new IOException(e); + } + } + + public int readInt() throws IOException { + try { + return input.readInt(); + } catch (KryoException e) { + throw new IOException(e); + } + } + + public long readLong() throws IOException { + try { + return input.readLong(); + } catch (KryoException e) { + throw new IOException(e); + } + } + + public float readFloat() throws IOException { + try { + return input.readFloat(); + } catch (KryoException e) { + throw new IOException(e); + } + } + + public double readDouble() throws IOException { + try { + return input.readDouble(); + } catch (KryoException e) { + throw new IOException(e); + } + } + + public byte[] readBytes() throws IOException { + try { + int len = input.readInt(); + if (len < 0) { + return null; + } else if (len == 0) { + return new byte[]{}; + } else { + return input.readBytes(len); + } + } catch (KryoException e) { + throw new IOException(e); + } + } + + public String readUTF() throws IOException { + // TODO + try { +// return kryo.readObject(input, String.class); + return input.readString(); + } catch (KryoException e) { + throw new IOException(e); + } + } + + public Object readObject() throws IOException, ClassNotFoundException { + // TODO +// throw new UnsupportedOperationException(); + try { + return kryo.readClassAndObject(input); + } catch (KryoException e) { + throw new IOException(e); + } + } + + + @SuppressWarnings("unchecked") + public T readObject(Class clazz) throws IOException, ClassNotFoundException { + // TODO optimization +// try { +// return (T) kryo.readClassAndObject(input); +// } catch (KryoException e) { +// throw new IOException(e); +// } + return (T) readObject(); + } + + @SuppressWarnings("unchecked") + public T readObject(Class clazz, Type type) throws IOException, ClassNotFoundException { +// try { +// return readObject(clazz); +// } catch (KryoException e) { +// throw new IOException(e); +// } + // TODO optimization + return (T) readObject(clazz); + } + + public void cleanup() { + KryoFactory.getDefaultFactory().returnKryo(kryo); + kryo = null; + } +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoObjectOutput.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoObjectOutput.java new file mode 100644 index 000000000000..fb127be60200 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoObjectOutput.java @@ -0,0 +1,102 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.kryo; + +import com.alibaba.dubbo.common.serialize.Cleanable; +import com.alibaba.dubbo.common.serialize.ObjectOutput; +import com.esotericsoftware.kryo.Kryo; +import com.esotericsoftware.kryo.io.Output; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * @author lishen + */ +public class KryoObjectOutput implements ObjectOutput, Cleanable { + + private Kryo kryo = KryoFactory.getDefaultFactory().getKryo(); + private Output output; + + public KryoObjectOutput(OutputStream outputStream) { + output = new Output(outputStream); + } + + public void writeBool(boolean v) throws IOException { + output.writeBoolean(v); + } + + public void writeByte(byte v) throws IOException { + output.writeByte(v); + } + + public void writeShort(short v) throws IOException { + output.writeShort(v); + } + + public void writeInt(int v) throws IOException { + output.writeInt(v); + } + + public void writeLong(long v) throws IOException { + output.writeLong(v); + } + + public void writeFloat(float v) throws IOException { + output.writeFloat(v); + } + + public void writeDouble(double v) throws IOException { + output.writeDouble(v); + } + + public void writeBytes(byte[] v) throws IOException { + if (v == null) { + output.writeInt(-1); + } else { + writeBytes(v, 0, v.length); + } + } + + public void writeBytes(byte[] v, int off, int len) throws IOException { + if (v == null) { + output.writeInt(-1); + } else { + output.writeInt(len); + output.write(v, off, len); + } + } + + + public void writeUTF(String v) throws IOException { + // TODO + output.writeString(v); +// kryo.writeObject(output, v); + } + + public void writeObject(Object v) throws IOException { + kryo.writeClassAndObject(output, v); + } + + public void flushBuffer() throws IOException { + output.flush(); + } + + public void cleanup() { + KryoFactory.getDefaultFactory().returnKryo(kryo); + kryo = null; + } +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoSerialization.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoSerialization.java new file mode 100644 index 000000000000..07766cb4c5f1 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/KryoSerialization.java @@ -0,0 +1,49 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.kryo; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.serialize.ObjectInput; +import com.alibaba.dubbo.common.serialize.ObjectOutput; +import com.alibaba.dubbo.common.serialize.OptimizedSerialization; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * TODO for now kryo serialization doesn't deny classes that don't implement the serializable interface + * + * @author lishen + */ +public class KryoSerialization implements OptimizedSerialization { + + public byte getContentTypeId() { + return 8; + } + + public String getContentType() { + return "x-application/kryo"; + } + + public ObjectOutput serialize(URL url, OutputStream out) throws IOException { + return new KryoObjectOutput(out); + } + + public ObjectInput deserialize(URL url, InputStream is) throws IOException { + return new KryoObjectInput(is); + } +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/PooledKryoFactory.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/PooledKryoFactory.java new file mode 100644 index 000000000000..7c2cfa5a6aa0 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/PooledKryoFactory.java @@ -0,0 +1,47 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.kryo; + +import com.esotericsoftware.kryo.Kryo; + +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; + +/** + * @author lishen + */ +public class PooledKryoFactory extends KryoFactory { + + private final Queue pool = new ConcurrentLinkedQueue(); + + @Override + public void returnKryo(Kryo kryo) { + pool.offer(kryo); + } + + @Override + public void close() { + pool.clear(); + } + + public Kryo getKryo() { + Kryo kryo = pool.poll(); + if (kryo == null) { + kryo = createKryo(); + } + return kryo; + } +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/PrototypeKryoFactory.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/PrototypeKryoFactory.java new file mode 100644 index 000000000000..06c18787cbbf --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/PrototypeKryoFactory.java @@ -0,0 +1,28 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.kryo; + +import com.esotericsoftware.kryo.Kryo; + +/** + * @author lishen + */ +public class PrototypeKryoFactory extends KryoFactory { + + public Kryo getKryo() { + return createKryo(); + } +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/ReflectionUtils.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/ReflectionUtils.java new file mode 100644 index 000000000000..40997fe39988 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/ReflectionUtils.java @@ -0,0 +1,31 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.kryo; + +/** + * @author lishen + */ +public abstract class ReflectionUtils { + + public static boolean checkZeroArgConstructor(Class clazz) { + try { + clazz.getDeclaredConstructor(); + return true; + } catch (NoSuchMethodException e) { + return false; + } + } +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/SingletonKryoFactory.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/SingletonKryoFactory.java new file mode 100644 index 000000000000..2e3aefd487e4 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/SingletonKryoFactory.java @@ -0,0 +1,37 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.kryo; + +import com.esotericsoftware.kryo.Kryo; + +/** + * CAUSION this is only for test purpose since both kryo and this class are not thread-safe + * + * @author lishen + */ +public class SingletonKryoFactory extends KryoFactory { + +// private final Kryo instance = createKryo(); + private Kryo instance; + + @Override + public Kryo getKryo() { + if (instance == null) { + instance = createKryo(); + } + return instance; + } +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/ThreadLocalKryoFactory.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/ThreadLocalKryoFactory.java new file mode 100644 index 000000000000..aee8659ab5d6 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/kryo/ThreadLocalKryoFactory.java @@ -0,0 +1,35 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.kryo; + +import com.esotericsoftware.kryo.Kryo; + +/** + * @author lishen + */ +public class ThreadLocalKryoFactory extends KryoFactory { + + private final ThreadLocal holder = new ThreadLocal() { + @Override + protected Kryo initialValue() { + return createKryo(); + } + }; + + public Kryo getKryo() { + return holder.get(); + } +} diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/FstSerializationTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/FstSerializationTest.java new file mode 100644 index 000000000000..02932765df59 --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/FstSerializationTest.java @@ -0,0 +1,13 @@ +package com.alibaba.dubbo.common.serialize.serialization; + +import com.alibaba.dubbo.common.serialize.support.kryo.KryoSerialization; + +/** + * @author lishen + */ +public class FstSerializationTest extends AbstractSerializationTest { + + { + serialization = new KryoSerialization(); + } +} diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/KyroSerializationTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/KyroSerializationTest.java new file mode 100644 index 000000000000..244a49fa1d49 --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/KyroSerializationTest.java @@ -0,0 +1,13 @@ +package com.alibaba.dubbo.common.serialize.serialization; + +import com.alibaba.dubbo.common.serialize.support.kryo.KryoSerialization; + +/** + * @author lishen + */ +public class KyroSerializationTest extends AbstractSerializationTest { + + { + serialization = new KryoSerialization(); + } +} \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/ReflectionUtilsTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/ReflectionUtilsTest.java new file mode 100644 index 000000000000..f4ef790ec6eb --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/serialize/serialization/ReflectionUtilsTest.java @@ -0,0 +1,34 @@ +package com.alibaba.dubbo.common.serialize.serialization; + +import com.alibaba.dubbo.common.serialize.support.kryo.ReflectionUtils; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + + + +/** + * @author lishen + */ +public class ReflectionUtilsTest { + + @Test + public void test() { + assertTrue(ReflectionUtils.checkZeroArgConstructor(String.class)); + assertTrue(ReflectionUtils.checkZeroArgConstructor(Bar.class)); + assertFalse(ReflectionUtils.checkZeroArgConstructor(Foo.class)); + } + + static class Foo { + public Foo(int i) { + + } + } + + static class Bar { + private Bar() { + + } + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/SerializationOptimizerImpl.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/SerializationOptimizerImpl.java new file mode 100644 index 000000000000..881ba9b49b42 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/SerializationOptimizerImpl.java @@ -0,0 +1,49 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo; + +import com.alibaba.dubbo.common.serialize.support.SerializationOptimizer; +import com.alibaba.dubbo.demo.bid.BidRequest; +import com.alibaba.dubbo.demo.bid.BidResponse; +import com.alibaba.dubbo.demo.bid.Device; +import com.alibaba.dubbo.demo.bid.Geo; +import com.alibaba.dubbo.demo.bid.Impression; +import com.alibaba.dubbo.demo.bid.SeatBid; +import com.alibaba.dubbo.demo.user.User; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +/** + * This class must be accessible from both the provider and consumer + * + * @author lishen + */ +public class SerializationOptimizerImpl implements SerializationOptimizer { + + public Collection getSerializableClasses() { + List classes = new LinkedList(); + classes.add(BidRequest.class); + classes.add(BidResponse.class); + classes.add(Device.class); + classes.add(Geo.class); + classes.add(Impression.class); + classes.add(SeatBid.class); + classes.add(User.class); + return classes; + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidRequest.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidRequest.java new file mode 100644 index 000000000000..905be3e4cf84 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidRequest.java @@ -0,0 +1,55 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.bid; + +import java.io.Serializable; +import java.util.List; + +/** + * @author lishen + */ +public class BidRequest implements Serializable { + + private String id; + + private Device device; + + private List impressions; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Device getDevice() { + return device; + } + + public void setDevice(Device device) { + this.device = device; + } + + public List getImpressions() { + return impressions; + } + + public void setImpressions(List impressions) { + this.impressions = impressions; + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidResponse.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidResponse.java new file mode 100644 index 000000000000..e5b26b425def --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidResponse.java @@ -0,0 +1,44 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.bid; + +import java.io.Serializable; +import java.util.List; + +/** + * @author lishen + */ +public class BidResponse implements Serializable { + + private String id; + private List seatBids; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public List getSeatBids() { + return seatBids; + } + + public void setSeatBids(List seatBids) { + this.seatBids = seatBids; + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidService.java new file mode 100644 index 000000000000..31ed65d0ad45 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidService.java @@ -0,0 +1,23 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.bid; + +public interface BidService { + + BidResponse bid(BidRequest request); + + void throwNPE() throws NullPointerException; +} \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Device.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Device.java new file mode 100644 index 000000000000..81dcab6960f9 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Device.java @@ -0,0 +1,79 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.bid; + +import java.io.Serializable; + +/** + * @author lishen + */ +public class Device implements Serializable { + + private String os; + private String make; + private String version; + private String model; + private String lang; + private Geo geo; + + public String getOs() { + return os; + } + + public void setOs(String os) { + this.os = os; + } + + public String getMake() { + return make; + } + + public void setMake(String make) { + this.make = make; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + public String getLang() { + return lang; + } + + public void setLang(String lang) { + this.lang = lang; + } + + public Geo getGeo() { + return geo; + } + + public void setGeo(Geo geo) { + this.geo = geo; + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Geo.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Geo.java new file mode 100644 index 000000000000..ddbe6b2e547c --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Geo.java @@ -0,0 +1,61 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.bid; + +import java.io.Serializable; + +/** + * @author lishen + */ +public class Geo implements Serializable { + + private float lon; + private float lat; + private String country; + private String city; + + public float getLon() { + return lon; + } + + public void setLon(float lon) { + this.lon = lon; + } + + public float getLat() { + return lat; + } + + public void setLat(float lat) { + this.lat = lat; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Impression.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Impression.java new file mode 100644 index 000000000000..2b4cddfc5594 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Impression.java @@ -0,0 +1,43 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.bid; + +import java.io.Serializable; + +/** + * @author lishen + */ +public class Impression implements Serializable { + + private String id; + private double bidFloor; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public double getBidFloor() { + return bidFloor; + } + + public void setBidFloor(double bidFloor) { + this.bidFloor = bidFloor; + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/SeatBid.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/SeatBid.java new file mode 100644 index 000000000000..8e852e657b59 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/SeatBid.java @@ -0,0 +1,44 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.bid; + +import java.io.Serializable; + +/** + * @author lishen + */ +public class SeatBid implements Serializable { + + private String seat; + + private String group; + + public String getSeat() { + return seat; + } + + public void setSeat(String seat) { + this.seat = seat; + } + + public String getGroup() { + return group; + } + + public void setGroup(String group) { + this.group = group; + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/ClientTraceFilter.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/ClientTraceFilter.java new file mode 100644 index 000000000000..8796e71b880f --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/ClientTraceFilter.java @@ -0,0 +1,36 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.extension; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import java.io.IOException; + +/** + * @author lishen + */ +public class ClientTraceFilter implements ClientRequestFilter, ClientResponseFilter { + + public void filter(ClientRequestContext requestContext) throws IOException { + System.out.println("Client request filter invoked"); + } + + public void filter(ClientRequestContext clientRequestContext, ClientResponseContext clientResponseContext) throws IOException { + System.out.println("Client response filter invoked"); + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/DynamicTraceBinding.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/DynamicTraceBinding.java new file mode 100644 index 000000000000..27e6521bd801 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/DynamicTraceBinding.java @@ -0,0 +1,30 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.extension; + +import javax.ws.rs.container.DynamicFeature; +import javax.ws.rs.container.ResourceInfo; +import javax.ws.rs.core.FeatureContext; + +/** + * @author lishen + */ +public class DynamicTraceBinding implements DynamicFeature { + + public void configure(ResourceInfo resourceInfo, FeatureContext context) { + context.register(DynamicTraceInterceptor.class); + } +} \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/DynamicTraceInterceptor.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/DynamicTraceInterceptor.java new file mode 100644 index 000000000000..f8b8203e01ca --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/DynamicTraceInterceptor.java @@ -0,0 +1,42 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.extension; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.ext.ReaderInterceptor; +import javax.ws.rs.ext.ReaderInterceptorContext; +import javax.ws.rs.ext.WriterInterceptor; +import javax.ws.rs.ext.WriterInterceptorContext; +import java.io.IOException; + +/** + * @author lishen + */ +@Priority(Priorities.USER) +public class DynamicTraceInterceptor implements ReaderInterceptor, WriterInterceptor { + + public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Dynamic reader interceptor invoked"); + return readerInterceptorContext.proceed(); + } + + public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Dynamic writer interceptor invoked"); + writerInterceptorContext.proceed(); + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/TraceFilter.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/TraceFilter.java new file mode 100644 index 000000000000..912770028373 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/TraceFilter.java @@ -0,0 +1,39 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.extension; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import java.io.IOException; + +/** + * @author lishen + */ +@Priority(Priorities.USER) +public class TraceFilter implements ContainerRequestFilter, ContainerResponseFilter { + + public void filter(ContainerRequestContext requestContext) throws IOException { + System.out.println("Request filter invoked"); + } + + public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException { + System.out.println("Response filter invoked"); + } +} \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/TraceInterceptor.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/TraceInterceptor.java new file mode 100644 index 000000000000..f8c25fc585b4 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/TraceInterceptor.java @@ -0,0 +1,42 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.extension; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.ext.ReaderInterceptor; +import javax.ws.rs.ext.ReaderInterceptorContext; +import javax.ws.rs.ext.WriterInterceptor; +import javax.ws.rs.ext.WriterInterceptorContext; +import java.io.IOException; + +/** + * @author lishen + */ +@Priority(Priorities.USER) +public class TraceInterceptor implements ReaderInterceptor, WriterInterceptor { + + public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Reader interceptor invoked"); + return readerInterceptorContext.proceed(); + } + + public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Writer interceptor invoked"); + writerInterceptorContext.proceed(); + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/hello/HelloService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/hello/HelloService.java new file mode 100644 index 000000000000..297e7915e218 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/hello/HelloService.java @@ -0,0 +1,23 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.hello; + +/** + * @author lishen + */ +public interface HelloService { + String hello(String name); +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/User.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/User.java new file mode 100644 index 000000000000..e4b43ebf29d7 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/User.java @@ -0,0 +1,67 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.user; + +import org.codehaus.jackson.annotate.JsonProperty; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * @author lishen + */ +@XmlRootElement +public class User implements Serializable { + + private Long id; + +// @JsonProperty("username") + private String name; + + public User() { + } + + public User(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + +// @XmlElement(name = "username") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "User (" + + "id=" + id + + ", name='" + name + '\'' + + ')'; + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/UserService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/UserService.java new file mode 100644 index 000000000000..74782f25c6e3 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/UserService.java @@ -0,0 +1,25 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.user; + +/** + * @author lishen + */ +public interface UserService { + User getUser(Long id); + + Long registerUser(User user); +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java new file mode 100644 index 000000000000..f60533a41ded --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java @@ -0,0 +1,43 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.user.facade; + +import com.alibaba.dubbo.demo.user.User; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +/** + * @author lishen + */ +@Path("u") +@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +public interface AnotherUserRestService { + + @GET + @Path("{id : \\d+}") + User getUser(@PathParam("id") Long id); + + @POST + @Path("register") + RegistrationResult registerUser(User user); +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/RegistrationResult.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/RegistrationResult.java new file mode 100644 index 000000000000..1924ed0c805c --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/RegistrationResult.java @@ -0,0 +1,45 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.user.facade; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * DTO to customize the returned message + * + * @author lishen + */ +@XmlRootElement +public class RegistrationResult implements Serializable { + + private Long id; + + public RegistrationResult() { + } + + public RegistrationResult(Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestService.java new file mode 100644 index 000000000000..a349e17a398f --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestService.java @@ -0,0 +1,38 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.user.facade; + +import com.alibaba.dubbo.demo.user.User; + +/** + * This interface acts as some kind of service broker for the original UserService + + * Here we want to simulate the twitter/weibo rest api, e.g. + * + * http://localhost:8888/user/1.json + * http://localhost:8888/user/1.xml + * + * @author lishen + */ +public interface UserRestService { + + /** + * the request object is just used to test jax-rs injection + */ + User getUser(Long id/*, HttpServletRequest request*/); + + RegistrationResult registerUser(User user); +} diff --git a/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/RestClient.java b/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/RestClient.java new file mode 100644 index 000000000000..578423ead714 --- /dev/null +++ b/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/RestClient.java @@ -0,0 +1,104 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.consumer; + +import com.alibaba.dubbo.demo.user.User; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +/** + * @author lishen + */ +public class RestClient { + + public static void main(String[] args) { + final String port = "8888"; +// final String port = "8080"; + +// for (int i = 0; i < 500; i++) { +// final int index = i + 1; +// new Thread(new Runnable() { +// public void run() { +// System.out.println("Starting thread " + index + "..."); +// for (int j = 0; j < 500; j++) { + registerUser("http://localhost:" + port + "/services/users/register.json", MediaType.APPLICATION_JSON_TYPE); + + registerUser("http://localhost:" + port + "/services/users/register.xml", MediaType.TEXT_XML_TYPE); + + getUser("http://localhost:" + port + "/services/users/1.json"); + + getUser("http://localhost:" + port + "/services/users/2.xml"); + + registerUser("http://localhost:" + port + "/services/u/register.json", MediaType.APPLICATION_JSON_TYPE); + + registerUser("http://localhost:" + port + "/services/u/register.xml", MediaType.TEXT_XML_TYPE); + + getUser("http://localhost:" + port + "/services/u/1.json"); + + getUser("http://localhost:" + port + "/services/u/2.xml"); + + registerUser("http://localhost:" + port + "/services/customers/register.json", MediaType.APPLICATION_JSON_TYPE); + + registerUser("http://localhost:" + port + "/services/customers/register.xml", MediaType.TEXT_XML_TYPE); + + getUser("http://localhost:" + port + "/services/customers/1.json"); + + getUser("http://localhost:" + port + "/services/customers/2.xml"); +// } +// } +// }).start(); +// } + } + + private static void registerUser(String url, MediaType mediaType) { + System.out.println("Registering user via " + url); + User user = new User(1L, "dang"); + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(url); + Response response = target.request().post(Entity.entity(user, mediaType)); + + try { + if (response.getStatus() != 200) { + throw new RuntimeException("Failed with HTTP error code : " + response.getStatus()); + } + System.out.println("Successfully got result: " + response.readEntity(String.class)); + } finally { + response.close(); + client.close(); + } + } + + private static void getUser(String url) { + System.out.println("Getting user via " + url); + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(url); + Response response = target.request().get(); + try { + if (response.getStatus() != 200) { + throw new RuntimeException("Failed with HTTP error code : " + response.getStatus()); + } + System.out.println("Successfully got result: " + response.readEntity(String.class)); + } finally { + response.close(); + client.close(); + } + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/bid/BidServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/bid/BidServiceImpl.java new file mode 100644 index 000000000000..391ffbc3a810 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/bid/BidServiceImpl.java @@ -0,0 +1,43 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.bid; + +import java.util.ArrayList; +import java.util.List; + +public class BidServiceImpl implements BidService { + + public BidResponse bid(BidRequest request) { + BidResponse response = new BidResponse(); + + response.setId("abc"); + + SeatBid seatBid = new SeatBid(); + seatBid.setGroup("group"); + seatBid.setSeat("seat"); + List seatBids = new ArrayList(1); + seatBids.add(seatBid); + + response.setSeatBids(seatBids); + + return response; + } + + public void throwNPE() throws NullPointerException { + throw new NullPointerException(); + } + +} \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/hello/HelloServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/hello/HelloServiceImpl.java new file mode 100644 index 000000000000..80fcf24fc566 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/hello/HelloServiceImpl.java @@ -0,0 +1,26 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.hello; + +/** + * @author lishen + */ +public class HelloServiceImpl implements HelloService { + + public String hello(String name) { + return "hello " + name; + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/UserServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/UserServiceImpl.java new file mode 100644 index 000000000000..ef3ba3483170 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/UserServiceImpl.java @@ -0,0 +1,36 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.user; + +import java.util.concurrent.atomic.AtomicLong; + +/** + * @author lishen + */ +public class UserServiceImpl implements UserService { + + private final AtomicLong idGen = new AtomicLong(); + + public User getUser(Long id) { + return new User(id, "dang" + id); + } + + + public Long registerUser(User user) { +// System.out.println("Username is " + user.getName()); + return idGen.incrementAndGet(); + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java new file mode 100644 index 000000000000..ffef936a02b6 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java @@ -0,0 +1,63 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.user.facade; + +import com.alibaba.dubbo.config.annotation.Service; +import com.alibaba.dubbo.demo.user.User; +import com.alibaba.dubbo.demo.user.UserService; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +/** + * @author lishen + */ +@Service(protocol = "rest", group = "annotationConfig") +@Path("customers") +@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +public class AnnotationDrivenUserRestServiceImpl implements UserRestService { + +// private static final Logger logger = LoggerFactory.getLogger(UserRestServiceImpl.class); + + @Autowired + private UserService userService; + + public void setUserService(UserService userService) { + this.userService = userService; + } + + @GET + @Path("{id : \\d+}") + public User getUser(@PathParam("id") Long id/*, @Context HttpServletRequest request*/) { + // test context injection +// System.out.println("Client address from @Context injection: " + (request != null ? request.getRemoteAddr() : "")); +// System.out.println("Client address from RpcContext: " + RpcContext.getContext().getRemoteAddressString()); + return userService.getUser(id); + } + + @POST + @Path("register") + public RegistrationResult registerUser(User user) { + return new RegistrationResult(userService.registerUser(user)); + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestServiceImpl.java new file mode 100644 index 000000000000..31da5f93aa63 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestServiceImpl.java @@ -0,0 +1,39 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.user.facade; + +import com.alibaba.dubbo.demo.user.User; +import com.alibaba.dubbo.demo.user.UserService; + +/** + * @author lishen + */ +public class AnotherUserRestServiceImpl implements AnotherUserRestService { + + private UserService userService; + + public void setUserService(UserService userService) { + this.userService = userService; + } + + public User getUser(Long id) { + return userService.getUser(id); + } + + public RegistrationResult registerUser(User user) { + return new RegistrationResult(userService.registerUser(user)); + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java new file mode 100644 index 000000000000..1387205f6f78 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java @@ -0,0 +1,61 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.user.facade; + +import com.alibaba.dubbo.demo.user.User; +import com.alibaba.dubbo.demo.user.UserService; +import com.alibaba.dubbo.demo.user.facade.RegistrationResult; +import com.alibaba.dubbo.demo.user.facade.UserRestService; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +/** + * @author lishen + */ +@Path("users") +@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +public class UserRestServiceImpl implements UserRestService { + +// private static final Logger logger = LoggerFactory.getLogger(UserRestServiceImpl.class); + + private UserService userService; + + public void setUserService(UserService userService) { + this.userService = userService; + } + + @GET + @Path("{id : \\d+}") + public User getUser(@PathParam("id") Long id/*, @Context HttpServletRequest request*/) { + // test context injection +// System.out.println("Client address from @Context injection: " + (request != null ? request.getRemoteAddr() : "")); +// System.out.println("Client address from RpcContext: " + RpcContext.getContext().getRemoteAddressString()); + return userService.getUser(id); + } + + @POST + @Path("register") + public RegistrationResult registerUser(User user) { + return new RegistrationResult(userService.registerUser(user)); + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/log4j.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/log4j.xml new file mode 100644 index 000000000000..ae988c35f139 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/log4j.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/webapp/WEB-INF/web.xml b/dubbo-demo/dubbo-demo-provider/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000000..9a355c15ffce --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,30 @@ + + + + + + contextConfigLocation + /WEB-INF/classes/META-INF/spring/dubbo-demo-provider.xml + + + + + com.alibaba.dubbo.remoting.http.servlet.BootstrapListener + + + + org.springframework.web.context.ContextLoaderListener + + + + dispatcher + com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet + 1 + + + + dispatcher + /services/* + + \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/BootstrapListener.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/BootstrapListener.java new file mode 100644 index 000000000000..7a562574aa1d --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/BootstrapListener.java @@ -0,0 +1,35 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.http.servlet; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +/** + * This class must be defined before something like spring's ContextLoaderListener in web.xml + * + * @author lishen + */ +public class BootstrapListener implements ServletContextListener { + + public void contextInitialized(ServletContextEvent servletContextEvent) { + ServletManager.getInstance().addServletContext(ServletManager.EXTERNAL_SERVER_PORT, servletContextEvent.getServletContext()); + } + + public void contextDestroyed(ServletContextEvent servletContextEvent) { + ServletManager.getInstance().removeServletContext(ServletManager.EXTERNAL_SERVER_PORT); + } +} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/ServletManager.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/ServletManager.java new file mode 100644 index 000000000000..8e9744d3aa84 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/servlet/ServletManager.java @@ -0,0 +1,51 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.http.servlet; + +import javax.servlet.ServletContext; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * TODO this may not be a pretty elegant solution, + * and we may need to make change to the whole remoting-http architecture in the future + * + * @author lishen + */ +public class ServletManager { + + public static final int EXTERNAL_SERVER_PORT = -1234; + + private static final ServletManager instance = new ServletManager(); + + private final Map contextMap = new ConcurrentHashMap(); + + public static ServletManager getInstance() { + return instance; + } + + public void addServletContext(int port, ServletContext servletContext) { + contextMap.put(port, servletContext); + } + + public void removeServletContext(int port) { + contextMap.remove(port); + } + + public ServletContext getServletContext(int port) { + return contextMap.get(port); + } +} diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceImplHolder.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceImplHolder.java new file mode 100644 index 000000000000..9371d91de264 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceImplHolder.java @@ -0,0 +1,30 @@ +package com.alibaba.dubbo.rpc.protocol; + +/** + * TODO this is just a workround for rest protocol, and now we just ensure it works in the most common dubbo usages + * + * @author lishen + */ +public class ServiceImplHolder { + + private static final ServiceImplHolder INSTANCE = new ServiceImplHolder(); + + private final ThreadLocal holder = new ThreadLocal(); + + public static ServiceImplHolder getInstance() { + return INSTANCE; + } + + private ServiceImplHolder() { + } + + public Object popServiceImpl() { + Object impl = holder.get(); + holder.remove(); + return impl; + } + + public void pushServiceImpl(Object impl) { + holder.set(impl); + } +} diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml new file mode 100644 index 000000000000..336705306864 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml @@ -0,0 +1,121 @@ + + 4.0.0 + + com.alibaba + dubbo-rpc + 2.8.0 + + dubbo-rpc-rest + jar + ${project.artifactId} + The JAX-RS rpc module of dubbo project + + true + + + + com.alibaba + dubbo-rpc-api + ${project.parent.version} + + + + com.alibaba + dubbo-remoting-http + ${project.parent.version} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.jboss.resteasy + resteasy-netty + 3.0.7.Final + + + + org.jboss.resteasy + resteasy-jdk-http + 3.0.7.Final + + + + org.jboss.resteasy + tjws + 3.0.7.Final + + + + org.jboss.resteasy + resteasy-undertow + 3.0.7.Final + + + + org.jboss.resteasy + resteasy-jackson-provider + 3.0.7.Final + + + + org.jboss.resteasy + resteasy-jaxb-provider + 3.0.7.Final + + + + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/Acme/Serve/Serve.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/Acme/Serve/Serve.java new file mode 100644 index 000000000000..a8930469556c --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/Acme/Serve/Serve.java @@ -0,0 +1,5549 @@ +// Serve - minimal Java servlet container class +// +// Copyright (C)1996,1998 by Jef Poskanzer . All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +// SUCH DAMAGE. +// +// Visit the ACME Labs Java page for up-to-date versions of this and other +// fine Java utilities: http://www.acme.com/java/ +// + +// All enhancements Copyright (C)1998-2010 by Dmitriy Rogatkin +// This version is compatible with JSDK 2.5 +// http://tjws.sourceforge.net +// $Id: Serve.java,v 1.194 2009/12/31 05:02:13 dmitriy Exp $ + +package Acme.Serve; + +import Acme.Utils; + +import javax.servlet.*; +import javax.servlet.http.*; +import java.io.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.URL; +import java.security.SecureRandom; +import java.text.MessageFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +// TODO Added this class for now since looks like there's a bug in resteasy... + +/// Minimal Java servlet container class. +//

+// This class implements a very small embeddable servlet container. +// It runs Servlets compatible with the API used by Sun's +// Java System Application server. +// Servlet API can be found here. +// It comes with default Servlets which provide the usual +// httpd services, returning files and directory listings. +//

+// This is not in any sense a competitor for Java System Application server. +// Java System Application server is a full-fledged HTTP server and more. +// Acme.Serve is tiny, about 5000 lines, and provides only the +// functionality necessary to deliver an Applet's .class files +// and then start up a Servlet talking to the Applet. +// They are both written in Java, they are both web servers, and +// they both implement the Servlet API; other than that they couldn't +// be more different. +//

+// This is actually the second HTTP server I've written. +// The other one is called +// thttpd, +// it's written in C, and is also pretty small although much more +// featureful than this. +//

+// Other Java HTTP servers: +//

+//

+// A June 1997 BYTE +// magazine article mentioning this server.
+// A December 1997 BYTE +// magazine article giving it an Editor's Choice Award of Distinction.
+// Fetch the +// software.
+// Fetch the entire Acme package. +//

+// @see Acme.Serve.servlet.http.HttpServlet +// @see FileServlet +// @see CgiServlet +//

Post notes

+// Currently the server 3 more times complex and can compete with +// most popular app and web servers used for deploying of web +// Java applications. + +// Inheritance can extend usage of this server +public class Serve implements ServletContext, Serializable +{ + + public static final String ARG_PORT = "port"; + + public static final String ARG_THROTTLES = "throttles"; + + public static final String ARG_SERVLETS = "servlets"; + + public static final String ARG_REALMS = "realms"; + + public static final String ARG_ALIASES = "aliases"; + + public static final String ARG_BINDADDRESS = "bind-address"; + + public static final String ARG_BACKLOG = "backlog"; + + public static final String ARG_CGI_PATH = "cgi-path"; + + public static final String ARG_ERR = "error-stream"; + + public static final String ARG_OUT = "out-stream"; + + public static final String ARG_SESSION_TIMEOUT = "session-timeout"; + + public static final String ARG_LOG_DIR = "log-dir"; + + public static final String ARG_LOG_OPTIONS = "log-options"; + + public static final String ARG_NOHUP = "nohup"; + + public static final String ARG_JSP = "JSP"; + + public static final String ARG_WAR = "war-deployer"; + + public static final String ARG_KEEPALIVE = "keep-alive"; + + public static final String DEF_LOGENCODING = "tjws.serve.log.encoding"; + + public static final String ARG_KEEPALIVE_TIMEOUT = "timeout-keep-alive"; + + public static final String ARG_MAX_CONN_USE = "max-alive-conn-use"; + + public static final String ARG_SESSION_PERSIST = "sssn-persistance"; + + public static final String ARG_MAX_ACTIVE_SESSIONS = "max-active-sessions"; + + public static final String ARG_ACCESS_LOG_FMT = "access-log-format"; + + public static final String ARG_ACCEPTOR_CLASS = "acceptorImpl"; + + public static final String ARG_WORK_DIRECTORY = "workdirectory"; + + public static final String ARG_SESSION_SEED = "SessionSeed"; + + public static final String ARG_THREAD_POOL_SIZE = Utils.ThreadPool.MAXNOTHREAD; + + + protected static final int DEF_SESSION_TIMEOUT = 30; // in minutes + + protected static final int DEF_MIN_ACT_SESS = 10; + + protected static final int DESTROY_TIME_SEC = 15; + + protected static final int HTTP_MAX_HDR_LEN = 1024 * 1024 * 10; + + public static final int DEF_PORT = 8080; + + public static final String BGCOLOR = "BGCOLOR=\"#D1E9FE\""; + + /** + * max number of alive connections default value + */ + protected static final int DEF_MAX_CONN_USE = 100; + + public static final String UTF8 = "UTF-8"; // default encoding + + protected String hostName; + + private transient PrintStream logStream; + + private boolean useAccLog; + + private boolean keepAlive; + + private int timeoutKeepAlive; + + private int maxAliveConnUse; + + private boolean showUserAgent; + + private boolean showReferer; + + protected String keepAliveHdrParams; + + protected transient PathTreeDictionary registry; + + protected transient PathTreeDictionary realms; + + protected transient PathTreeDictionary mappingtable; + + private Hashtable attributes; + + protected transient KeepAliveCleaner keepAliveCleaner; + + protected transient ThreadGroup serverThreads; + + protected transient Utils.ThreadPool threadPool; + + protected transient Constructor gzipInStreamConstr; + + // for sessions + private byte[] uniqer = new byte[20]; // TODO consider configurable strength + + private SecureRandom srandom; + + protected HttpSessionContextImpl sessions; + + protected int expiredIn; + + public Map arguments; + + public Properties mime; + + protected List connections = new ArrayList(); + + // / Constructor. + public Serve(Map arguments, PrintStream logStream) + { + this.arguments = arguments; + this.logStream = logStream; + registry = new PathTreeDictionary(); + realms = new PathTreeDictionary(); + attributes = new Hashtable(); + serverThreads = new ThreadGroup("TJWS threads"); + Properties props = new Properties(); + props.putAll(arguments); + // TODO do not create thread pool unless requested + threadPool = new Utils.ThreadPool(props, new Utils.ThreadFactory() + { + public Thread create(Runnable runnable) + { + Thread result = new Thread(serverThreads, runnable); + result.setDaemon(true); + return result; + } + }); + setAccessLogged(); + // modified by lishen + keepAlive = arguments.get(ARG_KEEPALIVE) == null || ((Boolean) arguments.get(ARG_KEEPALIVE)).booleanValue(); +// keepAlive = false; + System.out.println("KEEPALIVE!: " + keepAlive); + int timeoutKeepAliveSec; + try + { + timeoutKeepAliveSec = Integer.parseInt((String) arguments.get(ARG_KEEPALIVE_TIMEOUT)); + } + catch (Exception ex) + { + timeoutKeepAliveSec = 30; + } + timeoutKeepAlive = timeoutKeepAliveSec * 1000; + try + { + maxAliveConnUse = Integer.parseInt((String) arguments.get(ARG_MAX_CONN_USE)); + } + catch (Exception ex) + { + maxAliveConnUse = DEF_MAX_CONN_USE; + } + keepAliveHdrParams = "timeout=" + timeoutKeepAliveSec + ", max=" + maxAliveConnUse; + + expiredIn = arguments.get(ARG_SESSION_TIMEOUT) != null ? ((Integer) arguments.get(ARG_SESSION_TIMEOUT)) + .intValue() : DEF_SESSION_TIMEOUT; + srandom = new SecureRandom((arguments.get(ARG_SESSION_SEED) == null ? "TJWS" + new Date() : (String) arguments.get(ARG_SESSION_SEED)).getBytes()); + try + { + gzipInStreamConstr = Class.forName("java.util.zip.GZIPInputStream").getConstructor(new Class[]{InputStream.class}); + } + catch (ClassNotFoundException cne) + { + + } + catch (NoSuchMethodException nsm) + { + + } + initMime(); + } + + /** + * Default constructor to create TJWS as a bean + */ + public Serve() + { + this(new HashMap(), System.err); + } + + protected void setAccessLogged() + { + String logflags = (String) arguments.get(ARG_LOG_OPTIONS); + if (logflags != null) + { + useAccLog = true; + showUserAgent = logflags.indexOf('A') >= 0; + showReferer = logflags.indexOf('R') >= 0; + } + } + + protected boolean isAccessLogged() + { + return useAccLog; + } + + protected boolean isShowReferer() + { + return showReferer; + } + + protected boolean isShowUserAgent() + { + return showUserAgent; + } + + protected boolean isKeepAlive() + { + return keepAlive; + } + + protected int getKeepAliveDuration() + { + return timeoutKeepAlive; + } + + protected String getKeepAliveParamStr() + { + return keepAliveHdrParams; + } + + protected int getMaxTimesConnectionUse() + { + return maxAliveConnUse; + } + + protected void initMime() + { + mime = new Properties(); + try + { + mime.load(getClass().getClassLoader().getResourceAsStream("Acme/Resource/mime.properties")); + } + catch (Exception ex) + { + log("MIME map can't be loaded:" + ex); + } + } + + // / Register a Servlet by class name. Registration consists of a URL + // pattern, which can contain wildcards, and the class name of the Servlet + // to launch when a matching URL comes in. Patterns are checked for + // matches in the order they were added, and only the first match is run. + public void addServlet(String urlPat, String className) + { + addServlet(urlPat, className, (Hashtable) null); + } + + /** + * Adds a servlet to run + * + * @param urlPat servlet invoker URL pattern + * @param className servlet class name + * @param initParams servlet init parameters + */ + public void addServlet(String urlPat, String className, Hashtable initParams) + { + // Check if we're allowed to make one of these. + SecurityManager security = System.getSecurityManager(); + if (security != null) + { + int i = className.lastIndexOf('.'); + if (i > 0) + { + security.checkPackageAccess(className.substring(0, i)); + security.checkPackageDefinition(className.substring(0, i)); + } + } + + // Make a new one. + try + { + addServlet(urlPat, (Servlet) Class.forName(className).newInstance(), initParams); + } + catch (ClassNotFoundException e) + { + log("Class not found: " + className); + ClassLoader cl = getClass().getClassLoader(); + log("Class loader: " + cl); + if (cl instanceof java.net.URLClassLoader) + log("CP: " + java.util.Arrays.asList(((java.net.URLClassLoader) cl).getURLs())); + } + catch (ClassCastException e) + { + log("Servlet class doesn't implement javax.servlet.Servlet: " + e.getMessage()); + } + catch (InstantiationException e) + { + log("Can't instantiate servlet: " + e.getMessage()); + } + catch (IllegalAccessException e) + { + log("Illegal class access: " + e.getMessage()); + } + catch (Exception e) + { + log("Unexpected problem of servlet creation: " + e, e); + } + } + + /** + * Register a Servlet. Registration consists of a URL pattern, + * which can contain wildcards, and the Servlet to + * launch when a matching URL comes in. Patterns are checked for + * matches in the order they were added, and only the first match is run. + * + * @param urlPat servlet invoker URL pattern + * @param servlet already instantiated servlet but init + */ + public void addServlet(String urlPat, Servlet servlet) + { + addServlet(urlPat, servlet, (Hashtable) null); + } + + /** + * Register a Servlet + * + * @param urlPat + * @param servlet + * @param initParams + */ + public synchronized void addServlet(String urlPat, Servlet servlet, Hashtable initParams) + { + try + { + if (getServlet(urlPat) != null) + log("Servlet overriden by " + servlet + ", for path:" + urlPat); + servlet.init(new ServeConfig((ServletContext) this, initParams, urlPat)); + registry.put(urlPat, servlet); + } + catch (ServletException e) + { // + // it handles UnavailableException as well without an attempt to re-adding + log("Problem initializing servlet, it won't be used: " + e); + } + } + + public Servlet unloadServlet(Servlet servlet) + { + Servlet result = null; + synchronized (registry) + { + result = (Servlet) registry.remove(servlet)[0]; + } + return result; + } + + public synchronized void unloadServlet(String urlPat) + { + Servlet servlet = (Servlet) registry.remove(urlPat)[0]; + if (servlet != null) + servlet.destroy(); // sessions associated with it have to be invalidated to free up any the servlet specific object + // TODO decide if UnavailableException should be thrown at access + } + + // / Register a standard set of Servlets. These will return + // files or directory listings, and run CGI programs, much like a + // standard HTTP server. + //

+ // Because of the pattern checking order, this should be called + // after you've added any custom Servlets. + //

+ // The current set of default servlet mappings: + //

    + //
  • If enabled, *.cgi goes to CgiServlet, and gets run as a CGI program. + //
  • * goes to FileServlet, and gets served up as a file or directory. + //
+ // @param cgi whether to run CGI programs + // TODO: provide user specified CGI directory + public void addDefaultServlets(String cgi) + { + try + { + addDefaultServlets(cgi, null); + } + catch (IOException ioe) + { /* ignore, makes sense only for throtles */ + } + } + + /** + * Register a standard set of Servlets, with optional throttles. These will return files or directory listings, and run CGI programs, much like a standard + * HTTP server. + *

+ * Because of the pattern checking order, this should be called after you've added any custom Servlets. + *

+ * The current set of default servlet mappings: + *

    + *
  • If enabled, *.cgi goes to CgiServlet, and gets run as a CGI program. + *
  • * goes to FileServlet, and gets served up as a file or directory. + *
+ * + * @param cgi whether to run CGI programs + * @param throttles filename to read FileServlet throttle settings from, can be null + * @throws java.io.IOException + */ + public void addDefaultServlets(String cgi, String throttles) throws IOException + { + // TODO: provide user specified CGI directory + if (cgi != null) + { + if (getServlet("/" + cgi) == null) + addServlet("/" + cgi, new Acme.Serve.CgiServlet()); + else + log("Servlet for path '/" + cgi + "' already defined and no default will be used."); + } + if (getServlet("/") == null) + if (throttles != null) + addServlet("/", new Acme.Serve.FileServlet(throttles, null)); + else + addServlet("/", new Acme.Serve.FileServlet()); + else + log("Servlet for path '/' already defined and no default will be used."); + } + + protected void addWarDeployer(String deployerFactory, String throttles) + { + if (deployerFactory == null) // try to use def + deployerFactory = "rogatkin.web.WarRoller"; + try + { + WarDeployer wd = (WarDeployer) Class.forName(deployerFactory).newInstance(); + wd.deploy(this); + } + catch (ClassNotFoundException cnf) + { + log("Problem initializing war deployer: " + cnf); + } + catch (Exception e) + { + log("Problem war(s) deployment", e); + } + } + + protected File getPersistentFile() + { + if (arguments.get(ARG_SESSION_PERSIST) == null || (Boolean) arguments.get(ARG_SESSION_PERSIST) == Boolean.FALSE) + return null; + String workPath = (String) arguments.get(ARG_WORK_DIRECTORY); + if (workPath == null) + workPath = "."; + return new File(workPath, hostName + '-' + + (arguments.get(ARG_PORT) == null ? String.valueOf(DEF_PORT) : arguments.get(ARG_PORT)) + + "-session.obj"); + } + + // Run the server. Returns only on errors. + transient boolean running = true; + + protected transient Acceptor acceptor; + + protected transient Thread ssclThread; + + protected transient boolean initialized; + + protected CountDownLatch shutdownLatch; + protected Thread backgroundThread; + + public void runInBackground() + { + shutdownLatch = new CountDownLatch(1); + try + { + init(); + } + catch (IOException e) + { + throw new RuntimeException(e); + } + backgroundThread = new Thread() + { + public void run() + { + try + { + serve(); + } + finally + { + shutdownLatch.countDown(); + } + } + }; + backgroundThread.start(); + + } + + public void stopBackground() + { + try + { + notifyStop(); + } + catch (Throwable ignored) + { + } + try + { + if (shutdownLatch.await(100, TimeUnit.MILLISECONDS) == false) + { + try + { + backgroundThread.interrupt(); + } + catch (Exception ignored) + { + } + } + shutdownLatch.await(1, TimeUnit.SECONDS); + } + catch (InterruptedException e) + { + } + synchronized(connections) + { + for (ServeConnection conn : connections) + { + conn.closeSocket(); + } + connections.clear(); + } + } + + /** + * Launches the server + * It doesn't exist until server runs, so start it in a dedicated thread. + * + * @return 0 if the server successfully terminated, 1 if it can't be started and -1 if it + * was terminated during some errors + */ + public int serve() + { + try + { + while (running) + { + try + { + Socket socket = acceptor.accept(); + // TODO consider to use ServeConnection object pool + if (keepAliveCleaner != null) // we need to add regardless of keep alive + keepAliveCleaner.addConnection(new ServeConnection(socket, this)); + else + new ServeConnection(socket, this); // TODO consider req/resp objects pooling + } + catch (IOException e) + { + log("Accept: " + e); + } + catch (SecurityException se) + { + log("Illegal access: " + se); + } + catch (IllegalStateException is) + { + log("Illegal state: " + is); + } + } + } + catch (Throwable t) + { + log("Unhandled exception: " + t + ", server is terminating.", t); + if (t instanceof ThreadDeath) + throw (Error) t; + return -1; + } + finally + { + try + { + if (acceptor != null) + acceptor.destroy(); + } + catch (IOException e) + { + } + } + return 0; + } + + public void init() throws IOException + { + shutdownLatch = new CountDownLatch(1); + acceptor = createAcceptor(); + + if (expiredIn > 0) + { + ssclThread = new Thread(serverThreads, new Runnable() + { + public void run() + { + while (running) + { + try + { + Thread.sleep(expiredIn * 60 * 1000); + } + catch (InterruptedException ie) + { + if (running == false) + break; + } + Enumeration e = sessions.keys(); + while (e.hasMoreElements()) + { + Object sid = e.nextElement(); + if (sid != null) + { + AcmeSession as = (AcmeSession) sessions.get(sid); + if (as != null && (as.checkExpired() || !as.isValid())) + { // log("sesion + as = (AcmeSession) sessions.remove(sid); + if (as != null && as.isValid()) + try + { + as.invalidate(); + } + catch (IllegalStateException ise) + { + + } + } + } + } + } + } + }, "Session cleaner"); + ssclThread.setPriority(Thread.MIN_PRIORITY); + // ssclThread.setDaemon(true); + ssclThread.start(); + } // else + // expiredIn = -expiredIn; + if (isKeepAlive()) + { + keepAliveCleaner = new KeepAliveCleaner(); + keepAliveCleaner.start(); + } + File fsessions = getPersistentFile(); + if (fsessions != null && fsessions.exists()) + { + BufferedReader br = null; + try + { + br = new BufferedReader(new FileReader(fsessions)); + sessions = HttpSessionContextImpl.restore(br, Math.abs(expiredIn) * 60, this); + } + catch (IOException ioe) + { + log("Problem in restoring sessions.", ioe); + } + catch (Exception e) + { + log("Unexpected problem in restoring sessions.", e); + } + finally + { + if (br != null) + try + { + br.close(); + } + catch (IOException ioe) + { + } + } + } + if (sessions == null) + sessions = new HttpSessionContextImpl(); + // TODO: display address as name and as ip + System.out.println("[" + new Date() + "] TJWS httpd " + hostName + " - " + acceptor + " is listening."); + } + + /** + * Tells the server to stop + * + * @throws java.io.IOException + */ + public void notifyStop() throws IOException + { + running = false; + acceptor.destroy(); + acceptor = null; + if (ssclThread != null) + ssclThread.interrupt(); + } + + public static interface Acceptor + { + public void init(Map inProperties, Map outProperties) throws IOException; + + public Socket accept() throws IOException; + + public void destroy() throws IOException; + } + + protected Acceptor createAcceptor() throws IOException + { + String acceptorClass = (String) arguments.get(ARG_ACCEPTOR_CLASS); + if (acceptorClass == null) + acceptorClass = "Acme.Serve.SimpleAcceptor"; + // assured defaulting here + try + { + acceptor = (Acceptor) Class.forName(acceptorClass).newInstance(); + } + catch (InstantiationException e) + { + log("Couldn't instantiate Acceptor, the Server is inoperable", e); + } + catch (IllegalAccessException e) + { + Constructor c; + try + { + c = Class.forName(acceptorClass).getDeclaredConstructor(Utils.EMPTY_CLASSES); + c.setAccessible(true); + acceptor = (Acceptor) c.newInstance(Utils.EMPTY_OBJECTS); + } + catch (Exception e1) + { + log("Acceptor is not accessable or can't be instantiated, the Server is inoperable", e); + } + } + catch (ClassNotFoundException e) + { + log("Acceptor class not found, the Server is inoperable", e); + } + Map acceptorProperties = new Properties(); + acceptor.init(arguments, acceptorProperties); + hostName = (String) acceptorProperties.get(ARG_BINDADDRESS); + return acceptor; + } + + // Methods from ServletContext. + + // / Gets a servlet by name. + // @param name the servlet name + // @return null if the servlet does not exist + + public Servlet getServlet(String name) + { + try + { + return (Servlet) registry.get(name)[0]; + } + catch (NullPointerException npe) + { + return null; + } + } + + // / Enumerates the servlets in this context (server). Only servlets that + // are accesible will be returned. This enumeration always includes the + // servlet itself. + public Enumeration getServlets() + { + return registry.elements(); + } + + // / Enumerates the names of the servlets in this context (server). Only + // servlets that are accesible will be returned. This enumeration always + // includes the servlet itself. + public Enumeration getServletNames() + { + return registry.keys(); + } + + // / Destroys all currently-loaded servlets. + public synchronized void destroyAllServlets() + { + //log("Entering destroyAllServlets()", new Exception("Entering destroyAllServlets()")); + // serialize sessions + + // invalidate all sessions + // TODO consider merging two pieces below, generally if session is stored, + // it shouldn't be invalidated + File sf = getPersistentFile(); + if (sf != null && sessions != null) + { + Writer w = null; + try + { + w = new FileWriter(sf); + sessions.save(w); + log("Sessions stored."); + } + catch (IOException ioe) + { + log("IO problem in storing sessions " + ioe); + } + catch (Throwable t) + { + log("Problem in storing sessions " + t); + } + finally + { + try + { + w.close(); + } + catch (Exception e) + { + } + } + + Enumeration e = sessions.keys(); + while (e.hasMoreElements()) + { + Object sid = e.nextElement(); + if (sid != null) + { + AcmeSession as = (AcmeSession) sessions.get(sid); + if (as != null) + { + as = (AcmeSession) sessions.remove(sid); + if (as != null && as.isValid()) + try + { + as.invalidate(); + } + catch (IllegalStateException ise) + { + + } + } + } + } + } + // destroy servlets + final Enumeration en = registry.elements(); + Runnable servletDestroyer = new Runnable() + { + public void run() + { + ((Servlet) en.nextElement()).destroy(); + } + }; + int dhc = 0; + while (en.hasMoreElements()) + { + Thread destroyThread = new Thread(servletDestroyer, "Destroy"); + destroyThread.setDaemon(true); + destroyThread.start(); + try + { + destroyThread.join(DESTROY_TIME_SEC * 1000); + } + catch (InterruptedException e) + { + } + if (destroyThread.isAlive()) + { + log("Destroy thread didn't terminate in " + DESTROY_TIME_SEC); + destroyThread.setName("Destroy too long " + (dhc++)); // let it running with different name + //destroyThread.stop(); + } + } + // clean access tree + registry = new PathTreeDictionary(); + } + + protected void setMappingTable(PathTreeDictionary mappingtable) + { + this.mappingtable = mappingtable; + } + + protected void setRealms(PathTreeDictionary realms) + { + this.realms = realms; + } + + AcmeSession getSession(String id) + { + return (AcmeSession) sessions.get(id); + } + + HttpSession createSession() + { + Integer ms = (Integer) this.arguments.get(ARG_MAX_ACTIVE_SESSIONS); + if (ms != null && ms.intValue() < sessions.size()) + return null; + HttpSession result = new AcmeSession(generateSessionId(), Math.abs(expiredIn) * 60, this, sessions); + synchronized (sessions) + { + sessions.put(result.getId(), result); + } + return result; + } + + void removeSession(String id) + { + synchronized (sessions) + { + sessions.remove(id); + } + } + + // / Write information to the servlet log. + // @param message the message to log + public void log(String message) + { + Date date = new Date(System.currentTimeMillis()); + logStream.println("[" + date.toString() + "] " + message); + } + + public void log(String message, Throwable throwable) + { + if (throwable != null) + { + StringWriter sw; + PrintWriter pw = new PrintWriter(sw = new StringWriter()); + throwable.printStackTrace(pw); + // printCauses(throwable, pw); + message = message + '\n' + sw; + } + log(message); + } + + // protected void printCauses(Throwable throwable, PrintWriter printWriter) { + // try { + // throwable = throwable instanceof ServletException ? ((ServletException) throwable).getRootCause() + // : (Throwable) throwable.getClass().getMethod("getCause", new Class[] {}).invoke(throwable, + // new Object[] {}); + // if (throwable != null) { + // printWriter.write("Caused by:\n"); + // throwable.printStackTrace(printWriter); + // printCauses(throwable, printWriter); + // } + // } catch (Exception e) { + // } + // } + + // / Write a stack trace to the servlet log. + // @param exception where to get the stack trace + // @param message the message to log + + public void log(Exception exception, String message) + { + log(message, exception); + } + + // / Applies alias rules to the specified virtual path and returns the + // corresponding real path. It returns null if the translation + // cannot be performed. + // @param path the path to be translated + public String getRealPath(String path) + { + // try { + // path = new String(path.getBytes("ISO-8859-1"), UTF8); + // } catch (Exception ee) { // no encoding + // } + // System.err.print("[" + path + "]->["); + if (mappingtable != null) + { + // try find first sub-path + Object[] os = mappingtable.get(path); + // System.err.println("Searching for path: "+path+" found: "+os[0]); + if (os[0] == null) + return null; + int slpos = ((Integer) os[1]).intValue(); + int pl = path.length(); + if (slpos > 0) + { + if (path.length() > slpos) + path = path.substring(slpos + 1); + else + path = ""; + } + else if (pl > 0) + { + for (int i = 0; i < pl; i++) + { + char s = path.charAt(i); + if (s == '/' || s == '\\') + continue; + else + { + if (i > 0) + path = path.substring(i); + break; + } + } + } + // System.err.println("Path after processing :"+path+" slash was at + // "+slpos); + return new File((File) os[0], path).getPath(); + } + return path; + } + + /** + * @return + */ + public String getContextPath() + { + return ""; + } + + // / Returns the MIME type of the specified file. + // @param file file name whose MIME type is required + public String getMimeType(String file) + { + int dp = file.lastIndexOf('.'); + if (dp > 0) + { + return mime.getProperty(file.substring(dp + 1).toUpperCase()); + } + return null; + } + + // / Returns the name and version of the web server under which the servlet + // is running. + // Same as the CGI variable SERVER_SOFTWARE. + public String getServerInfo() + { + return Serve.Identification.serverName + " " + Serve.Identification.serverVersion + " (" + + Serve.Identification.serverUrl + ")"; + } + + // / Returns the value of the named attribute of the network service, or + // null if the attribute does not exist. This method allows access to + // additional information about the service, not already provided by + // the other methods in this interface. + public Object getAttribute(String name) + { + return attributes.get(name); + } + + // ///////////////// JSDK 2.1 extensions ////////////////////////// + public void removeAttribute(String name) + { + attributes.remove(name); + } + + public void setAttribute(String name, Object object) + { + if (object != null) + attributes.put(name, object); + else + attributes.remove(name); + } + + public Enumeration getAttributeNames() + { + return attributes.keys(); + } + + public ServletContext getContext(String uripath) + { + // TODO check webapp servlets to find out conexts for uri + return this; // only root context supported + } + + public int getMajorVersion() + { + return 2; // support 2.x + } + + public int getMinorVersion() + { + return 5; // support 2.5 + } + + // 2.3 + + /** + * Returns a directory-like listing of all the paths to resources within the web application whose longest sub-path matches the supplied path argument. + * Paths indicating subdirectory paths end with a '/'. The returned paths are all relative to the root of the web application and have a leading '/'. For + * example, for a web application containing + *

+ * /welcome.html
+ * /catalog/index.html
+ * /catalog/products.html
+ * /catalog/offers/books.html
+ * /catalog/offers/music.html
+ * /customer/login.jsp
+ * /WEB-INF/web.xml
+ * /WEB-INF/classes/com.acme.OrderServlet.class, + *

+ * getResourcePaths("/") returns {"/welcome.html", "/catalog/", "/customer/", "/WEB-INF/"}
+ * getResourcePaths("/catalog/") returns {"/catalog/index.html", "/catalog/products.html", "/catalog/offers/"}. + *

+ * + * @param the - + * partial path used to match the resources, which must start with a / + * @return a Set containing the directory listing, or null if there are no resources in the web application whose path begins with the supplied path. + * @since Servlet 2.3 + */ + public java.util.Set getResourcePaths(String path) + { + String realPath = getRealPath(path); + if (realPath != null) + { + + String[] dir = new File(realPath).list(); + if (dir.length > 0) + { + HashSet set = new HashSet(dir.length); + for (int i = 0; i < dir.length; i++) + set.add(dir[i]); + return set; + } + } + return null; + } + + /** + * Returns the name of this web application correponding to this ServletContext as specified in the deployment descriptor for this web application by the + * display-name element. + * + * @return The name of the web application or null if no name has been declared in the deployment descriptor. + * @since Servlet 2.3 + */ + public String getServletContextName() + { + return null; + } + + /** + * Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context + * root. + *

+ *

+ * This method allows the servlet container to make a resource available to servlets from any source. Resources can be located on a local or remote file + * system, in a database, or in a .war file. + *

+ *

+ * The servlet container must implement the URL handlers and URLConnection objects that are necessary to access the resource. + *

+ *

+ * This method returns null if no resource is mapped to the pathname. + *

+ *

+ * Some containers may allow writing to the URL returned by this method using the methods of the URL class. + *

+ *

+ * The resource content is returned directly, so be aware that requesting a .jsp page returns the JSP source code. Use a + * RequestDispatcher instead to include results of an execution. + *

+ *

+ * This method has a different purpose than java.lang.Class.getResource, which looks up resources based on a class loader. This method does + * not use class loaders. + * + * @param path a String specifying the path to the resource + * @return the resource located at the named path, or null if there is no resource at that path + * @throws java.net.MalformedURLException if the pathname is not given in the correct form + */ + public URL getResource(String path) throws MalformedURLException + { + if (path == null || path.length() == 0 || path.charAt(0) != '/') + throw new MalformedURLException("Path " + path + " is not in acceptable form."); + File resFile = new File(getRealPath(path)); + if (resFile.exists()) // TODO get canonical path is more robust + return new URL("file", "localhost", resFile.getPath()); + return null; + } + + /** + * Returns the resource located at the named path as an InputStream object. + *

+ *

+ * The data in the InputStream can be of any type or length. The path must be specified according to the rules given in + * getResource. This method returns null if no resource exists at the specified path. + *

+ *

+ * Meta-information such as content length and content type that is available via getResource method is lost when using this method. + *

+ *

+ * The servlet container must implement the URL handlers and URLConnection objects necessary to access the resource. + *

+ *

+ * This method is different from java.lang.Class.getResourceAsStream, which uses a class loader. This method allows servlet containers to + * make a resource available to a servlet from any location, without using a class loader. + * + * @param path a String specifying the path to the resource + * @return the InputStream returned to the servlet, or null if no resource exists at the specified path + */ + public InputStream getResourceAsStream(String path) + { + try + { + return getResource(path).openStream(); + } + catch (Exception e) + { + } + return null; + } + + public RequestDispatcher getRequestDispatcher(String urlpath) + { + if (urlpath == null || urlpath.length() == 0 || urlpath.charAt(0) != '/') + return null; + try + { + return new SimpleRequestDispatcher(urlpath); + } + catch (NullPointerException npe) + { + return null; + } + } + + // no way to specify parameters for context + public String getInitParameter(String param) + { + return null; + } + + public Enumeration getInitParameterNames() + { + return Utils.EMPTY_ENUMERATION; + } + + public RequestDispatcher getNamedDispatcher(String name) + { + // named resources are not supported + return null; + } + + synchronized String generateSessionId() + { + srandom.nextBytes(uniqer); + // TODO swap randomly bytes + return Utils.base64Encode(uniqer); + } + + protected class SimpleRequestDispatcher implements RequestDispatcher + { + HttpServlet servlet; + + String dispatchPath; + + String dispatchQuery; + + int dispatchLen; + + SimpleRequestDispatcher(String path) + { + Object[] os = registry.get(path); + servlet = (HttpServlet) os[0]; + //log("Dispatch to: " + path + ", servlet "+servlet); + if (servlet == null) + throw new NullPointerException(); + dispatchLen = ((Integer) os[1]).intValue(); + int qmp = path.indexOf('?'); + if (qmp < 0 || qmp >= path.length() - 1) + dispatchPath = path; + else + { + dispatchPath = path.substring(0, qmp); + dispatchQuery = path.substring(qmp + 1); + } + } + + public void forward(ServletRequest _request, ServletResponse _response) throws ServletException, + IOException + { + _request.removeAttribute("javax.servlet.forward.request_uri"); // reset in case of nested + _response.reset(); + servlet.service(new HttpServletRequestWrapper((HttpServletRequest) _request) + { + public String getPathInfo() + { + return dispatchLen >= dispatchPath.length() ? null : dispatchPath.substring(dispatchLen); + } + + public String getRequestURI() + { + return dispatchPath; + } + + public String getQueryString() + { + return dispatchQuery; + } + + public String getPathTranslated() + { + //System.out.println("Path t path i: "+getPathInfo()+", dp: "+dispatchPath); + return getRequest().getRealPath(getPathInfo()); + } + + public String getServletPath() + { + return dispatchLen <= 0 ? "" : dispatchPath.substring(0, dispatchLen); + } + + public synchronized Enumeration getAttributeNames() + { + if (super.getAttribute("javax.servlet.forward.request_uri") == null) + { + setAttribute("javax.servlet.forward.request_uri", super.getRequestURI()); + setAttribute("javax.servlet.forward.context_path", this.getContextPath()); + setAttribute("javax.servlet.forward.servlet_path", super.getServletPath()); + setAttribute("javax.servlet.forward.path_info", super.getPathInfo()); + setAttribute("javax.servlet.forward.query_string", super.getQueryString()); + } + return super.getAttributeNames(); + } + + public Object getAttribute(String name) + { + getAttributeNames(); // here is some overhead + return super.getAttribute(name); + } + + }, _response); + // TODO think when response isn't actual response ServeConnection + ((ServeConnection) _response).closeStreams(); // do not allow to continue + } + + public void include(ServletRequest _request, ServletResponse _response) throws ServletException, + IOException + { + _request.removeAttribute("javax.servlet.include.request_uri"); // reset in case of nested + ((Serve.ServeConnection) _response).setInInclude(true); + try + { + servlet.service(new HttpServletRequestWrapper((HttpServletRequest) _request) + { + public synchronized Enumeration getAttributeNames() + { + if (super.getAttribute("javax.servlet.include.request_uri") == null) + { + setAttribute("javax.servlet.include.request_uri", dispatchPath); + setAttribute("javax.servlet.include.context_path", this.getContextPath()); + setAttribute("javax.servlet.include.servlet_path", dispatchLen <= 0 ? "" : dispatchPath + .substring(0, dispatchLen)); + setAttribute("javax.servlet.include.path_info", dispatchLen >= dispatchPath.length() ? null + : dispatchPath.substring(dispatchLen)); + setAttribute("javax.servlet.include.query_string", dispatchQuery); + } + return super.getAttributeNames(); + } + + public Object getAttribute(String name) + { + getAttributeNames(); // here is some overhead + return super.getAttribute(name); + } + + }, _response); + } + finally + { + ((Serve.ServeConnection) _response).setInInclude(false); + } + } + + } + + // Keep Alive supporter, JDK 1.4 based for backwar compatibility + class KeepAliveCleaner extends Thread + { + protected List connections; + + protected List ingoings; + + protected volatile boolean stopped; + + private boolean noCheckClose; + + KeepAliveCleaner() + { + super("KeepAlive cleaner"); + connections = new ArrayList(); + ingoings = new ArrayList(); + setDaemon(true); + } + + public void end() + { + stopped = true; + this.interrupt(); + } + + synchronized void addConnection(ServeConnection conn) + { + synchronized (ingoings) + { + if (stopped == false) + ingoings.add(conn); + } + } + + public void run() + { + long d = getKeepAliveDuration(); + int maxUse = getMaxTimesConnectionUse(); + while (true) + { + synchronized (ingoings) + { + Iterator i = ingoings.iterator(); + while (i.hasNext()) + { + connections.add(i.next()); + i.remove(); + } + } + Iterator i = connections.iterator(); + long ct = System.currentTimeMillis(); + d = getKeepAliveDuration(); + while (i.hasNext()) + { + ServeConnection conn = (ServeConnection) i.next(); + boolean closed = conn.socket == null; + if (noCheckClose == false) + synchronized (conn) + { + if (conn.socket != null) + try + { + closed = ((Boolean) conn.socket.getClass().getMethod("isClosed", + Utils.EMPTY_CLASSES).invoke(conn.socket, Utils.EMPTY_OBJECTS)) + .booleanValue(); + } + catch (IllegalArgumentException e) + { + } + catch (SecurityException e) + { + } + catch (IllegalAccessException e) + { + } + catch (InvocationTargetException e) + { + } + catch (NoSuchMethodException e) + { + noCheckClose = true; + } + } + if (closed || (conn.keepAlive && (ct - conn.lastWait > d && conn.lastRun < conn.lastWait)) + || stopped + /* || conn.timesRequested > maxUse */) + { + i.remove(); + synchronized (conn) + { + if (conn.socket != null) + try + { + //System.err.println("Closing socket:"+conn.socket.getClass().getName()); // !!! + //conn.socket.close(); + conn.socket.getInputStream().close(); + } + catch (IOException ioe) + { + // ignore + } + //System.err.println("done"); + } + } + } + if (stopped && connections.size() == 0) + break; + try + { + sleep(d); + } + catch (InterruptedException ie) + { + stopped = true; // not thread safe + } + } + } + } + + final static class Identification + { + public static final String serverName = "D. Rogatkin's TJWS based on Acme.Serve"; + + public static final String serverVersion = "Version 1.70, $Revision: 1.194 $"; + + public static final String serverUrl = "http://tjws.sourceforge.net"; + + public static final String serverIdHtml = "

" + serverName + " " + serverVersion + "
"; + } + + // //////////////////////////////////////////////////////////////// + + protected static class ServeConfig implements ServletConfig + { + + private ServletContext context; + + private Hashtable init_params; + + private String servletName; + + public ServeConfig(ServletContext context) + { + this(context, null, "undefined"); + } + + public ServeConfig(ServletContext context, Hashtable initParams, String servletName) + { + this.context = context; + this.init_params = initParams; + this.servletName = servletName; + } + + // Methods from ServletConfig. + + // / Returns the context for the servlet. + + public ServletContext getServletContext() + { + return context; + } + + // / Gets an initialization parameter of the servlet. + // @param name the parameter name + public String getInitParameter(String name) + { + // This server supports servlet init params. :) + if (init_params != null) + return (String) init_params.get(name); + return null; + } + + // / Gets the names of the initialization parameters of the servlet. + // @param name the parameter name + public Enumeration getInitParameterNames() + { + // This server does:) support servlet init params. + if (init_params != null) + return init_params.keys(); + return new Vector().elements(); + } + + // 2.2 + public String getServletName() + { + return servletName; + } + } + + // ///////////////////////////////////////////////////////////////////// + /** + * provides request/response + */ + public static class ServeConnection implements Runnable, HttpServletRequest, HttpServletResponse + { + private Socket socket; + + private Hashtable sslAttributes; + + private Serve serve; + + private ServletInputStream in; + + private ServletOutputStream out; + + private String scheme; + + public final static String WWWFORMURLENCODE = "application/x-www-form-urlencoded"; + + public final static String TRANSFERENCODING = "transfer-encoding".toLowerCase(); + + public final static String KEEPALIVE = "Keep-Alive".toLowerCase(); + + public final static String CONTENT_ENCODING = "Content-Encoding".toLowerCase(); + + public final static String CONNECTION = "Connection".toLowerCase(); + + public final static String CHUNKED = "chunked"; + + public final static String CONTENTLENGTH = "Content-Length".toLowerCase(); + + public final static String CONTENTTYPE = "Content-Type".toLowerCase(); + + public final static String SETCOOKIE = "Set-Cookie".toLowerCase(); + + public final static String HOST = "Host".toLowerCase(); + + public final static String COOKIE = "Cookie".toLowerCase(); + + public final static String ACCEPT_LANGUAGE = "Accept-Language".toLowerCase(); + + public final static String SESSION_COOKIE_NAME = "JSESSIONID"; + + public final static String SESSION_URL_NAME = ";$sessionid$"; // ;jsessionid= + + private static final Map EMPTYHASHTABLE = new Hashtable(); + + // URL rewriting + // http://www.myserver.com/catalog/index.html;jsessionid=mysession1928 + // like: + // http://www.sun.com/2001-0227/sunblade/;$sessionid$AD5RQ0IAADJAZAMTA1LU5YQ + + private String reqMethod; // == null by default + + private String reqUriPath, reqUriPathUn; + + private String reqProtocol; + + private String charEncoding; // req and resp + + private String remoteUser; + + private String authType; + + private boolean oneOne; // HTTP/1.1 or better + + private boolean reqMime; + + private Vector reqHeaderNames = new Vector(); + + private Vector reqHeaderValues = new Vector(); + + private Locale locale; // = java.util.Locale.getDefault(); + + private int uriLen; + + protected boolean keepAlive = true; + + protected int timesRequested; + + protected long lastRun, lastWait; + + private Vector outCookies; + + private Vector inCookies; + + private String sessionCookieValue, sessionUrlValue, sessionValue; + + protected String reqQuery; + + private PrintWriter pw; + + private ServletOutputStream rout; + + private Map formParameters; + + private Hashtable attributes = new Hashtable(); + + private int resCode = -1; + + private String resMessage; + + private Hashtable resHeaderNames = new Hashtable(); + + private String[] postCache; + + private boolean headersWritten; + + private MessageFormat accessFmt; + + private Object[] logPlaceholders; + + // TODO consider creation an instance per thread in a pool, thread memory can be used + + private final SimpleDateFormat expdatefmt = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss 'GMT'", Locale.US); // used for cookie + + private final SimpleDateFormat rfc850DateFmt = new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss 'GMT'", + Locale.US); // rfc850-date + + private final SimpleDateFormat headerdateformat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", + Locale.US); // rfc1123-date + + private final SimpleDateFormat asciiDateFmt = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy", Locale.US); // ASCII date, used in headers + + private static final TimeZone tz = TimeZone.getTimeZone("GMT"); + + static + { + tz.setID("GMT"); + } + + /* + * protected void finalize() throws Throwable { serve.log("Connection collected"); super.finalize(); } + */ + + // / Constructor. + + public ServeConnection(Socket socket, Serve serve) + { + // Save arguments. + this.socket = socket; + this.serve = serve; + expdatefmt.setTimeZone(tz); + headerdateformat.setTimeZone(tz); + rfc850DateFmt.setTimeZone(tz); + asciiDateFmt.setTimeZone(tz); + if (serve.isAccessLogged()) + { + // not format string must be not tull + accessFmt = new MessageFormat((String) serve.arguments.get(ARG_ACCESS_LOG_FMT)); + logPlaceholders = new Object[12]; + } + serve.threadPool.executeThread(this); + synchronized(serve.connections) + { + serve.connections.add(this); + } + } + + private void initSSLAttrs() + { + if (socket.getClass().getName().indexOf("SSLSocket") > 0) + { + try + { + sslAttributes = new Hashtable(); + Object sslSession = socket.getClass().getMethod("getSession", Utils.EMPTY_CLASSES).invoke(socket, + Utils.EMPTY_OBJECTS); + if (sslSession != null) + { + sslAttributes.put("javax.net.ssl.session", sslSession); + Method m = sslSession.getClass().getMethod("getCipherSuite", Utils.EMPTY_CLASSES); + m.setAccessible(true); + sslAttributes.put("javax.net.ssl.cipher_suite", m.invoke(sslSession, Utils.EMPTY_OBJECTS)); + m = sslSession.getClass().getMethod("getPeerCertificates", Utils.EMPTY_CLASSES); + m.setAccessible(true); + sslAttributes.put("javax.net.ssl.peer_certificates", m.invoke(sslSession, Utils.EMPTY_OBJECTS)); + } + } + catch (IllegalAccessException iae) + { + sslAttributes = null; + //iae.printStackTrace(); + } + catch (NoSuchMethodException nsme) + { + sslAttributes = null; + //nsme.printStackTrace(); + } + catch (InvocationTargetException ite) + { + // note we do not clear attributes, because SSLPeerUnverifiedException + // happens in the last call, when no client sertificate + //sslAttributes = null; + //ite.printStackTrace(); + } + catch (IllegalArgumentException iae) + { + //sslAttributes = null; + //iae.printStackTrace(); + } + //System.err.println("Socket SSL attrs: "+sslAttributes); + } + } + + /** + * it closes stream awaring of keep -alive + * + * @throws java.io.IOException + */ + public void closeStreams() throws IOException + { + //System.err.println("===>CLOSE()"); + IOException ioe = null; + try + { + if (pw != null) + pw.flush(); + else + out.flush(); + } + catch (IOException io1) + { + ioe = io1; + } + try + { + out.close(); + } + catch (IOException io1) + { + if (ioe != null) + ioe = (IOException) ioe.initCause(io1); + else + ioe = io1; + } + try + { + in.close(); + } + catch (IOException io1) + { + if (ioe != null) + ioe = (IOException) ioe.initCause(io1); + else + ioe = io1; + } + if (ioe != null) + throw ioe; + } + + public void closeSocket() + { + if (socket != null) + { + try + { + socket.close(); + } + catch (IOException e) + { + } + } + } + + // protected void finalize() throws Throwable { + // System.err.println("Connection object gone"); // !!! + // super.finalize(); + // } + + private void restart() + { + // new Exception("RESTART").printStackTrace(); + reqMethod = null; + reqUriPath = reqUriPathUn = null; + reqProtocol = null; + charEncoding = null; + remoteUser = null; + authType = null; + oneOne = false; + reqMime = false; + // considering that clear() works faster than new + if (reqHeaderNames == null) + reqHeaderNames = new Vector(); + else + reqHeaderNames.clear(); + if (reqHeaderValues == null) + reqHeaderValues = new Vector(); + else + reqHeaderValues.clear(); + locale = null; + uriLen = 0; + outCookies = null; + inCookies = null; + sessionCookieValue = null; + sessionUrlValue = null; + sessionValue = null; + reqQuery = null; + pw = null; + rout = null; + formParameters = null; + if (attributes == null) + attributes = new Hashtable(); + else + attributes.clear(); + if (sslAttributes != null) + attributes.putAll(sslAttributes); + resCode = -1; + resMessage = null; + resHeaderNames.clear(); + headersWritten = false; + postCache = null; + ((ServeInputStream) in).refresh(); + ((ServeOutputStream) out).refresh(); + } + + // Methods from Runnable. + public void run() + { + try + { + initSSLAttrs(); + in = new ServeInputStream(socket.getInputStream(), this); + out = new ServeOutputStream(socket.getOutputStream(), this); + do + { + restart(); + // Get the streams. + parseRequest(); + if (reqMethod != null && serve.isAccessLogged()) + { + // consider caching socket stuff for faster logging + // {0} {1} {2} [{3,date,dd/MMM/yyyy:HH:mm:ss Z}] \"{4} {5} {6}\" {7,number,#} {8,number} {9} {10} + // ARG_ACCESS_LOG_FMT + logPlaceholders[0] = socket.getInetAddress(); // IP + logPlaceholders[1] = "-"; // the RFC 1413 identity of the client + logPlaceholders[2] = remoteUser == null ? "-" : remoteUser; // remote user + logPlaceholders[3] = new Date(lastRun); // time stamp {3,date,dd/MMM/yyyy:HH:mm:ss Z} {3,time,} + logPlaceholders[4] = reqMethod; // method + logPlaceholders[5] = reqUriPathUn; // resource + logPlaceholders[6] = reqProtocol; // protocol + logPlaceholders[7] = new Integer(resCode); // res code + logPlaceholders[8] = new Long(((ServeOutputStream) out).lengthWritten()); + logPlaceholders[9] = new Integer(socket.getLocalPort()); + logPlaceholders[10] = serve.isShowReferer() ? getHeader("Referer") : "-"; + logPlaceholders[11] = serve.isShowUserAgent() ? getHeader("User-Agent") : "-"; + serve.logStream.println(accessFmt.format(logPlaceholders)); + } + lastRun = 0; + timesRequested++; + } while (keepAlive && serve.isKeepAlive() && timesRequested < serve.getMaxTimesConnectionUse()); + } + catch (IOException ioe) + { + //System.err.println("Drop "+ioe); + String errMsg = ioe.getMessage(); + if ((errMsg == null || errMsg.indexOf("ocket closed") < 0) && ioe instanceof java.nio.channels.AsynchronousCloseException == false) + serve.log("IO error: " + ioe + " in processing a request from " + socket.getInetAddress() + ":" + + socket.getLocalPort() + " / " + socket.getClass().getName()/*, ioe*/); + else + synchronized (this) + { + //serve.log("Exception considered as socket closed:"+ioe, ioe); + socket = null; + } + } + finally + { + synchronized (this) + { + synchronized(serve.connections) + { + serve.connections.remove(this); + } + if (socket != null) + try + { + socket.close(); + } + catch (IOException e) + { /* ignore */ + } + socket = null; + } + } + } + + private void parseRequest() throws IOException + { + byte[] lineBytes = new byte[4096]; + int len; + String line; + // / TODO put time mark here for start waiting for receiving requests + lastWait = System.currentTimeMillis(); + // Read the first line of the request. + len = in.readLine(lineBytes, 0, lineBytes.length); + if (len == -1 || len == 0) + { + if (keepAlive) + { + keepAlive = false; + // connection seems be closed + + } + else + { + problem("Status-Code 400: Bad Request(empty)", SC_BAD_REQUEST); + } + return; + } + if (len >= lineBytes.length) + { + problem("Status-Code 414: Request-URI Too Long", SC_REQUEST_URI_TOO_LONG); + return; + } + // //lastRun = 0; // to avoid closing socket in long process + line = new String(lineBytes, 0, len, UTF8); + StringTokenizer ust = new StringTokenizer(line); + if (ust.hasMoreTokens()) + { + reqMethod = ust.nextToken(); + if (ust.hasMoreTokens()) + { + reqUriPathUn = ust.nextToken(); + // TODO make it only when URL overwrite enambled + int uop = reqUriPathUn.indexOf(SESSION_URL_NAME); + if (uop > 0) + { + sessionUrlValue = reqUriPathUn.substring(uop + SESSION_URL_NAME.length()); + reqUriPathUn = reqUriPathUn.substring(0, uop); + try + { + serve.getSession(sessionUrlValue).userTouch(); + } + catch (NullPointerException npe) + { + sessionUrlValue = null; + } + catch (IllegalStateException ise) + { + sessionUrlValue = null; + } + } + if (ust.hasMoreTokens()) + { + reqProtocol = ust.nextToken(); + oneOne = !reqProtocol.toUpperCase().equals("HTTP/1.0"); + reqMime = true; + // Read the rest of the lines. + String s; + while ((s = ((ServeInputStream) in).readLine(HTTP_MAX_HDR_LEN)) != null) + { + if (s.length() == 0) + break; + int c = s.indexOf(':', 0); + if (c > 0) + { + String key = s.substring(0, c).trim().toLowerCase(); + String value = s.substring(c + 1).trim(); + reqHeaderNames.addElement(key); + reqHeaderValues.addElement(value); + if (CONNECTION.equalsIgnoreCase(key)) + if (oneOne) + keepAlive = "close".equalsIgnoreCase(value) == false; + else + keepAlive = KEEPALIVE.equalsIgnoreCase(value); + else if (KEEPALIVE.equalsIgnoreCase(key)) + { /// FF specific ? + // parse value to extract the connection specific timeoutKeepAlive and maxAliveConnUse + // todo that introduce the value in req/resp and copy defaults from Serve + + } + } + else + serve.log("header field '" + s + "' without ':'"); + } + } + else + { + reqProtocol = "HTTP/0.9"; + oneOne = false; + reqMime = false; + } + } + } + + if (reqProtocol == null) + { + problem("Status-Code 400: Malformed request line:" + line, SC_BAD_REQUEST); + return; + } + // Check Host: header in HTTP/1.1 requests. + if (oneOne) + { + String host = getHeader(HOST); + if (host == null) + { + problem("'Host' header missing in HTTP/1.1 request", SC_BAD_REQUEST); + return; + } + } + + // Split off query string, if any. + int qmark = reqUriPathUn.indexOf('?'); + if (qmark > -1) + { + if (qmark < reqUriPathUn.length() - 1) + reqQuery = reqUriPathUn.substring(qmark + 1); + reqUriPathUn = reqUriPathUn.substring(0, qmark); + } + reqUriPath = Utils.decode(reqUriPathUn, UTF8); + // TDOD check if reqUriPathUn starts with http://host:port + if (CHUNKED.equals(getHeader(TRANSFERENCODING))) + { + setHeader(CONTENTLENGTH, null); + ((ServeInputStream) in).chunking(true); + } + String contentEncoding = extractEncodingFromContentType(getHeader(CONTENTTYPE)); + // TODO: encoding in request can be invalid, then do default + setCharacterEncoding(contentEncoding != null ? contentEncoding : UTF8); + String contentLength = getHeader(CONTENTLENGTH); + if (contentLength != null) + try + { + ((ServeInputStream) in).setContentLength(Long.parseLong(contentLength)); + } + catch (NumberFormatException nfe) + { + serve.log("Invalid value of input content-length: " + contentLength); + } + // the code was originally in processing headers loop, however hhas been moved here + String encoding = getHeader(CONTENT_ENCODING); + /* Don't do content encoding. Let RESTEASY handle it + if (encoding != null) + { + if ((encoding.equalsIgnoreCase("gzip") || encoding.equalsIgnoreCase("compressed")) + && null != serve.gzipInStreamConstr && ((ServeInputStream) in).compressed(true)) + { + } + else + { + problem("Status-Code 415: Unsupported media type:" + encoding, SC_UNSUPPORTED_MEDIA_TYPE); + return; + } + } + */ + if (assureHeaders() && socket.getKeepAlive() == false) + socket.setKeepAlive(true); + // TODO new SimpleRequestDispatcher(reqUriPathUn).forward((ServletRequest) this, (ServletResponse) this); + Object[] os = serve.registry.get(reqUriPath); + if (os[0] != null) + { // note, os always not null + // / TODO put time mark here to monitor actual servicing + lastRun = System.currentTimeMillis(); + // System.err.println("Servlet "+os[0]+" for path "+reqUriPath); + uriLen = ((Integer) os[1]).intValue(); + runServlet((HttpServlet) os[0]); + } + else + { + problem("No any servlet found for serving " + reqUriPath, SC_BAD_REQUEST); + } + } + + private boolean assureHeaders() + { + if (reqMime) + setHeader("MIME-Version", "1.0"); + setDateHeader("Date", System.currentTimeMillis()); + setHeader("Server", Serve.Identification.serverName + "/" + Serve.Identification.serverVersion); + if (keepAlive && serve.isKeepAlive()) + { + if (reqMime) + { + setHeader(CONNECTION, KEEPALIVE); // set for 1.1 too, because some client do not follow a standard + if (oneOne) + setHeader(KEEPALIVE, serve.getKeepAliveParamStr()); + } + return true; + } + else + setHeader(CONNECTION, "close"); + return false; + } + + private void runServlet(HttpServlet servlete) throws IOException + { + // Set default response fields. + setStatus(SC_OK); + try + { + parseCookies(); + if (sessionValue == null) // not from cookie + sessionValue = sessionUrlValue; + if (authenificate()) + { + if (servlete instanceof SingleThreadModel) + synchronized (servlete) + { + servlete.service((ServletRequest) this, (ServletResponse) this); + } + else + servlete.service((ServletRequest) this, (ServletResponse) this); + } + // old close + } + catch (UnavailableException e) + { + if (e.isPermanent()) + { + serve.registry.remove(servlete); + servlete.destroy(); + } + else if (e.getUnavailableSeconds() > 0) + serve.log("Temporary unavailability feature is not supported " + servlete); + problem(e.getMessage(), SC_SERVICE_UNAVAILABLE); + } + catch (ServletException e) + { + serve.log("Servlet exception", e); + Throwable rootCause = e.getRootCause(); + while (rootCause != null) + { + serve.log("Caused by", rootCause); + if (rootCause instanceof ServletException) + rootCause = ((ServletException) rootCause).getRootCause(); + else + rootCause = rootCause.getCause(); /* 1.4 */ + } + problem(e.toString(), SC_INTERNAL_SERVER_ERROR); + } + catch (IOException ioe) + { + throw ioe; + } + catch (Exception e) + { + serve.log("Unexpected problem running servlet", e); + problem("Unexpected problem running servlet: " + e.toString(), SC_INTERNAL_SERVER_ERROR); + } + finally + { + closeStreams(); + // socket will be closed by a caller if no keep-alive + } + } + + private boolean authenificate() throws IOException + { + Object[] o = serve.realms.get(reqUriPath); // by Niel Markwick + BasicAuthRealm realm = null; + if (o != null) + realm = (BasicAuthRealm) o[0]; + // System.err.println("looking for realm for path "+getPathInfo()+" + // in + // "+serve.realms+" found "+realm); + if (realm == null) + return true; + + String credentials = getHeader("Authorization"); + + if (credentials != null) + { + credentials = Acme.Utils.base64Decode(credentials.substring(credentials.indexOf(' ') + 1), + getCharacterEncoding()); + int i = credentials.indexOf(':'); + String user = credentials.substring(0, i); + String password = credentials.substring(i + 1); + remoteUser = user; + authType = "BASIC"; // support only basic authenification (FORM, CLIENT_CERT, DIGEST ) + String realPassword = (String) realm.get(user); + // System.err.println("User "+user+" Password "+password+" real + // "+realPassword); + if (realPassword != null && realPassword.equals(password)) + return true; + } + + setStatus(SC_UNAUTHORIZED); + setHeader("WWW-Authenticate", "basic realm=\"" + realm.name() + '"'); + //writeHeaders(); // because sendError() is used + realSendError(); + return false; + } + + private void problem(String logMessage, int resCode) + { + serve.log(logMessage); + try + { + sendError(resCode, logMessage); + } + catch (IllegalStateException e) + { /* ignore */ + } + catch (IOException e) + { /* ignore */ + } + } + + private static final int MAYBEVERSION = 1; + + private static final int INVERSION = 2; + + private static final int OLD_INNAME = 3; + + private static final int OLD_INVAL = 4; + + private static final int INVERSIONNUM = 5; + + private static final int RECOVER = 6; + + private static final int NEW_INNAME = 7; + + private static final int NEW_INVAL = 8; + + private static final int INPATH = 9; + + private static final int MAYBEINPATH = 10; + + private static final int INPATHVALUE = 11; + + private static final int MAYBEPORT = 12; + + private static final int INDOMAIN = 13; + + private static final int MAYBEDOMAIN = 14; + + private static final int INPORT = 15; + + private static final int INDOMAINVALUE = 16; + + private static final int INPORTVALUE = 17; + + private void parseCookies() throws IOException + { + if (inCookies == null) + inCookies = new Vector(); + String cookies = getHeader(COOKIE); + if (cookies == null) + return; + try + { + String cookie_name = null; + String cookie_value = null; + String cookie_path = null; + String cookie_domain = null; + if (cookies.length() > 300 * 4096) + throw new IOException("Cookie string too long:" + cookies.length()); + //System.err.println("We received:" + cookies); + char[] cookiesChars = cookies.toCharArray(); + int state = MAYBEVERSION; + StringBuffer token = new StringBuffer(256); + boolean quoted = false; + for (int i = 0; i < cookiesChars.length; i++) + { + char c = cookiesChars[i]; + + switch (state) + { + case MAYBEVERSION: + if (c != ' ') + { + token.append(c); + if (c == '$') + { + state = INVERSION; // RFC 2965 + } + else + // RFC 2109 + state = OLD_INNAME; + } + break; + case OLD_INNAME: + if (c == '=') + { + state = OLD_INVAL; + cookie_name = token.toString(); + token.setLength(0); + } + else if (c != ' ' || token.length() > 0) + token.append(c); + break; + // TODO introduce val_start. then quoted value and value + case OLD_INVAL: + if (quoted == false) + { + if (c == ';') + { + state = OLD_INNAME; + cookie_value = token.toString(); + token.setLength(0); + addCookie(cookie_name, cookie_value, null, null); + } + else if (c == '"' && token.length() == 0) + quoted = true; + else + token.append(c); + } + else + { + if (c == '"') + quoted = false; + else + token.append(c); + } + break; + case INVERSION: + if (c == '=') + { + if ("$Version".equals(token.toString())) + state = INVERSIONNUM; + else + { + state = OLD_INVAL; // consider name starts with $ + cookie_name = token.toString(); + } + token.setLength(0); + } + else + token.append(c); + break; + case INVERSIONNUM: + if (c == ',' || c == ';') + { + token.setLength(0); + state = NEW_INNAME; + } + else if (Character.isDigit(c) == false) + { + state = RECOVER; + } + else + token.append(c); + break; + case NEW_INNAME: + if (c == '=') + { + state = NEW_INVAL; + cookie_name = token.toString(); + token.setLength(0); + } + else if (c != ' ' || token.length() > 0) + token.append(c); + break; + case NEW_INVAL: + if (c == ';') + { + state = MAYBEINPATH; + cookie_value = token.toString(); + token.setLength(0); + cookie_path = null; + } + else if (c == ',') + { + state = NEW_INNAME; + cookie_value = token.toString(); + token.setLength(0); + addCookie(cookie_name, cookie_value, null, null); + } + else + token.append(c); + break; + case MAYBEINPATH: + if (c != ' ') + { + token.append(c); + if (c == '$') + { + state = INPATH; + } + else + { + addCookie(cookie_name, cookie_value, null, null); + state = NEW_INNAME; + } + } + break; + case INPATH: + if (c == '=') + { + if ("$Path".equals(token.toString())) + state = INPATHVALUE; + else + { + addCookie(cookie_name, cookie_value, null, null); + state = NEW_INVAL; // consider name starts with $ + cookie_name = token.toString(); + } + token.setLength(0); + } + else + token.append(c); + break; + case INPATHVALUE: + if (c == ',') + { + cookie_path = token.toString(); + state = NEW_INNAME; + addCookie(cookie_name, cookie_value, cookie_path, null); + token.setLength(0); + } + else if (c == ';') + { + state = MAYBEDOMAIN; + cookie_path = token.toString(); + token.setLength(0); + } + else + token.append(c); + break; + case MAYBEDOMAIN: + if (c != ' ') + { + token.append(c); + if (c == '$') + { + state = INDOMAIN; + } + else + { + addCookie(cookie_name, cookie_value, cookie_path, null); + state = NEW_INNAME; + } + } + break; + case INDOMAIN: + if (c == '=') + { + if ("$Domain".equals(token.toString())) + state = INDOMAINVALUE; + else + { + addCookie(cookie_name, cookie_value, cookie_path, null); + state = NEW_INVAL; // consider name starts with $ + cookie_name = token.toString(); + } + token.setLength(0); + } + break; + case INDOMAINVALUE: + if (c == ',') + { + state = NEW_INNAME; + addCookie(cookie_name, cookie_value, cookie_path, token.toString()); + token.setLength(0); + } + else if (c == ';') + { + cookie_domain = token.toString(); + state = MAYBEPORT; + } + else + token.append(c); + break; + case MAYBEPORT: + if (c != ' ') + { + token.append(c); + if (c == '$') + { + state = INPORT; + } + else + { + addCookie(cookie_name, cookie_value, cookie_path, cookie_domain); + state = NEW_INNAME; + } + } + break; + case INPORT: + if (c == '=') + { + if ("$Port".equals(token.toString())) + state = INPORTVALUE; + else + { + addCookie(cookie_name, cookie_value, cookie_path, cookie_domain); + state = NEW_INVAL; // consider name starts with $ + cookie_name = token.toString(); + } + token.setLength(0); + } + break; + case INPORTVALUE: + if (c == ',' || c == ';') + { + int port = Integer.parseInt(token.toString()); + state = NEW_INNAME; + addCookie(cookie_name, cookie_value, cookie_path, cookie_domain); + token.setLength(0); + } + else if (Character.isDigit(c) == false) + { + state = RECOVER; + } + else + token.append(c); + break; + case RECOVER: + serve.log("Parsing recover of cookie string " + cookies, null); + if (c == ';' || c == ',') + { + token.setLength(0); + state = NEW_INNAME; + } + break; + } + } + if (state == OLD_INVAL || state == NEW_INVAL) + { + cookie_value = token.toString(); + addCookie(cookie_name, cookie_value, null, null); + } + else if (state == INPATHVALUE) + { + addCookie(cookie_name, cookie_value, token.toString(), null); + } + else if (state == INDOMAINVALUE) + { + addCookie(cookie_name, cookie_value, cookie_path, token.toString()); + } + else if (state == INPORTVALUE) + addCookie(cookie_name, cookie_value, cookie_path, cookie_domain); + } + catch (Error e) + { + serve.log("Error in parsing cookies: " + cookies, e); + } + catch (Exception e) + { + serve.log("An exception in parsing cookies: " + cookies, e); + } + } + + private void addCookie(String name, String value, String path, String domain) + { + if (SESSION_COOKIE_NAME.equals(name) && sessionCookieValue == null) + { + sessionCookieValue = value; + try + { + serve.getSession(sessionCookieValue).userTouch(); + sessionValue = sessionCookieValue; + sessionUrlValue = null; + } + catch (IllegalStateException ise) + { + sessionCookieValue = null; + } + catch (NullPointerException npe) + { + sessionCookieValue = null; + } + } + else + { + Cookie c; + inCookies.addElement(c = new Cookie(name, value)); + if (path != null) + { + c.setPath(path); + if (domain != null) + c.setDomain(domain); + } + } + } + + // Methods from ServletRequest. + + // / Returns the size of the request entity data, or -1 if not known. + // Same as the CGI variable CONTENT_LENGTH. + + public int getContentLength() + { + return getIntHeader(CONTENTLENGTH); + } + + // / Returns the MIME type of the request entity data, or null if + // not known. + // Same as the CGI variable CONTENT_TYPE. + public String getContentType() + { + return getHeader(CONTENTTYPE); + } + + // / Returns the protocol and version of the request as a string of + // the form /.. + // Same as the CGI variable SERVER_PROTOCOL. + public String getProtocol() + { + return reqProtocol; + } + + // / Returns the scheme of the URL used in this request, for example + // "http", "https", or "ftp". Different schemes have different rules + // for constructing URLs, as noted in RFC 1738. The URL used to create + // a request may be reconstructed using this scheme, the server name + // and port, and additional information such as URIs. + public String getScheme() + { + if (scheme == null) + // lazy stuf dlc + synchronized (this) + { + if (scheme == null) + scheme = socket.getClass().getName().indexOf("SSLSocket") > 0 ? "https" : "http"; + } + return scheme; + } + + // / Returns the host name of the server as used in the part of + // the request URI. + // Same as the CGI variable SERVER_NAME. + public String getServerName() + { + String serverName; + serverName = getHeader(HOST); + if (serverName != null && serverName.length() > 0) + { + int colon = serverName.indexOf(':'); + if (colon >= 0) + { + if (colon < serverName.length()) + serverName = serverName.substring(0, colon); + } + } + + if (serverName == null) + { + try + { + serverName = InetAddress.getLocalHost().getHostName(); + } + catch (java.net.UnknownHostException ignore) + { + serverName = "127.0.0.0"; + } + } + + int slash = serverName.indexOf("/"); + if (slash >= 0) + serverName = serverName.substring(slash + 1); + return serverName; + } + + // / Returns the port number on which this request was received as used + // in + // the part of the request URI. + // Same as the CGI variable SERVER_PORT. + public int getServerPort() + { + return socket.getLocalPort(); + } + + // / Returns the IP address of the agent that sent the request. + // Same as the CGI variable REMOTE_ADDR. + public String getRemoteAddr() + { + return socket.getInetAddress().getHostAddress(); + } + + // / Returns the fully qualified host name of the agent that sent the + // request. + // Same as the CGI variable REMOTE_HOST. + public String getRemoteHost() + { + String result = socket.getInetAddress().getHostName(); + return result != null ? result : getRemoteAddr(); + } + + // / Applies alias rules to the specified virtual path and returns the + // corresponding real path, or null if the translation can not be + // performed for any reason. For example, an HTTP servlet would + // resolve the path using the virtual docroot, if virtual hosting is + // enabled, and with the default docroot otherwise. Calling this + // method with the string "/" as an argument returns the document root. + public String getRealPath(String path) + { + return serve.getRealPath(path); + } + + // / Returns an input stream for reading request data. + // @exception IllegalStateException if getReader has already been called + // @exception IOException on other I/O-related errors + public ServletInputStream getInputStream() throws IOException + { + synchronized (in) + { + if (((ServeInputStream) in).isReturnedAsReader()) + throw new IllegalStateException("Already returned as a reader."); + ((ServeInputStream) in).setReturnedAsStream(true); + } + return in; + } + + // / Returns a buffered reader for reading request data. + // @exception UnsupportedEncodingException if the character set encoding + // isn't supported + // @exception IllegalStateException if getInputStream has already been + // called + // @exception IOException on other I/O-related errors + public BufferedReader getReader() + { + synchronized (in) + { + if (((ServeInputStream) in).isReturnedAsStream()) + throw new IllegalStateException("Already returned as a stream."); + ((ServeInputStream) in).setReturnedAsReader(true); + } + if (charEncoding != null) + try + { + return new BufferedReader(new InputStreamReader(in, charEncoding)); + } + catch (UnsupportedEncodingException uee) + { + } + return new BufferedReader(new InputStreamReader(in)); + } + + private synchronized Map getParametersFromRequest() + { + Map result = null; + if ("GET".equals(reqMethod)) + { + if (reqQuery != null) + try + { + result = Acme.Utils.parseQueryString(reqQuery, charEncoding); + } + catch (IllegalArgumentException ex) + { + serve.log("Exception " + ex + " at parsing 'get' data " + reqQuery); + } + } + else if ("POST".equals(reqMethod)) + { + String contentType = getContentType(); + if (contentType != null && WWWFORMURLENCODE.regionMatches(true, 0, contentType, 0, WWWFORMURLENCODE.length())) + { + if (postCache == null) + { + postCache = new String[1]; + InputStream is = null; + try + { + result = Acme.Utils.parsePostData(getContentLength(), is = getInputStream(), charEncoding, + postCache); + } + catch (Exception ex) + { + serve.log("Exception " + ex + " at parsing 'POST' data of length " + getContentLength()); + // TODO propagate the exception ? + return EMPTYHASHTABLE; + } + } + else + result = Acme.Utils.parseQueryString(postCache[0], charEncoding); + if (reqQuery != null && reqQuery.length() > 0) + result.putAll(Acme.Utils.parseQueryString(reqQuery, charEncoding)); + } + else if (reqQuery != null) + result = Acme.Utils.parseQueryString(reqQuery, charEncoding); + } + return result != null ? result : EMPTYHASHTABLE; + } + + // / Returns the parameter names for this request. + public synchronized Enumeration getParameterNames() + { + if (formParameters == null) + formParameters = getParametersFromRequest(); + return ((Hashtable) formParameters).keys(); + } + + // / Returns the value of the specified query string parameter, or null + // if not found. + // @param name the parameter name + public String getParameter(String name) + { + String[] params = getParameterValues(name); + if (params == null || params.length == 0) + return null; + + return params[0]; + } + + // / Returns the values of the specified parameter for the request as an + // array of strings, or null if the named parameter does not exist. + public synchronized String[] getParameterValues(String name) + { + if (formParameters == null) + getParameterNames(); + + return (String[]) formParameters.get(name); + } + + // / Returns the value of the named attribute of the request, or null if + // the attribute does not exist. This method allows access to request + // information not already provided by the other methods in this + // interface. + public Object getAttribute(String name) + { + // System.err.println("!!!Get att orig:"+name+"="+attributes.get(name)); + return attributes.get(name); + } + + // Methods from HttpServletRequest. + + // / Gets the array of cookies found in this request. + + public Cookie[] getCookies() + { + Cookie[] cookieArray = new Cookie[inCookies.size()]; + inCookies.copyInto(cookieArray); + return cookieArray; + } + + // / Returns the method with which the request was made. This can be + // "GET", + // "HEAD", "POST", or an extension method. + // Same as the CGI variable REQUEST_METHOD. + public String getMethod() + { + return reqMethod; + } + + /** + * **************************************************************************************************************************************************** + * Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. To reconstruct an URL + * with a scheme and host, use HttpUtils.getRequestURL(javax.servlet.http.HttpServletRequest). + */ + // / Returns the full request URI. + public String getRequestURI() + { + return reqUriPathUn; + } + + /** + * Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port number, and server path, but it + * does not include query string parameters.
+ * Because this method returns a StringBuffer, not a string, you can modify the URL easily, for example, to append query parameters. + *

+ * This method is useful for creating redirect messages and for reporting errors. + * + * @return a StringBuffer object containing the reconstructed URL + * @since 2.3 + */ + public StringBuffer getRequestURL() + { + int port = getServerPort(); + return new StringBuffer().append(getScheme()).append("://").append(getServerName()).append( + "https".equals(getScheme()) && port == 443 || port == 80 ? "" : ":" + String.valueOf(port)).append( + getRequestURI()); + } + + // / Returns the part of the request URI that referred to the servlet + // being + // invoked. + // Analogous to the CGI variable SCRIPT_NAME. + public String getServletPath() + { + // In this server, the entire path is regexp-matched against the + // servlet pattern, so there's no good way to distinguish which + // part refers to the servlet. + return uriLen > 0 ? reqUriPath.substring(0, uriLen) : ""; + } + + // / Returns optional extra path information following the servlet path, + // but + // immediately preceding the query string. Returns null if not + // specified. + // Same as the CGI variable PATH_INFO. + public String getPathInfo() + { + // In this server, the entire path is regexp-matched against the + // servlet pattern, so there's no good way to distinguish which + // part refers to the servlet. + return uriLen >= reqUriPath.length() ? null : reqUriPath.substring(uriLen); + } + + // / Returns extra path information translated to a real path. Returns + // null if no extra path information was specified. + // Same as the CGI variable PATH_TRANSLATED. + public String getPathTranslated() + { + // In this server, the entire path is regexp-matched against the + // servlet pattern, so there's no good way to distinguish which + // part refers to the servlet. + return getRealPath(getPathInfo()); + } + + // / Returns the query string part of the servlet URI, or null if not + // known. + // Same as the CGI variable QUERY_STRING. + public String getQueryString() + { + return reqQuery; + } + + // / Returns the name of the user making this request, or null if not + // known. + // Same as the CGI variable REMOTE_USER. + public String getRemoteUser() + { + return remoteUser; + } + + // / Returns the authentication scheme of the request, or null if none. + // Same as the CGI variable AUTH_TYPE. + public String getAuthType() + { + return authType; + } + + // / Returns the value of a header field, or null if not known. + // Same as the information passed in the CGI variabled HTTP_*. + // @param name the header field name + public String getHeader(String name) + { + int i = reqHeaderNames.indexOf(name.toLowerCase()); + if (i == -1) + return null; + return (String) reqHeaderValues.elementAt(i); + } + + public int getIntHeader(String name) + { + String val = getHeader(name); + if (val == null) + return -1; + return Integer.parseInt(val); + } + + public long getDateHeader(String name) + { + String val = getHeader(name); + if (val == null) + return -1; + try + { + return headerdateformat.parse(val).getTime(); + } + catch (ParseException pe) + { + try + { + return rfc850DateFmt.parse(val).getTime(); + } + catch (ParseException pe1) + { + try + { + return asciiDateFmt.parse(val).getTime(); + } + catch (ParseException pe3) + { + throw new IllegalArgumentException("Value " + val + + " can't be converted to Date using any of formats: [" + headerdateformat.toPattern() + + "][ " + rfc850DateFmt.toPattern() + "][" + asciiDateFmt.toPattern()); + } + } + } + } + + // / Returns an Enumeration of the header names. + public Enumeration getHeaderNames() + { + return reqHeaderNames.elements(); + } + + // / Gets the current valid session associated with this request, if + // create is false or, if necessary, creates a new session for the + // request, if create is true. + //

+ // Note: to ensure the session is properly maintained, the servlet + // developer must call this method (at least once) before any output + // is written to the response. + //

+ // Additionally, application-writers need to be aware that newly + // created sessions (that is, sessions for which HttpSession.isNew + // returns true) do not have any application-specific state. + public synchronized HttpSession getSession(boolean create) + { + HttpSession result = null; + if (sessionValue != null) + { + result = serve.getSession(sessionValue); + if (result != null && ((AcmeSession) result).isValid() == false) + { + serve.removeSession(sessionValue); + result = null; + } + //System.err.println("^^^^^^^req sess: "+sessionValue+", found:"+result); + } + if (result == null && create) + { + result = serve.createSession(); + if (result != null) + { + sessionValue = result.getId(); + } + else + throw new RuntimeException("A session can't be created"); + //System.err.println("^~~~~~created: "+sessionValue); + } + return result; + } + + // JSDK 2.1 + public HttpSession getSession() + { + return getSession(true); + } + + public boolean isRequestedSessionIdFromURL() + { + return isRequestedSessionIdFromUrl(); + } + + // from ServletRequest + public Enumeration getAttributeNames() + { + return attributes.keys(); + } + + /** + * Stores an attribute in this request. Attributes are reset between requests. + * This method is most often used in conjunction with RequestDispatcher. + *

Attribute names should follow the same conventions as package names. + * Names beginning with java.*, javax.*, and com.sun.*, are reserved for + * use by Sun Microsystems. If the object passed in is null, the effect is + * the same as calling removeAttribute(java.lang.String). + *

+ * It is warned that when the request is dispatched from the servlet resides + * in a different web application by RequestDispatcher, the object set by + * this method may not be correctly retrieved in the caller servlet. + * + * @param name - a String specifying the name of the attribute + * @param o - the Object to be stored + */ + public void setAttribute(String key, Object o) + { + //System.err.println("!!!Set att orig:"+key+"="+o); + //if ("javax.servlet.jsp.jspException".equals(key) && o instanceof Throwable) + //((Throwable)o).printStackTrace(); + + if (o != null) + attributes.put(key, o); + else + attributes.remove(key); + } + + // / Gets the session id specified with this request. This may differ + // from the actual session id. For example, if the request specified + // an id for an invalid session, then this will get a new session with + // a new id. + public String getRequestedSessionId() + { + return sessionValue; + } + + // / Checks whether this request is associated with a session that is + // valid in the current session context. If it is not valid, the + // requested session will never be returned from the getSession + // method. + public boolean isRequestedSessionIdValid() + { + if (sessionValue != null) + { + AcmeSession session = serve.getSession(sessionValue); + return (session != null && session.isValid()); + } + return false; + } + + /** + * Checks whether the session id specified by this request came in as a cookie. (The requested session may not be one returned by the getSession + * method.) + */ + public boolean isRequestedSessionIdFromCookie() + { + return sessionCookieValue != null; + } + + // / Checks whether the session id specified by this request came in as + // part of the URL. (The requested session may not be the one returned + // by the getSession method.) + public boolean isRequestedSessionIdFromUrl() + { + return sessionUrlValue != null; + } + + // Methods from ServletResponse. + + // / Sets the content length for this response. + // @param length the content length + + public void setContentLength(int length) + { + if (length >= 0) + setIntHeader(CONTENTLENGTH, length); + else + setHeader(CONTENTLENGTH, null); + } + + // / Sets the content type for this response. + // @param type the content type + public void setContentType(String type) + { + setHeader(CONTENTTYPE, type != null ? type : "Unknown"); + } + + // / Returns an output stream for writing response data. + public ServletOutputStream getOutputStream() + { + synchronized (out) + { + if (rout == null) + { + if (pw != null) + throw new IllegalStateException("Already returned as a writer"); + rout = out; + } + } + return rout; + } + + // / Returns a print writer for writing response data. The MIME type of + // the response will be modified, if necessary, to reflect the character + // encoding used, through the charset=... property. This means that the + // content type must be set before calling this method. + // @exception UnsupportedEncodingException if no such encoding can be + // provided + // @exception IllegalStateException if getOutputStream has been called + // @exception IOException on other I/O errors + public PrintWriter getWriter() throws IOException + { + synchronized (out) + { + if (pw == null) + { + if (rout != null) + throw new IllegalStateException("Already was returned as servlet output stream"); + String encoding = getCharacterEncoding(); + if (encoding != null) + pw = new PrintWriter(new OutputStreamWriter(out, encoding)); + else + pw = new PrintWriter(out); + } + } + return pw; + } + + // / Returns the character set encoding used for this MIME body. The + // character encoding is either the one specified in the assigned + // content type, or one which the client understands. If no content + // type has yet been assigned, it is implicitly set to text/plain. + public String getCharacterEncoding() + { + String ct = (String) resHeaderNames.get(CONTENTTYPE.toLowerCase()); + if (ct != null) + { + String enc = extractEncodingFromContentType(ct); + if (enc != null) + return enc; + } + return charEncoding; + } + + private String extractEncodingFromContentType(String ct) + { + if (ct == null) + return null; + int scp = ct.indexOf(';'); + if (scp > 0) + { + scp = ct.toLowerCase().indexOf("charset=", scp); + if (scp >= 0) + { + ct = ct.substring(scp + "charset=".length()).trim(); + scp = ct.indexOf(';'); + if (scp > 0) + ct = ct.substring(0, scp); + int l = ct.length(); + if (l > 2 && ct.charAt(0) == '"') + return ct.substring(1, l - 1); + return ct; + } + } + return null; + } + + // 2.2 + // do not use buffer + public void flushBuffer() throws IOException + { + ((ServeOutputStream) out).flush(); + } + + /** + * Clears the content of the underlying buffer in the response without clearing headers or status code. If the response has been committed, this method + * throws an IllegalStateException. + * + * @since 2.3 + */ + public void resetBuffer() + { + ((ServeOutputStream) out).reset(); + synchronized (this) + { + headersWritten = false; + } + } + + public int getBufferSize() + { + return ((ServeOutputStream) out).getBufferSize(); + } + + public void setBufferSize(int size) + { + ((ServeOutputStream) out).setBufferSize(size); + } + + /** + * Returns a boolean indicating if the response has been committed. A commited response has already had its status code and headers written. + * + * @return a boolean indicating if the response has been committed + * @see setBufferSize(int), getBufferSize(), flushBuffer(), reset() + */ + // a caller should think about syncronization + public boolean isCommitted() + { + return headersWritten && ((ServeOutputStream) out).lengthWritten() > 0; + } + + /** + * Clears any data that exists in the buffer as well as the status code and headers. If the response has been committed, this method throws an + * IllegalStateException. + * + * @throws IllegalStateException + * - + * if the response has already been committed + * @see setBufferSize(int), getBufferSize(), flushBuffer(), isCommitted() + */ + public void reset() throws IllegalStateException + { + // new Exception("RESET").printStackTrace(); + if (!isCommitted()) + { + if (outCookies != null) + outCookies.clear(); + resHeaderNames.clear(); + pw = null; + rout = null; + ((ServeOutputStream) out).reset(); + assureHeaders(); + } + else + throw new IllegalStateException("Header have already been committed."); + } + + /** + * Sets the locale of the response, setting the headers (including the Content-Type's charset) as appropriate. This method should be called before a + * call to getWriter(). By default, the response locale is the default locale for the server. + * + * @param loc - + * the locale of the response + * @see getLocale() + */ + public void setLocale(Locale locale) + { + this.locale = locale; + } + + /** + * For request: Returns the preferred Locale that the client will accept content in, based on the Accept-Language header. If the client request doesn't + * provide an Accept-Language header, this method returns the default locale for the server. + *

+ * For response: Returns the locale specified for this response using the setLocale(java.util.Locale) method. Calls made to setLocale after the response + * is committed have no effect. If no locale has been specified, the container's default locale is returned. + */ + public Locale getLocale() + { + if (locale != null) + return locale; + Enumeration e = getLocales(); + if (e.hasMoreElements()) + return (Locale) e.nextElement(); + return Locale.getDefault(); + } + + /** + * Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the + * client based on the Accept-Language header. If the client request doesn't provide an Accept-Language header, this method returns an Enumeration + * containing one Locale, the default locale for the server. + */ + public Enumeration getLocales() + { + // TODO: cache result + String al = getHeader(ACCEPT_LANGUAGE); + TreeSet ts = new TreeSet(); + if (al != null) + { + // System.err.println("Accept lang:"+al); + StringTokenizer st = new StringTokenizer(al, ";", false); + try + { + while (st.hasMoreTokens()) + { + String langs = st.nextToken(";"); + // System.err.println("Langs:"+langs); + String q = st.nextToken(";="); + // System.err.println("q:"+q); + q = st.nextToken("=,"); + // System.err.println("q:"+q); + float w = 0; + try + { + w = Float.valueOf(q).floatValue(); + } + catch (NumberFormatException nfe) + { + } + if (w > 0) + { + StringTokenizer lst = new StringTokenizer(langs, ", ", false); + while (lst.hasMoreTokens()) + { + String lan = lst.nextToken(); + int di = lan.indexOf('-'); + if (di < 0) + ts.add(new LocaleWithWeight(new Locale(lan.trim()) /* 1.4 */, w)); + else + ts.add(new LocaleWithWeight(new Locale(lan.substring(0, di), lan.substring(di + 1) + .trim().toUpperCase()), w)); + } + } + } + } + catch (NoSuchElementException ncee) + { + // can't parse + } + } + if (ts.size() == 0) + ts.add(new LocaleWithWeight(Locale.getDefault(), 1)); + return new AcceptLocaleEnumeration(ts); + } + + /** + * Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or + * reading input using getReader(). + * + * @param a - + * String containing the name of the chararacter encoding. + * @throws java.io.UnsupportedEncodingException + * - + * if this is not a valid encoding + * @since JSDK 2.3 + */ + public void setCharacterEncoding(String _enc) + { + // TODO: check if encoding is valid + charEncoding = _enc; + synchronized (this) + { + formParameters = null; + } + } + + public void addDateHeader(String header, long date) + { + addHeader(header, headerdateformat.format(new Date(date))); + } + + public void addHeader(String header, String value) + { + header = header.trim().toLowerCase(); + Object o = resHeaderNames.get(header); + if (o == null) + setHeader(header, value); + else + { + if (o instanceof String[]) + { + String[] oldVal = (String[]) o; + String[] newVal = new String[oldVal.length + 1]; + System.arraycopy(oldVal, 0, newVal, 0, oldVal.length); + newVal[oldVal.length] = value; + resHeaderNames.put(header, newVal); + } + else if (o instanceof String) + { + String[] newVal = new String[2]; + newVal[0] = (String) o; + newVal[1] = value; + resHeaderNames.put(header, newVal); + } + else + throw new RuntimeException("Invalid content of header hash - " + o.getClass().getName()); + } + } + + public void addIntHeader(String header, int value) + { + addHeader(header, Integer.toString(value)); + } + + public RequestDispatcher getRequestDispatcher(String urlpath) + { + if (urlpath.length() > 0 && urlpath.charAt(0) != '/') + { + String dispatchPath = getContextPath(); + String pathInfo = getPathInfo(); + String servletPath = getServletPath(); + ; + if (pathInfo != null) + { + dispatchPath += servletPath; + int slp = pathInfo.indexOf('/', 1); + if (slp > 0) // can it ever happen? + dispatchPath += pathInfo.substring(0, slp - 1); + } + else + { + int spsp = servletPath.lastIndexOf('/'); + if (spsp >= 0) + dispatchPath += servletPath.substring(0, spsp); + } + // serve.log("Dispatch path:"+dispatchPath); + urlpath = dispatchPath + '/' + urlpath; + } + return serve.getRequestDispatcher(urlpath); + } + + public boolean isSecure() + { + return "https".equals(getScheme()); + } + + public void removeAttribute(String name) + { + attributes.remove(name); + } + + // only root context supported + public String getContextPath() + { + return ""; + } + + public Enumeration getHeaders(String header) + { + Vector result = new Vector(); + int i = -1; + while ((i = reqHeaderNames.indexOf(header.toLowerCase(), i + 1)) >= 0) + result.addElement(reqHeaderValues.elementAt(i)); + return result.elements(); + } + + public java.security.Principal getUserPrincipal() + { + return null; + } + + public boolean isUserInRole(String user) + { + return false; + } + + /** + * Returns a java.util.Map of the parameters of this request. Request parameters are extra information sent with the request. For HTTP servlets, + * parameters are contained in the query string or posted form data. + * + * @return an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type + * String. The values in the parameter map are of type String array. + * @since 2.3 + */ + public synchronized Map getParameterMap() + { + if (formParameters == null) + getParameterNames(); + return formParameters; + } + + // Methods from HttpServletResponse. + + // / Adds the specified cookie to the response. It can be called + // multiple times to set more than one cookie. + + public void addCookie(Cookie cookie) + { + if (outCookies == null) + outCookies = new Vector(); + + outCookies.addElement(cookie); + } + + // / Checks whether the response message header has a field with the + // specified name. + public boolean containsHeader(String name) + { + return resHeaderNames.contains(name); + } + + // JSDK 2.1 extension + public String encodeURL(String url) + { + int uop = url.indexOf(SESSION_URL_NAME); + // TODO not robust enough + if (uop > 0) + url = url.substring(0, uop); + if (sessionValue == null || isRequestedSessionIdFromCookie()) + return url; + try + { + new URL(url); // for testing syntac + int ehp = url.indexOf('/'); + if (ehp < 0) + ehp = url.indexOf('?'); + if (ehp < 0) + ehp = url.indexOf('#'); + if (ehp < 0) + ehp = url.length(); + if (url.regionMatches(true, 0, getRequestURL().toString(), 0, ehp) == false) + return url; + } + catch (MalformedURLException e) + { + } + + return url + SESSION_URL_NAME + sessionValue; + } + + public String encodeRedirectURL(String url) + { + return encodeURL(url); + } + + /** + * Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request. + * + * @return an integer specifying the port number + * @since 2.4 + */ + public int getRemotePort() + { + return socket.getPort(); // TODO not quite robust + } + + /** + * Returns the host name of the Internet Protocol (IP) interface on which the request was received. + * + * @return a String containing the host name of the IP on which the request was received. + * @since 2.4 + */ + public String getLocalName() + { + InetAddress ia = socket/* serve.serverSocket */.getLocalAddress(); + return ia == null ? null : ia.getHostAddress(); + } + + /** + * Returns the Internet Protocol (IP) address of the interface on which the request was received. + * + * @return a String containing the IP address on which the request was received. + * @since 2.4 + */ + public String getLocalAddr() + { + InetAddress ia = /* serve.serverSocket */socket.getLocalAddress(); + return ia == null ? null : ia.getCanonicalHostName(); /* 1.4 */ + } + + /** + * Returns the Internet Protocol (IP) port number of the interface on which the request was received. + * + * @return an integer specifying the port number + * @since 2.4 + */ + public int getLocalPort() + { + return getServerPort(); + } + + // / Sets the status code and message for this response. + // @param resCode the status code + // @param resMessage the status message + public void setStatus(int resCode, String resMessage) + { + // if (((ServeOutputStream) out).isInInclude()) + // return; + this.resCode = resCode; + this.resMessage = resMessage; + } + + // / Sets the status code and a default message for this response. + // @param resCode the status code + public void setStatus(int resCode) + { + switch (resCode) + { + case SC_CONTINUE: + setStatus(resCode, "Continue"); + break; + case SC_SWITCHING_PROTOCOLS: + setStatus(resCode, "Switching protocols"); + break; + case SC_OK: + setStatus(resCode, "Ok"); + break; + case SC_CREATED: + setStatus(resCode, "Created"); + break; + case SC_ACCEPTED: + setStatus(resCode, "Accepted"); + break; + case SC_NON_AUTHORITATIVE_INFORMATION: + setStatus(resCode, "Non-authoritative"); + break; + case SC_NO_CONTENT: + setStatus(resCode, "No content"); + break; + case SC_RESET_CONTENT: + setStatus(resCode, "Reset content"); + break; + case SC_PARTIAL_CONTENT: + setStatus(resCode, "Partial content"); + break; + case SC_MULTIPLE_CHOICES: + setStatus(resCode, "Multiple choices"); + break; + case SC_MOVED_PERMANENTLY: + setStatus(resCode, "Moved permanentently"); + break; + case SC_MOVED_TEMPORARILY: + setStatus(resCode, "Moved temporarily"); + break; + case SC_SEE_OTHER: + setStatus(resCode, "See other"); + break; + case SC_NOT_MODIFIED: + setStatus(resCode, "Not modified"); + break; + case SC_USE_PROXY: + setStatus(resCode, "Use proxy"); + break; + case SC_BAD_REQUEST: + setStatus(resCode, "Bad request"); + break; + case SC_UNAUTHORIZED: + setStatus(resCode, "Unauthorized"); + break; + case SC_PAYMENT_REQUIRED: + setStatus(resCode, "Payment required"); + break; + case SC_FORBIDDEN: + setStatus(resCode, "Forbidden"); + break; + case SC_NOT_FOUND: + setStatus(resCode, "Not found"); + break; + case SC_METHOD_NOT_ALLOWED: + setStatus(resCode, "Method not allowed"); + break; + case SC_NOT_ACCEPTABLE: + setStatus(resCode, "Not acceptable"); + break; + case SC_PROXY_AUTHENTICATION_REQUIRED: + setStatus(resCode, "Proxy auth required"); + break; + case SC_REQUEST_TIMEOUT: + setStatus(resCode, "Request timeout"); + break; + case SC_CONFLICT: + setStatus(resCode, "Conflict"); + break; + case SC_GONE: + setStatus(resCode, "Gone"); + break; + case SC_LENGTH_REQUIRED: + setStatus(resCode, "Length required"); + break; + case SC_PRECONDITION_FAILED: + setStatus(resCode, "Precondition failed"); + break; + case SC_REQUEST_ENTITY_TOO_LARGE: + setStatus(resCode, "Request entity too large"); + break; + case SC_REQUEST_URI_TOO_LONG: + setStatus(resCode, "Request URI too long"); + break; + case SC_UNSUPPORTED_MEDIA_TYPE: + setStatus(resCode, "Unsupported media type"); + break; + case SC_INTERNAL_SERVER_ERROR: + setStatus(resCode, "Internal server error"); + break; + case SC_NOT_IMPLEMENTED: + setStatus(resCode, "Not implemented"); + break; + case SC_BAD_GATEWAY: + setStatus(resCode, "Bad gateway"); + break; + case SC_SERVICE_UNAVAILABLE: + setStatus(resCode, "Service unavailable"); + break; + case SC_GATEWAY_TIMEOUT: + setStatus(resCode, "Gateway timeout"); + break; + case SC_HTTP_VERSION_NOT_SUPPORTED: + setStatus(resCode, "HTTP version not supported"); + break; + case 207: + setStatus(resCode, "Multi Status"); + break; + default: + setStatus(resCode, ""); + break; + } + } + + // / Sets the value of a header field. + // @param name the header field name + // @param value the header field value + public void setHeader(String header, String value) + { + header = header.trim().toLowerCase(); // normilize header + if (value == null) + resHeaderNames.remove(header); + else + { + resHeaderNames.put(header, value); + //if (header.equals(CONTENTTYPE)) { + // String enc = extractEncodingFromContentType(value); + // if (enc != null) + // setCharacterEncoding(enc); + //} + } + } + + // / Sets the value of an integer header field. + // @param name the header field name + // @param value the header field integer value + public void setIntHeader(String header, int value) + { + setHeader(header, Integer.toString(value)); + } + + // / Sets the value of a long header field. + // @param name the header field name + // @param value the header field long value + public void setLongHeader(String header, long value) + { + setHeader(header, Long.toString(value)); + } + + // / Sets the value of a date header field. + // @param name the header field name + // @param value the header field date value + public void setDateHeader(String header, long value) + { + setHeader(header, headerdateformat.format(new Date(value))); + } + + // / Writes the status line and message headers for this response to the + // output stream. + // @exception IOException if an I/O error has occurred + void writeHeaders() throws IOException + { + synchronized (this) + { + // TODO: possible to write trailer when chunked out, + // so chunked out should be global flag + if (headersWritten) + return; + + headersWritten = true; + } + if (reqMime) + { + boolean chunked_out = false; + boolean wasContentLen = false; + if (resMessage.length() < 256) + out.println(reqProtocol + " " + resCode + " " + resMessage.replace('\r', '/').replace('\n', '/')); + else + out.println(reqProtocol + " " + resCode + " " + + resMessage.substring(0, 255).replace('\r', '/').replace('\n', '/')); + Enumeration he = resHeaderNames.keys(); + while (he.hasMoreElements()) + { + String name = (String) he.nextElement(); + Object o = resHeaderNames.get(name); + if (o instanceof String) + { + String value = (String) o; + if (value != null) + {// just in case + out.println(name + ": " + value); + if (wasContentLen == false) + if (CONTENTLENGTH.equals(name)) + try + { + wasContentLen = Long.parseLong(value) > 0; + } + catch (NumberFormatException nfe) + { + } + if (chunked_out == false) + if (TRANSFERENCODING.equals(name) && CHUNKED.equals(value)) + chunked_out = true; + } + } + else if (o instanceof String[]) + { + String[] values = (String[]) o; + out.print(name + ": " + values[0]); + for (int i = 1; i < values.length; i++) + out.print("," + values[i]); + out.println(); + } + } + StringBuffer sb = null; + StringBuffer sb2 = null; + Cookie cc = null; + // add session cookie + if (sessionValue != null) + { + HttpSession session = serve.getSession(sessionValue); + if (session != null) + { + if (((AcmeSession) session).isValid()) + { + if (session.isNew()) + { + cc = new Cookie(SESSION_COOKIE_NAME, sessionValue); + if (serve.expiredIn < 0) + cc.setMaxAge(Math.abs(serve.expiredIn) * 60); + ServletContext sc = ((AcmeSession) session).getServletContext(); + try + { + String cp = (String) sc.getClass().getMethod("getContextPath", Utils.EMPTY_CLASSES) + .invoke(sc, Utils.EMPTY_OBJECTS); + if (cp.length() == 0) + cp = "/"; + cc.setPath(cp); + } + catch (Exception e) + { + + } + + addCookie(cc); + } + } + else + { + cc = new Cookie(SESSION_COOKIE_NAME, ""); + cc.setMaxAge(0); + addCookie(cc); + } + } + } + + // how to remove a cookie + // cc = new Cookie(cookieName, ""); + // cc.setMaxAge(0); + // + for (int i = 0; outCookies != null && i < outCookies.size(); i++) + { + cc = (Cookie) outCookies.elementAt(i); + if (cc.getSecure() && isSecure() == false) + continue; + int version = cc.getVersion(); + String token; + if (version > 1) + { + if (sb2 == null) + sb2 = new StringBuffer(SETCOOKIE + "2: "); + else + sb2.append(','); + sb2.append(cc.getName()); + sb2.append("=\""); + sb2.append(cc.getValue()).append('"'); + token = cc.getComment(); + if (token != null) + sb2.append("; Comment=\"").append(token).append('"'); + token = cc.getDomain(); + if (token != null) + sb2.append("; Domain=\"").append(token).append('"'); + if (cc.getMaxAge() >= 0) + sb2.append("; Max-Age=\"").append(cc.getMaxAge()).append('"'); + token = cc.getPath(); + if (token != null) + sb2.append("; Path=\"").append(token).append('"'); + if (cc.getSecure()) + { + sb2.append("; Secure"); + } + sb2.append("; Version=\"").append(version).append('"'); + } + else + { + if (sb == null) + sb = new StringBuffer(SETCOOKIE + ": "); + else + //sb.append(','); + sb.append("\r\n" + SETCOOKIE + ": "); // for IE not + sb.append(cc.getName()); + sb.append('='); + sb.append(cc.getValue());//.append('"'); + if (cc.getDomain() != null && cc.getDomain().length() > 0) + { + sb.append("; domain=" + cc.getDomain()); + } + if (cc.getMaxAge() >= 0) + { + sb.append("; expires="); + sb.append(expdatefmt.format(new Date(new Date().getTime() + 1000l * cc.getMaxAge()))); + } + if (cc.getPath() != null && cc.getPath().length() > 0) + { + sb.append("; path=" + cc.getPath()); + } + if (cc.getSecure()) + { + sb.append("; secure"); + } + } + } + if (sb != null) + { + out.println(sb.toString()); + //System.err.println("We sent cookies: " + sb); + } + if (sb2 != null) + { + out.println(sb2.toString()); + //System.err.println("We sent cookies 2: " + sb2); + } + // Test for existence of message body + if (containsBody() && wasContentLen == false && chunked_out == false && serve.isKeepAlive()) + { + out.println(TRANSFERENCODING + ": " + CHUNKED); + chunked_out = true; + } + out.println(); + out.flush(); + ((ServeOutputStream) out).setChunked(chunked_out); + } + } + + private boolean containsBody() + { + return !("HEAD".equalsIgnoreCase(reqMethod) || (100 <= resCode && resCode < 200) || resCode == 204 || resCode == 304); + } + + // / Writes an error response using the specified status code and + // message. + // @param resCode the status code + // @param resMessage the status message + // @exception IOException if an I/O error has occurred + public void sendError(int resCode, String resMessage) throws IOException + { + setStatus(resCode, resMessage); + realSendError(); + } + + // / Writes an error response using the specified status code and a + // default + // message. + // @param resCode the status code + // @exception IOException if an I/O error has occurred + public void sendError(int resCode) throws IOException + { + setStatus(resCode); + realSendError(); + } + + public void setInInclude(boolean set) + { + ((ServeOutputStream) out).setInInclude(set); + } + + private void realSendError() throws IOException + { + if (isCommitted()) + throw new IllegalStateException("Can not send an error, headers have been already written"); + // if (((ServeOutputStream) out).isInInclude()) // ignore + // return; + setContentType("text/html"); + StringBuffer sb = new StringBuffer(100); + int lsp = resMessage.indexOf('\n'); + sb.append("").append( + "" + resCode + " " + (lsp < 0 ? resMessage : resMessage.substring(0, lsp)) + "") + .append("

" + resCode + " " + (lsp < 0 ? resMessage : resMessage.substring(0, lsp)) + "

"); + if (lsp > 0) + sb.append("
").append(Utils.htmlEncode(resMessage.substring(lsp), false)).append("
"); + sb.append("
"); + sb.append(Identification.serverIdHtml); + sb.append(""); + setContentLength(sb.length()); + out.print(sb.toString()); + closeStreams(); + } + + // / Sends a redirect message to the client using the specified redirect + // location URL. + // @param location the redirect location URL + // @exception IOException if an I/O error has occurred + public void sendRedirect(String location) throws IOException + { + if (isCommitted()) + throw new IllegalStateException("Can not redirect, headers have been already written"); + if (location.indexOf(":/") < 0) + { // relative + String portString = ""; + if ("https".equalsIgnoreCase(getScheme())) + { + if (getServerPort() != 443) + portString = ":" + getServerPort(); + } + else if (getServerPort() != 80) + portString = ":" + getServerPort(); + + if (location.length() > 0 && location.charAt(0) == '/') + { + location = getScheme() + "://" + getServerName() + portString + location; + } + else + { + int sp = reqUriPathUn.lastIndexOf('/'); + String uri; + if (sp < 0) + { + uri = reqUriPathUn + '/'; + sp = uri.length(); + } + else + { + uri = reqUriPathUn; + sp++; + } + location = getScheme() + "://" + getServerName() + portString + uri.substring(0, sp) + location; + } + } + // serve.log("location:"+location); + setHeader("Location", location); + setStatus(SC_MOVED_TEMPORARILY); + setContentType("text/html"); + StringBuffer sb = new StringBuffer(200); + sb.append("" + "" + SC_MOVED_TEMPORARILY + " Moved" + "

" + SC_MOVED_TEMPORARILY + " Moved

" + "This document has moved here.
"); + sb.append(Identification.serverIdHtml); + sb.append(""); + setContentLength(sb.length()); + // to avoid further out + out.print(sb.toString()); + closeStreams(); + } + + // URL session-encoding stuff. Not implemented, but the API is here + // for compatibility. + + // / Encodes the specified URL by including the session ID in it, or, if + // encoding is not needed, returns the URL unchanged. The + // implementation of this method should include the logic to determine + // whether the session ID needs to be encoded in the URL. For example, + // if the browser supports cookies, or session tracking is turned off, + // URL encoding is unnecessary. + //

+ // All URLs emitted by a Servlet should be run through this method. + // Otherwise, URL rewriting cannot be used with browsers which do not + // support cookies. + // @deprecated + + public String encodeUrl(String url) + { + return encodeURL(url); + } + + // / Encodes the specified URL for use in the sendRedirect method or, if + // encoding is not needed, returns the URL unchanged. The + // implementation of this method should include the logic to determine + // whether the session ID needs to be encoded in the URL. Because the + // rules for making this determination differ from those used to + // decide whether to encode a normal link, this method is seperate + // from the encodeUrl method. + //

+ // All URLs sent to the HttpServletResponse.sendRedirect method should + // be + // run through this method. Otherwise, URL rewriting cannot be used with + // browsers which do not support cookies. + public String encodeRedirectUrl(String url) + { + return encodeRedirectURL(url); + } + + public Socket getSocket() + { + // TODO apply security check + return socket; + } + } + + protected static class BasicAuthRealm extends Hashtable + { + String name; + + BasicAuthRealm(String name) + { + this.name = name; + } + + String name() + { + return name; + } + } + + public static class ServeInputStream extends ServletInputStream + { + private final static boolean STREAM_DEBUG = false; + + /** + * The actual input stream (buffered). + */ + private InputStream in, origIn; + + private ServeConnection conn; + + private int chunksize = 0; + + private boolean chunking = false, compressed; + + private boolean returnedAsReader, returnedAsStream; + + private long contentLength = -1; + + private long readCount; + + private byte[] oneReadBuf = new byte[1]; + + private boolean closed; + + /* ------------------------------------------------------------ */ + /** + * Constructor + */ + public ServeInputStream(InputStream in, ServeConnection conn) + { + this.conn = conn; + this.in = new BufferedInputStream(in); + } + + void refresh() + { + returnedAsReader = false; + returnedAsStream = false; + contentLength = -1; + readCount = 0; + chunksize = 0; + closed = false; + compressed(false); + } + + /* ------------------------------------------------------------ */ + /** + * @param chunking + */ + public void chunking(boolean chunking) + { + if (contentLength == -1) + this.chunking = chunking; + } + + boolean compressed(boolean on) + { + if (on) + { + if (compressed == false) + { + origIn = in; + try + { + ServeInputStream sis = new ServeInputStream(in, conn); + if (chunking) + { + sis.chunking(true); + chunking(false); + } + in = (InputStream) conn.serve.gzipInStreamConstr.newInstance(new Object[]{sis}); + compressed = true; + //conn.serve.log("Compressed stream was created with success", null); + } + catch (Exception ex) + { + if (ex instanceof InvocationTargetException) + conn.serve.log("Problem in compressed stream creation", ((InvocationTargetException) ex).getTargetException()); + else + conn.serve.log("Problem in compressed stream obtaining", ex); + } + } + } + else if (compressed) + { + compressed = false; + in = origIn; + } + return compressed; + } + + /** + * sets max read byte in input + */ + void setContentLength(long contentLength) + { + if (this.contentLength == -1 && contentLength >= 0 && chunking == false) + { + this.contentLength = contentLength; + readCount = 0; + } + } + + /* ------------------------------------------------------------ */ + /** + * Read a line ended by CRLF, used internally only for reading headers. + * No char encoding, ASCII only + */ + protected String readLine(int maxLen) throws IOException + { + if (maxLen <= 0) + throw new IllegalArgumentException("Max len:" + maxLen); + StringBuffer buf = new StringBuffer(Math.min(1024, maxLen)); + + int c; + boolean cr = false; + int i = 0; + while ((c = in.read()) != -1) + { + if (c == 10) + { // LF + if (cr) + break; + break; + //throw new IOException ("LF without CR"); + } + else if (c == 13) // CR + cr = true; + else + { + //if (cr) + //throw new IOException ("CR without LF"); + // see http://www.w3.org/Protocols/HTTP/1.1/rfc2616bis/draft-lafon-rfc2616bis-03.html#tolerant.applications + cr = false; + if (i >= maxLen) + throw new IOException("Line lenght exceeds " + maxLen); + buf.append((char) c); + i++; + } + } + if (STREAM_DEBUG) + System.err.println(buf); + if (c == -1 && buf.length() == 0) + return null; + + return buf.toString(); + } + + /* ------------------------------------------------------------ */ + public int read() throws IOException + { + int result = read(oneReadBuf, 0, 1); + if (result == 1) + return 255 & oneReadBuf[0]; + return -1; + } + + /* ------------------------------------------------------------ */ + public int read(byte b[]) throws IOException + { + return read(b, 0, b.length); + } + + /* ------------------------------------------------------------ */ + public synchronized int read(byte b[], int off, int len) throws IOException + { + if (closed) + throw new IOException("The stream is already closed"); + if (chunking) + { + if (chunksize <= 0 && getChunkSize() <= 0) + return -1; + if (len > chunksize) + len = chunksize; + len = in.read(b, off, len); + chunksize = (len < 0) ? -1 : (chunksize - len); + } + else + { + if (contentLength >= 0) + { + if (contentLength - readCount < Integer.MAX_VALUE) + + len = Math.min(len, (int) (contentLength - readCount)); + if (len <= 0) + { + if (STREAM_DEBUG) + System.err.print("EOF"); + return -1; + } + len = in.read(b, off, len); + if (len > 0) + readCount += len; + } + else + // to avoid extra if + len = in.read(b, off, len); + } + if (STREAM_DEBUG && len > 0) + System.err.print(new String(b, off, len)); + + return len; + } + + /* ------------------------------------------------------------ */ + public long skip(long len) throws IOException + { + if (STREAM_DEBUG) + System.err.println("instream.skip() :" + len); + if (closed) + throw new IOException("The stream is already closed"); + if (chunking) + { + if (chunksize <= 0 && getChunkSize() <= 0) + return -1; + if (len > chunksize) + len = chunksize; + len = in.skip(len); + chunksize = (len < 0) ? -1 : (chunksize - (int) len); + } + else + { + if (contentLength >= 0) + { + len = Math.min(len, contentLength - readCount); + if (len <= 0) + return -1; + len = in.skip(len); + readCount += len; + } + else + len = in.skip(len); + } + return len; + } + + /* ------------------------------------------------------------ */ + /** + * Available bytes to read without blocking. If you are unlucky may return 0 when there are more + */ + public int available() throws IOException + { + if (STREAM_DEBUG) + System.err.println("instream.available()"); + if (closed) + throw new IOException("The stream is already closed"); + if (chunking) + { + int len = in.available(); + if (len <= chunksize) + return len; + return chunksize; + } + + if (contentLength >= 0) + { + int len = in.available(); + if (contentLength - readCount < Integer.MAX_VALUE) + return Math.min(len, (int) (contentLength - readCount)); + return len; + } + else + return in.available(); + } + + /* ------------------------------------------------------------ */ + public void close() throws IOException + { + // keep alive, will be closed by socket + // in.close(); + if (STREAM_DEBUG) + System.err.println("instream.close() " + closed); + if (closed) + return; //throw new IOException("The stream is already closed"); + // read until end of chunks or content length + if (chunking) + while (read() >= 0) ; + else if (contentLength < 0) ; + else + { + long skipCount = contentLength - readCount; + while (skipCount > 0) + { + long skipped = skip(skipCount); + if (skipped <= 0) + break; + skipCount -= skipped; + } + } + if (conn.keepAlive == false) + in.close(); + closed = true; + } + + /* ------------------------------------------------------------ */ + /** + * Mark is not supported + * + * @return false + */ + public boolean markSupported() + { + return false; + } + + /* ------------------------------------------------------------ */ + /** + * + */ + public void reset() throws IOException + { + // no buffering, so not possible + if (closed) + throw new IOException("The stream is already closed"); + if (STREAM_DEBUG) + System.err.println("instream.reset()"); + in.reset(); + } + + /* ------------------------------------------------------------ */ + /** + * Not Implemented + * + * @param readlimit + */ + public void mark(int readlimit) + { + // not supported + if (STREAM_DEBUG) + System.err.println("instream.mark(" + readlimit + ")"); + } + + /* ------------------------------------------------------------ */ + private int getChunkSize() throws IOException + { + if (chunksize < 0) + return -1; + + chunksize = -1; + + // Get next non blank line + chunking = false; + String line = readLine(60); + while (line != null && line.length() == 0) + line = readLine(60); + chunking = true; + + // Handle early EOF or error in format + if (line == null) + return -1; + + // Get chunksize + int i = line.indexOf(';'); + if (i > 0) + line = line.substring(0, i).trim(); + try + { + chunksize = Integer.parseInt(line, 16); + } + catch (NumberFormatException nfe) + { + throw new IOException("Chunked stream is broken, " + line); + } + + // check for EOF + if (chunksize == 0) + { + chunksize = -1; + // Look for footers + readLine(60); + chunking = false; + } + return chunksize; + } + + boolean isReturnedAsStream() + { + return returnedAsStream; + } + + void setReturnedAsStream(boolean _on) + { + returnedAsStream = _on; + } + + boolean isReturnedAsReader() + { + return returnedAsReader; + } + + void setReturnedAsReader(boolean _on) + { + returnedAsReader = _on; + } + } + + public static class ServeOutputStream extends ServletOutputStream + { + + private static final boolean STREAM_DEBUG = false; + + private boolean chunked; + + private boolean closed; + + // TODO: predefine as static byte[] used by chunked + // underneath stream + private OutputStream out; + + // private BufferedWriter writer; // for top speed + private ServeConnection conn; + + private int inInclude; + + private String encoding; + + private/*volatile*/ long lbytes; + + private Utils.SimpleBuffer buffer; + + public ServeOutputStream(OutputStream out, ServeConnection conn) + { + this.out = out; + this.conn = conn; + buffer = new Utils.SimpleBuffer(); + encoding = conn.getCharacterEncoding(); + if (encoding == null) + encoding = Utils.ISO_8859_1; + } + + void refresh() + { + chunked = false; + closed = false; + inInclude = 0; + lbytes = 0; + buffer.reset(); + encoding = conn.getCharacterEncoding(); + if (encoding == null) + encoding = Utils.ISO_8859_1; + } + + protected void reset() + { + if (lbytes == 0) + buffer.reset(); + else + throw new IllegalStateException("Result was already committed"); + } + + protected int getBufferSize() + { + return buffer.getSize(); + } + + protected void setBufferSize(int size) + { + if (lbytes > 0) + throw new IllegalStateException("Bytes already written in response"); + buffer.setSize(size); + } + + protected void setChunked(boolean set) + { + chunked = set; + } + + public void print(String s) throws IOException + { + write(s.getBytes(encoding)); + } + + public void write(int b) throws IOException + { + write(new byte[]{(byte) b}, 0, 1); + } + + public void write(byte[] b) throws IOException + { + write(b, 0, b.length); + } + + public void write(byte[] b, int off, int len) throws IOException + { + if (closed) + { + if (STREAM_DEBUG) + System.err.println((b == null ? "null" : new String(b, off, len)) + "\n won't be written, stream closed."); + throw new IOException("An attempt of writing " + len + " bytes to a closed out."); + } + + if (len == 0) + return; + // + conn.writeHeaders(); + b = buffer.put(b, off, len); + len = b.length; + if (len == 0) + return; + off = 0; + if (chunked) + { + String hexl = Integer.toHexString(len); + out.write((hexl + "\r\n").getBytes()); // no encoding Ok + lbytes += 2 + hexl.length(); + out.write(b, off, len); + lbytes += len; + out.write("\r\n".getBytes()); + lbytes += 2; + } + else + { + out.write(b, off, len); + lbytes += len; + } + + if (STREAM_DEBUG) + { + if (chunked) + System.err.println(Integer.toHexString(len)); + System.err.print(new String(b, off, len)); + if (chunked) + System.err.println(); + } + } + + public void flush() throws IOException + { + if (closed) + return; + // throw new IOException("An attempt of flushig closed out."); + conn.writeHeaders(); + byte[] b = buffer.get(); + if (b.length > 0) + { + if (chunked) + { + String hexl = Integer.toHexString(b.length); + out.write((hexl + "\r\n").getBytes()); // no encoding Ok + lbytes += 2 + hexl.length(); + out.write(b); + lbytes += b.length; + out.write("\r\n".getBytes()); + lbytes += 2; + if (STREAM_DEBUG) + { + System.err.println(hexl); + System.err.print(new String(b)); + System.err.println(); + } + } + else + { + out.write(b); + lbytes += b.length; + if (STREAM_DEBUG) + { + System.err.print(new String(b)); + } + } + } + out.flush(); + } + + public void close() throws IOException + { + if (closed) + return; + // throw new IOException("Stream is already closed."); + // new IOException("Stream closing").printStackTrace(); + try + { + flush(); + if (inInclude == 0) + { + if (chunked) + { + out.write("0\r\n\r\n".getBytes()); + lbytes += 5; + if (STREAM_DEBUG) + System.err.print("0\r\n\r\n"); + // TODO: here is possible to write trailer headers + out.flush(); + } + if (conn.keepAlive == false) + out.close(); + } + } + finally + { + closed = true; + } + } + + private long lengthWritten() + { + return lbytes; + } + + boolean isInInclude() + { + return inInclude == 0; + } + + void setInInclude(boolean _set) + { + inInclude = _set ? 1 : 0; + /*if (_set) + inInclude++; + else + inInclude--; + if (inInclude < 0) + throw new IllegalStateException("Not matching include set");*/ + } + } + + /** + * Class PathTreeDictionary - this class allows to put path elements in format n1/n2/n2[/*.ext] and get match to a pattern and a unmatched tail + */ + public static class PathTreeDictionary + { + Node root_node; + + public PathTreeDictionary() + { + root_node = new Node(); + } + + public synchronized void put(String path, Object value) + { + StringTokenizer st = new StringTokenizer(path, "\\/"); + Node cur_node = root_node; + while (st.hasMoreTokens()) + { + String nodename = st.nextToken(); + Node node = (Node) cur_node.get(nodename); + if (node == null) + { + node = new Node(); + cur_node.put(nodename, node); + } + cur_node = node; + } + cur_node.object = value; + } + + public synchronized Object[] remove(Object value) + { + return remove(root_node, value); + } + + public synchronized Object[] remove(String path) + { + Object[] result = get(path); + if (result[1] != null) + return remove(result[1]); + return result; + } + + public Object[] remove(Node node, Object value) + { + // TODO make full path, not only last element + Enumeration e = node.keys(); + while (e.hasMoreElements()) + { + String path = (String) e.nextElement(); + Node childNode = (Node) node.get(path); + if (childNode.object == value) + {// it's safe because the same instance can't be shared for several paths in this design + childNode.object = null; + return new Object[]{value, new Integer(0)}; + } + Object[] result = remove(childNode, value); + if (result[0] != null) + return result; + } + + return new Object[]{null, null}; + } + + /** + * This function looks up in the directory to find the perfect match and remove matching part from path, so if you need to keep original path, save it + * somewhere + */ + public Object[] get(String path) + { + Object[] result = new Object[2]; + if (path == null) + return result; + char[] ps = path.toCharArray(); + Node cur_node = root_node; + int p0 = 0, lm = 0; // last match + result[0] = cur_node.object; + boolean div_state = true; + for (int i = 0; i < ps.length; i++) + { + if (ps[i] == '/' || ps[i] == '\\') + { + if (div_state) + continue; + Node node = (Node) cur_node.get(new String(ps, p0, i - p0)); + if (node == null) + { + result[1] = new Integer(lm); + return result; + } + if (node.object != null) + { + result[0] = node.object; + lm = i; + } + cur_node = node; + div_state = true; + } + else + { + if (div_state) + { + p0 = i; + div_state = false; + } + } + } + cur_node = (Node) cur_node.get(new String(ps, p0, ps.length - p0)); + if (cur_node != null && cur_node.object != null) + { + result[0] = cur_node.object; + lm = ps.length; + } + result[1] = new Integer(lm); + return result; + } + + public Enumeration keys() + { + Vector result = new Vector(); + addSiblingNames(root_node, result, ""); + return result.elements(); + } + + public void addSiblingNames(Node node, Vector result, String path) + { + Enumeration e = node.keys(); + while (e.hasMoreElements()) + { + String pc = (String) e.nextElement(); + Node childNode = (Node) node.get(pc); + pc = path + '/' + pc; + if (childNode.object != null) + result.addElement(pc); + addSiblingNames(childNode, result, pc); + } + } + + public Enumeration elements() + { + Vector result = new Vector(); + addSiblingObjects(root_node, result); + return result.elements(); + } + + public void addSiblingObjects(Node node, Vector result) + { + Enumeration e = node.keys(); + while (e.hasMoreElements()) + { + Node childNode = (Node) node.get(e.nextElement()); + if (childNode.object != null) + result.addElement(childNode.object); + addSiblingObjects(childNode, result); + } + } + + class Node extends Hashtable + { + Object object; + } + } + + /** + * Http session support + *

+ * TODO: provide lazy session restoring, it should allow to load classes from wars 1st step it read serialization data and store under session attribute 2nd + * when the session requested, it tries to deserialize all session attributes considered that all classes available + */ + public static class AcmeSession extends Hashtable implements HttpSession + { + private long createTime; + + private long lastAccessTime; + + private String id; + + private int inactiveInterval; // in seconds + + private boolean expired; + + private transient ServletContext servletContext; + + private transient HttpSessionContext sessionContext; + + private transient List listeners; + + // TODO: check in documentation what is default inactive interval and + // what + // means 0 + // and what is mesurement unit + AcmeSession(String id, ServletContext servletContext, HttpSessionContext sessionContext) + { + this(id, 0, servletContext, sessionContext); + } + + AcmeSession(String id, int inactiveInterval, ServletContext servletContext, HttpSessionContext sessionContext) + { + // new Exception("Session created with: "+servletContext).printStackTrace(); //!!! + createTime = System.currentTimeMillis(); + this.id = id; + this.inactiveInterval = inactiveInterval; + this.servletContext = servletContext; + this.sessionContext = sessionContext; + } + + public long getCreationTime() + { + return createTime; + } + + public String getId() + { + return id; + } + + public long getLastAccessedTime() + { + return lastAccessTime; + } + + public void setMaxInactiveInterval(int interval) + { + inactiveInterval = interval; + } + + public int getMaxInactiveInterval() + { + return inactiveInterval; + } + + /** + * @deprecated + */ + public HttpSessionContext getSessionContext() + { + return sessionContext; + } + + /** + * Returns the ServletContext to which this session belongs. + * + * @return The ServletContext object for the web application + * @ince 2.3 + */ + public ServletContext getServletContext() + { + // System.err.println("ctx from:"+servletContext); //!!! + return servletContext; + } + + public Object getAttribute(String name) throws IllegalStateException + { + if (expired) + throw new IllegalStateException(); + return get((Object) name); + } + + public Object getValue(String name) throws IllegalStateException + { + return getAttribute(name); + } + + public Enumeration getAttributeNames() throws IllegalStateException + { + if (expired) + throw new IllegalStateException(); + return keys(); + } + + public String[] getValueNames() throws IllegalStateException + { + Enumeration e = getAttributeNames(); + Vector names = new Vector(); + while (e.hasMoreElements()) + names.addElement(e.nextElement()); + String[] result = new String[names.size()]; + names.copyInto(result); + return result; + } + + public void setAttribute(String name, Object value) throws IllegalStateException + { + if (expired) + throw new IllegalStateException(); + Object oldValue = value != null ? put((Object) name, value) : remove(name); + if (oldValue != null) + if (oldValue instanceof HttpSessionBindingListener) + ((HttpSessionBindingListener) oldValue).valueUnbound(new HttpSessionBindingEvent(this, name)); + else if (oldValue instanceof HttpSessionAttributeListener) + ((HttpSessionAttributeListener) oldValue).attributeReplaced(new HttpSessionBindingEvent(this, name, + value)); + if (value instanceof HttpSessionBindingListener) + ((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name)); + else if (value instanceof HttpSessionAttributeListener) + ((HttpSessionAttributeListener) value).attributeAdded(new HttpSessionBindingEvent(this, name)); + } + + public void putValue(String name, Object value) throws IllegalStateException + { + setAttribute(name, value); + } + + public void removeAttribute(String name) throws IllegalStateException + { + if (expired) + throw new IllegalStateException(); + Object value = remove((Object) name); + if (value != null) + if (value instanceof HttpSessionBindingListener) + ((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name)); + else if (value instanceof HttpSessionAttributeListener) + ((HttpSessionAttributeListener) value).attributeRemoved(new HttpSessionBindingEvent(this, name)); + } + + public void removeValue(String name) throws IllegalStateException + { + removeAttribute(name); + } + + public synchronized void invalidate() throws IllegalStateException + { + if (expired) + throw new IllegalStateException(); + notifyListeners(); + Enumeration e = getAttributeNames(); + while (e.hasMoreElements()) + { + removeAttribute((String) e.nextElement()); + } + setExpired(true); + // would be nice remove it from hash table also + } + + public boolean isNew() throws IllegalStateException + { + if (expired) + throw new IllegalStateException(); + return lastAccessTime == 0; + } + + public synchronized void setListeners(List l) + { + if (listeners == null) + { + listeners = l; + if (listeners != null) + { + HttpSessionEvent event = new HttpSessionEvent(this); + for (int i = 0; i < listeners.size(); i++) + try + { + ((HttpSessionListener) listeners.get(0)).sessionCreated(event); + } + catch (ClassCastException cce) + { + // log("Wrong session listener type."+cce); + } + catch (NullPointerException npe) + { + // log("Null session listener."); + } + } + } + } + + /** + * something hack, to update servlet context since session created out of scope + * + * @param sc + */ + public synchronized void setServletContext(ServletContext sc) + { + // System.err.println("ctx to:"+servletContext); //!!! + servletContext = sc; + } + + private void notifyListeners() + { + if (listeners != null) + { + HttpSessionEvent event = new HttpSessionEvent(this); + for (int i = 0; i < listeners.size(); i++) + try + { + ((HttpSessionListener) listeners.get(i)).sessionDestroyed(event); + } + catch (ClassCastException cce) + { + // log("Wrong session listener type."+cce); + } + catch (NullPointerException npe) + { + // log("Null session listener."); + } + } + } + + private void setExpired(boolean expired) + { + this.expired = expired; + } + + boolean isValid() + { + return !expired; + } + + boolean checkExpired() + { + return inactiveInterval > 0 && (inactiveInterval * 1000 < System.currentTimeMillis() - lastAccessTime); + } + + void userTouch() + { + if (isValid()) + lastAccessTime = System.currentTimeMillis(); + else + throw new IllegalStateException(); + } + + // storing session in format + // id:latency:contextname:tttt + // entry:base64 ser data + // entry:base64 ser data + // $$ + void save(Writer w) throws IOException + { + if (expired) + return; + // can't use append because old JDK + w.write(id); + w.write(':'); + w.write(Integer.toString(inactiveInterval)); + w.write(':'); + w.write(servletContext == null || servletContext.getServletContextName() == null ? "" : servletContext + .getServletContextName()); + w.write(':'); + w.write(Long.toString(lastAccessTime)); + w.write("\r\n"); + Enumeration e = getAttributeNames(); + ByteArrayOutputStream os = new ByteArrayOutputStream(1024 * 16); + while (e.hasMoreElements()) + { + String aname = (String) e.nextElement(); + Object so = get(aname); + if (so instanceof Serializable) + { + os.reset(); + ObjectOutputStream oos = new ObjectOutputStream(os); + try + { + oos.writeObject(so); + w.write(aname); + w.write(":"); + w.write(Utils.base64Encode(os.toByteArray())); + w.write("\r\n"); + } + catch (IOException ioe) + { + servletContext.log("Problem storing a session value of " + aname, ioe); + } + } + else + servletContext.log("Non serializable object " + so.getClass().getName() + " skiped in storing of " + aname, null); + if (so instanceof HttpSessionActivationListener) + ((HttpSessionActivationListener) so).sessionWillPassivate(new HttpSessionEvent(this)); + } + w.write("$$\r\n"); + } + + static AcmeSession restore(BufferedReader r, int inactiveInterval, ServletContext servletContext, + HttpSessionContext sessionContext) throws IOException + { + String s = r.readLine(); + if (s == null) // eos + return null; + int cp = s.indexOf(':'); + if (cp < 0) + throw new IOException("Invalid format for a session header, no session id: " + s); + String id = s.substring(0, cp); + int cp2 = s.indexOf(':', cp + 1); + if (cp2 < 0) + throw new IOException("Invalid format for a session header, no latency: " + s); + try + { + inactiveInterval = Integer.parseInt(s.substring(cp + 1, cp2)); + } + catch (NumberFormatException nfe) + { + servletContext.log("Session latency is invalid:" + s.substring(cp + 1, cp2) + " " + nfe); + } + cp = s.indexOf(':', cp2 + 1); + if (cp < 0) + throw new IOException("Invalid format for a session header, context name: " + s); + String contextName = s.substring(cp2 + 1, cp); + // consider servletContext.getContext("/"+contextName) + AcmeSession result = new AcmeSession(id, inactiveInterval, contextName.length() == 0 ? servletContext + : null, sessionContext); + try + { + result.lastAccessTime = Long.parseLong(s.substring(cp + 1)); + } + catch (NumberFormatException nfe) + { + servletContext.log("Last access time is invalid:" + s.substring(cp + 1) + " " + nfe); + } + do + { + s = r.readLine(); + if (s == null) + throw new IOException("Unexpected end of a stream."); + if ("$$".equals(s)) + return result; + cp = s.indexOf(':'); + if (cp < 0) + throw new IOException("Invalid format for a session entry: " + s); + String aname = s.substring(0, cp); + // if (lazyRestore) + // result.put(aname, s.substring(cp+1)); + ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(Utils.decode64(s + .substring(cp + 1)))); + Throwable restoreError; + try + { + Object so; + result.put(aname, so = ois.readObject()); + restoreError = null; + if (so instanceof HttpSessionActivationListener) + ((HttpSessionActivationListener) so).sessionDidActivate(new HttpSessionEvent(result)); + + } + catch (ClassNotFoundException cnfe) + { + restoreError = cnfe; + + } + catch (NoClassDefFoundError ncdfe) + { + restoreError = ncdfe; + } + catch (IOException ioe) + { + restoreError = ioe; + } + if (restoreError != null) + servletContext.log("Can't restore :" + aname + ", " + restoreError); + } while (true); + } + } + + protected static class LocaleWithWeight implements Comparable + { + protected float weight; // should be int + + protected Locale locale; + + LocaleWithWeight(Locale l, float w) + { + locale = l; + weight = w; + // System.err.println("Created "+l+", with:"+w); + } + + public int compareTo(Object o) + { + if (o instanceof LocaleWithWeight) + return (int) (((LocaleWithWeight) o).weight - weight) * 100; + throw new IllegalArgumentException(); + } + + public Locale getLocale() + { + return locale; + } + } + + protected static class AcceptLocaleEnumeration implements Enumeration + { + Iterator i; + + public AcceptLocaleEnumeration(TreeSet/* */ts) + { + i = ts.iterator(); + } + + public boolean hasMoreElements() + { + return i.hasNext(); + } + + public Object nextElement() + { + return ((LocaleWithWeight) i.next()).getLocale(); + /* + * Locale l =((LocaleWithWeight)i.next()).getLocale(); System.err.println("Returned l:"+l); return l; + */ + } + } + + // TODO: reconsider implementation by providing + // inner class implementing HttpSessionContext + // and returning it on request + // to avoid casting this class to Hashtable + + protected static class HttpSessionContextImpl extends Hashtable implements HttpSessionContext + { + + public Enumeration getIds() + { + return keys(); + } + + public HttpSession getSession(String sessionId) + { + return (HttpSession) get(sessionId); + } + + void save(Writer w) throws IOException + { + Enumeration e = elements(); + while (e.hasMoreElements()) + ((AcmeSession) e.nextElement()).save(w); + } + + static HttpSessionContextImpl restore(BufferedReader br, int inactiveInterval, ServletContext servletContext) + throws IOException + { + HttpSessionContextImpl result = new HttpSessionContextImpl(); + AcmeSession session; + while ((session = AcmeSession.restore(br, inactiveInterval, servletContext, result)) != null) + if (session.checkExpired() == false) + result.put(session.getId(), session); + return result; + } + } +} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/BaseRestServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/BaseRestServer.java new file mode 100644 index 000000000000..dca66e2421c7 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/BaseRestServer.java @@ -0,0 +1,62 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.utils.StringUtils; +import org.jboss.resteasy.spi.ResteasyDeployment; + +/** + * @author lishen + */ +public abstract class BaseRestServer implements RestServer { + + public void start(URL url) { + getDeployment().getMediaTypeMappings().put("json", "application/json"); + getDeployment().getMediaTypeMappings().put("xml", "text/xml"); +// server.getDeployment().getMediaTypeMappings().put("xml", "application/xml"); + getDeployment().getProviderClasses().add(RpcContextFilter.class.getName()); + + loadProviders(url.getParameter(Constants.EXTENSION_KEY, "")); + + doStart(url); + } + + public void deploy(Class resourceDef, Object resourceInstance, String contextPath) { + if (StringUtils.isEmpty(contextPath)) { + getDeployment().getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef)); + } else { + getDeployment().getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef), contextPath); + } + } + + public void undeploy(Class resourceDef) { + getDeployment().getRegistry().removeRegistrations(resourceDef); + } + + protected void loadProviders(String value) { + for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(value)) { + if (!StringUtils.isEmpty(clazz)) { + getDeployment().getProviderClasses().add(clazz.trim()); + } + } + } + + protected abstract ResteasyDeployment getDeployment(); + + protected abstract void doStart(URL url); +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java new file mode 100644 index 000000000000..a4bc90fa0c9b --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java @@ -0,0 +1,123 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.http.HttpBinder; +import com.alibaba.dubbo.remoting.http.HttpHandler; +import com.alibaba.dubbo.remoting.http.HttpServer; +import com.alibaba.dubbo.remoting.http.servlet.BootstrapListener; +import com.alibaba.dubbo.remoting.http.servlet.ServletManager; +import com.alibaba.dubbo.rpc.RpcContext; +import com.alibaba.dubbo.rpc.RpcException; +import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher; +import org.jboss.resteasy.spi.ResteasyDeployment; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Enumeration; + +/** + * @author lishen + */ +public class DubboHttpServer extends BaseRestServer { + + private final HttpServletDispatcher dispatcher = new HttpServletDispatcher(); + private final ResteasyDeployment deployment = new ResteasyDeployment(); + private HttpBinder httpBinder; + private HttpServer httpServer; +// private boolean isExternalServer; + + public DubboHttpServer(HttpBinder httpBinder) { + this.httpBinder = httpBinder; + } + + protected void doStart(URL url) { + // TODO jetty will by default enable keepAlive so the xml config has no effect now + httpServer = httpBinder.bind(url, new RestHandler()); + + ServletContext servletContext = ServletManager.getInstance().getServletContext(url.getPort()); + if (servletContext == null) { + servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT); + } + if (servletContext == null) { + throw new RpcException("No servlet context found. If you are using server='servlet', " + + "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml"); + } + + servletContext.setAttribute(ResteasyDeployment.class.getName(), deployment); + + try { + dispatcher.init(new SimpleServletConfig(servletContext)); + } catch (ServletException e) { + throw new RpcException(e); + } + } + + public void stop() { + httpServer.close(); + } + + protected ResteasyDeployment getDeployment() { + return deployment; + } + + private class RestHandler implements HttpHandler { + + public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { + // use the below approach if we want to minimize the dependencies on resteasy's internal stuff + // RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); + dispatcher.service(request, response); + } + } + + private static class SimpleServletConfig implements ServletConfig { + + private final ServletContext servletContext; + + public SimpleServletConfig(ServletContext servletContext) { + this.servletContext = servletContext; + } + + public String getServletName() { + return "DispatcherServlet"; + } + + public ServletContext getServletContext() { + return servletContext; + } + + public String getInitParameter(String s) { + return null; + } + + public Enumeration getInitParameterNames() { + return new Enumeration() { + public boolean hasMoreElements() { + return false; + } + + public Object nextElement() { + return null; + } + }; + } + } +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboResourceFactory.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboResourceFactory.java new file mode 100644 index 000000000000..c28cc22518de --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboResourceFactory.java @@ -0,0 +1,71 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import org.jboss.resteasy.spi.HttpRequest; +import org.jboss.resteasy.spi.HttpResponse; +import org.jboss.resteasy.spi.ResourceFactory; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + +/** + * We don't support propertyInjector here since the resource impl should be singleton in dubbo + * + * @author lishen + */ +public class DubboResourceFactory implements ResourceFactory { + + private Object resourceInstance; + private Class scannableClass; +// private PropertyInjector propertyInjector; +// private String context = null; + + public DubboResourceFactory(Object resourceInstance, Class scannableClass) { + this.resourceInstance = resourceInstance; + this.scannableClass = scannableClass; + } + +// public PropertyInjector getPropertyInjector() { +// return propertyInjector; +// } + + public Object createResource(HttpRequest request, HttpResponse response, + ResteasyProviderFactory factory) { + return resourceInstance; + } + + public Class getScannableClass() { + return scannableClass; + } + + public void registered(ResteasyProviderFactory factory) { +// this.propertyInjector = factory.getInjectorFactory().createPropertyInjector(getScannableClass(), factory); + } + + public void requestFinished(HttpRequest request, HttpResponse response, + Object resource) { + } + + public void unregistered() { + } + +// public void setContext(String context) { +// this.context = context; +// } +// +// public String getContext() { +// return context; +// } +} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/NettyServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/NettyServer.java new file mode 100644 index 000000000000..2bfdd65ebc5f --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/NettyServer.java @@ -0,0 +1,47 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer; +import org.jboss.resteasy.spi.ResteasyDeployment; + +/** + * Netty server can't support @Context injection of servlet objects since it's not a servlet container + * + * @author lishen + */ +public class NettyServer extends BaseRestServer { + + private final NettyJaxrsServer server = new NettyJaxrsServer(); + + protected void doStart(URL url) { + server.setPort(url.getPort()); + server.setKeepAlive(url.getParameter(Constants.KEEP_ALIVE_KEY, Constants.DEFAULT_KEEP_ALIVE)); + server.setExecutorThreadCount(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS)); + server.setIoWorkerCount(url.getParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS)); + server.start(); + } + + public void stop() { + server.stop(); + } + + protected ResteasyDeployment getDeployment() { + return server.getDeployment(); + } +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java new file mode 100644 index 000000000000..35036e0753e8 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java @@ -0,0 +1,146 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.remoting.http.HttpBinder; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import com.alibaba.dubbo.rpc.protocol.ServiceImplHolder; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.PoolingClientConnectionManager; +import org.apache.http.params.HttpConnectionParams; +import org.apache.http.params.HttpParams; +import org.jboss.resteasy.client.jaxrs.ResteasyClient; +import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; +import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; +import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine; +import org.jboss.resteasy.util.GetRestful; + +import javax.ws.rs.ProcessingException; +import javax.ws.rs.WebApplicationException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author lishen + */ +public class RestProtocol extends AbstractProxyProtocol { + + private static final int DEFAULT_PORT = 80; + + private final Map servers = new ConcurrentHashMap(); + + private final RestServerFactory serverFactory = new RestServerFactory(); + + public RestProtocol() { + super(WebApplicationException.class, ProcessingException.class); + } + + public void setHttpBinder(HttpBinder httpBinder) { + serverFactory.setHttpBinder(httpBinder); + } + + public int getDefaultPort() { + return DEFAULT_PORT; + } + + protected Runnable doExport(T impl, Class type, URL url) throws RpcException { + String addr = url.getIp() + ":" + url.getPort(); + Class implClass = ServiceImplHolder.getInstance().popServiceImpl().getClass(); + RestServer server = servers.get(addr); + if (server == null) { + server = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, "jetty")); + server.start(url); + servers.put(addr, server); + } + + final Class resourceDef = GetRestful.getRootResourceClass(implClass) != null ? implClass : type; + server.deploy(resourceDef, impl, getContextPath(url)); + + final RestServer s = server; + return new Runnable() { + public void run() { + // TODO due to dubbo's current architecture, + // it will be called from registry protocol in the shutdown process and won't appear in logs + s.undeploy(resourceDef); + } + }; + } + + protected T doRefer(Class serviceType, URL url) throws RpcException { + // TODO more configs to add + + PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); + // 20 is the default maxTotal of current PoolingClientConnectionManager + connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20)); + +// BasicHttpContext localContext = new BasicHttpContext(); + + DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager); + + HttpParams params = httpClient.getParams(); + // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now + HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + + ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/); + + ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); + + for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { + if (!StringUtils.isEmpty(clazz)) { + try { + client.register(Thread.currentThread().getContextClassLoader().loadClass(clazz.trim())); + } catch (ClassNotFoundException e) { + throw new RpcException("Error loading JAX-RS extension class: " + clazz.trim(), e); + } + } + } + + // TODO protocol + ResteasyWebTarget target = client.target("http://" + url.getHost() + ":" + url.getPort() + "/" + getContextPath(url)); + return target.proxy(serviceType); + } + + protected int getErrorCode(Throwable e) { + // TODO + return super.getErrorCode(e); + } + + public void destroy() { + super.destroy(); + for (Map.Entry entry : servers.entrySet()) { + try { + if (logger.isInfoEnabled()) { + logger.info("Closing the rest server at " + entry.getKey()); + } + entry.getValue().stop(); + } catch (Throwable t) { + logger.warn("Error closing rest server", t); + } + } + servers.clear(); + } + + protected String getContextPath(URL url) { + // TODO better solution? + int pos = url.getPath().indexOf("/"); + return pos > 0 ? url.getPath().substring(0, pos) : ""; + } +} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServer.java new file mode 100644 index 000000000000..cc989550a06b --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServer.java @@ -0,0 +1,35 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import com.alibaba.dubbo.common.URL; + +/** + * @author lishen + */ +public interface RestServer { + + void start(URL url); + + /** + * @param resourceDef it could be either resource interface or resource impl + */ + void deploy(Class resourceDef, Object resourceInstance, String contextPath); + + void undeploy(Class resourceDef); + + void stop(); +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java new file mode 100644 index 000000000000..54b26f71df79 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java @@ -0,0 +1,48 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import com.alibaba.dubbo.remoting.http.HttpBinder; + +/** + * Only the server that implements servlet container + * could support something like @Context injection of servlet objects. + * + * @author lishen + */ +public class RestServerFactory { + + private HttpBinder httpBinder; + + public void setHttpBinder(HttpBinder httpBinder) { + this.httpBinder = httpBinder; + } + + public RestServer createServer(String name) { + // TODO move names to Constants + if ("servlet".equalsIgnoreCase(name) || "jetty".equalsIgnoreCase(name)) { + return new DubboHttpServer(httpBinder); + } else if ("tjws".equalsIgnoreCase(name)) { + return new TjwsServer(); + } else if ("netty".equalsIgnoreCase(name)) { + return new NettyServer(); + } else if ("sunhttp".equalsIgnoreCase(name)) { + return new SunHttpServer(); + } else { + throw new IllegalArgumentException("Unrecognized server name: " + name); + } + } +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java new file mode 100644 index 000000000000..bfde8eb23b92 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java @@ -0,0 +1,38 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import com.alibaba.dubbo.rpc.RpcContext; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import java.io.IOException; + +/** + * @author lishen + */ +public class RpcContextFilter implements ContainerRequestFilter { + + public void filter(ContainerRequestContext requestContext) throws IOException { + HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class); + // this only works for servlet containers + if (request != null) { + RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); + } + } +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/SunHttpServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/SunHttpServer.java new file mode 100644 index 000000000000..7e4e51a1e17d --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/SunHttpServer.java @@ -0,0 +1,41 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import com.alibaba.dubbo.common.URL; +import org.jboss.resteasy.plugins.server.sun.http.SunHttpJaxrsServer; +import org.jboss.resteasy.spi.ResteasyDeployment; + +/** + * @author lishen + */ +public class SunHttpServer extends BaseRestServer { + + private final SunHttpJaxrsServer server = new SunHttpJaxrsServer(); + + protected void doStart(URL url) { + server.setPort(url.getPort()); + server.start(); + } + + public void stop() { + server.stop(); + } + + protected ResteasyDeployment getDeployment() { + return server.getDeployment(); + } +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/TjwsServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/TjwsServer.java new file mode 100644 index 000000000000..a8a765144d68 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/TjwsServer.java @@ -0,0 +1,43 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import com.alibaba.dubbo.common.URL; +import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer; +import org.jboss.resteasy.spi.ResteasyDeployment; + +/** + * @author lishen + */ +public class TjwsServer extends BaseRestServer { + + private final TJWSEmbeddedJaxrsServer server = new TJWSEmbeddedJaxrsServer(); + + protected void doStart(URL url) { + server.setPort(url.getPort()); + // below config is useless due to a resteasy bug +// server.setKeepAlive(false); + server.start(); + } + + protected ResteasyDeployment getDeployment() { + return server.getDeployment(); + } + + public void stop() { + server.stop(); + } +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java new file mode 100644 index 000000000000..d20553d1163a --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java @@ -0,0 +1,53 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +/** + * TODO implement this after migrating to servlet 3.x api + * + * @author lishen + */ +public class UndertowServer /*implements RestServer*/ { + +// // NOTEUndertowJaxrsServer doesn't implement EmbeddedJaxrsServer +// private final UndertowJaxrsServer server = new UndertowJaxrsServer(); +// +// private final ResteasyDeployment deployment = new ResteasyDeployment(); +// +// public void start(String host, int port) { +// deployment.start(); +// DeploymentInfo deploymentInfo = server.undertowDeployment(deployment); +// deploymentInfo.setContextPath("/"); +// deploymentInfo.setDeploymentName("dubbo-rest"); +// deploymentInfo.setClassLoader(Thread.currentThread().getContextClassLoader()); +// server.start(Undertow.builder().addListener(port, host)); +// server.deploy(deploymentInfo); +//// server.start(); +// } +// +// public void deploy(Class resourceDef, Object resourceInstance) { +// deployment.getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef)); +// } +// +// public void undeploy(Class resourceDef) { +// +// } +// +// public void stop() { +// +// } + +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/Acme/Resource/mime.properties b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/Acme/Resource/mime.properties new file mode 100644 index 000000000000..f3afc3999bff --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/Acme/Resource/mime.properties @@ -0,0 +1,104 @@ +# $Id: mime.properties,v 1.1 2009/12/10 04:30:50 dmitriy Exp $ +HTML=text/html +HTM=text/html +TXT=text/plain +XML=text/xml +CSS=text/css +SGML=text/x-sgml +SGM=text/x-sgml +GIF=image/gif +JPG=image/jpeg +JPEG=image/jpeg +JPE=image/jpeg +PNG=image/png +BMP=image/bmp +TIF=image/tiff +TIFF=image/tiff +RGB=image/x-rgb +XPM=image/x-xpixmap +XBM=image/x-xbitmap +SVG=image/svg-xml +SVGZ=image/svg-xml +# Audio +AU=audio/basic +SND=audio/basic +MID=audio/mid +MIDI=audio/mid +RMI=audio/mid +KAR=audio/mid +MPGA=audio/mpeg +MP2=audio/mpeg +MP3=audio/mpeg +WAV=audio/wav +AIFF=audio/aiff +AIFC=audio/aiff +AIF=audio/x-aiff +RA=audio/x-realaudio +RPM=audio/x-pn-realaudio-plugin +RAM=audio/x-pn-realaudio +SD2=audio/x-sd2 +# Applications +BIN=application/octet-stream +DMS=application/octet-stream +LHA=application/octet-stream +LZH=application/octet-stream +EXE=application/octet-stream +DLL=application/octet-stream +CLASS=application/octet-stream +HQX=application/mac-binhex40 +PS=application/postscript +AI=application/postscript +EPS=application/postscript +PDF=application/pdf +RTF=application/rtf +DOC=application/msword +DOCX=application/msword +PPT=application/powerpoint +PPTX=application/powerpoint +FIF=application/fractals +P7C=application/pkcs7-mime +# Application/x +JS=application/x-javascript +Z=application/x-compress +GZ=application/x-gzip +TAR=application/x-tar +TGZ=application/x-compressed +ZIP=application/x-zip-compressed +DIR=application/x-director +DCR=application/x-director +DXR=application/x-director +DVI=application/x-dvi +TEX=application/x-tex +LATEX=application/x-latex +TCL=application/x-tcl +CER=application/x-x509-ca-cert +CRT=application/x-x509-ca-cert +DER=application/x-x509-ca-cert +ISO=application/x-iso9660-image +# Video +MPG=video/mpeg +MPE=video/mpeg +MPEG=video/mpeg +QT=video/quicktime +MOV=video/quicktime +AVI=video/x-msvideo +MOVIE=video/x-sgi-movie +# Chemical +PDB=chemical/x-pdb +XYZ=chemical/x-pdb +# X- +ICE=x-conference/x-cooltalk +JNLP=application/x-java-jnlp-file +WRL=x-world/x-vrml +VRML=x-world/x-vrml +WML=text/vnd.wap.wml +WMLC=application/vnd.wap.wmlc +WMLS=text/vnd.wap.wmlscript +WMLSC=application/vnd.wap.wmlscriptc +WBMP=image/vnd.wap.wbmp +FLAC=audio/flac +OGG=audio/ogg +OGA=audio/ogg +SPX=audio/ogg +OGV=video/ogg +OGX=application/ogg \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol new file mode 100644 index 000000000000..a0f05272d08b --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol @@ -0,0 +1 @@ +rest=com.alibaba.dubbo.rpc.protocol.rest.RestProtocol \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-api/pom.xml b/dubbo-test/dubbo-test-benchmark-api/pom.xml new file mode 100644 index 000000000000..332a7cce7e6d --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-api/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + com.alibaba + dubbo-test + 2.8.0 + + dubbo-test-benchmark-api + jar + ${project.artifactId} + The benchmark test module of dubbo project + + true + + + + com.alibaba + dubbo-common + ${project.parent.version} + + + com.alibaba + dubbo-rpc-rest + ${project.parent.version} + + + javax.servlet + servlet-api + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidRequest.java b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidRequest.java new file mode 100644 index 000000000000..0073d0ba000e --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidRequest.java @@ -0,0 +1,57 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; +import java.util.List; + +/** + * @author lishen + */ +@XmlRootElement +public class BidRequest implements Serializable { + + private String id; + + private Device device; + + private List impressions; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Device getDevice() { + return device; + } + + public void setDevice(Device device) { + this.device = device; + } + + public List getImpressions() { + return impressions; + } + + public void setImpressions(List impressions) { + this.impressions = impressions; + } +} diff --git a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidResponse.java b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidResponse.java new file mode 100644 index 000000000000..b38f1507f485 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidResponse.java @@ -0,0 +1,46 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; +import java.util.List; + +/** + * @author lishen + */ +@XmlRootElement +public class BidResponse implements Serializable { + + private String id; + private List seatBids; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public List getSeatBids() { + return seatBids; + } + + public void setSeatBids(List seatBids) { + this.seatBids = seatBids; + } +} diff --git a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Device.java b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Device.java new file mode 100644 index 000000000000..c99b00e43939 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Device.java @@ -0,0 +1,81 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * @author lishen + */ +@XmlRootElement +public class Device implements Serializable { + + private String os; + private String make; + private String version; + private String model; + private String lang; + private Geo geo; + + public String getOs() { + return os; + } + + public void setOs(String os) { + this.os = os; + } + + public String getMake() { + return make; + } + + public void setMake(String make) { + this.make = make; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + public String getLang() { + return lang; + } + + public void setLang(String lang) { + this.lang = lang; + } + + public Geo getGeo() { + return geo; + } + + public void setGeo(Geo geo) { + this.geo = geo; + } +} diff --git a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/EchoService.java b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/EchoService.java new file mode 100644 index 000000000000..1d735918ada2 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/EchoService.java @@ -0,0 +1,40 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("echo") +@Consumes({MediaType.APPLICATION_JSON}) +//@Consumes({MediaType.TEXT_XML}) +@Produces({MediaType.APPLICATION_JSON}) +//@Produces({MediaType.TEXT_XML}) +public interface EchoService { + + @POST + @Path("bid") +// @GZIP + BidRequest bid(/*@GZIP */BidRequest request); + + @POST + @Path("text") +// @GZIP + Text text(/*@GZIP */Text text); +} \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Geo.java b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Geo.java new file mode 100644 index 000000000000..2733c494e22b --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Geo.java @@ -0,0 +1,63 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * @author lishen + */ +@XmlRootElement +public class Geo implements Serializable { + + private float lon; + private float lat; + private String country; + private String city; + + public float getLon() { + return lon; + } + + public void setLon(float lon) { + this.lon = lon; + } + + public float getLat() { + return lat; + } + + public void setLat(float lat) { + this.lat = lat; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getCity() { + return city; + } + + public void setCity(String city) { + this.city = city; + } +} diff --git a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Impression.java b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Impression.java new file mode 100644 index 000000000000..9d7ac8f13313 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Impression.java @@ -0,0 +1,45 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * @author lishen + */ +@XmlRootElement +public class Impression implements Serializable { + + private String id; + private double bidFloor; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public double getBidFloor() { + return bidFloor; + } + + public void setBidFloor(double bidFloor) { + this.bidFloor = bidFloor; + } +} diff --git a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/SeatBid.java b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/SeatBid.java new file mode 100644 index 000000000000..8132e267c5c1 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/SeatBid.java @@ -0,0 +1,46 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * @author lishen + */ +@XmlRootElement +public class SeatBid implements Serializable { + + private String seat; + + private String group; + + public String getSeat() { + return seat; + } + + public void setSeat(String seat) { + this.seat = seat; + } + + public String getGroup() { + return group; + } + + public void setGroup(String group) { + this.group = group; + } +} diff --git a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/SerializationOptimizerImpl.java b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/SerializationOptimizerImpl.java new file mode 100644 index 000000000000..ba7aa3fcb2a9 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/SerializationOptimizerImpl.java @@ -0,0 +1,41 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +import com.alibaba.dubbo.common.serialize.support.SerializationOptimizer; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +/** + * This class must be accessible from both the provider and consumer + * + * @author lishen + */ +public class SerializationOptimizerImpl implements SerializationOptimizer { + + public Collection getSerializableClasses() { + List classes = new LinkedList(); + classes.add(BidRequest.class); + classes.add(BidResponse.class); + classes.add(Device.class); + classes.add(Geo.class); + classes.add(Impression.class); + classes.add(SeatBid.class); + return classes; + } +} diff --git a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Text.java b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Text.java new file mode 100644 index 000000000000..077ffdda5d9a --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Text.java @@ -0,0 +1,43 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * @author lishen + */ +@XmlRootElement +public class Text implements Serializable { + + private String contents; + + public Text() { + } + + public Text(String contents) { + this.contents = contents; + } + + public String getContents() { + return contents; + } + + public void setContents(String contents) { + this.contents = contents; + } +} diff --git a/dubbo-test/dubbo-test-benchmark-client/pom.xml b/dubbo-test/dubbo-test-benchmark-client/pom.xml new file mode 100644 index 000000000000..ca7f1b842fee --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/pom.xml @@ -0,0 +1,200 @@ + + + 4.0.0 + + com.alibaba + dubbo-test + 2.8.0 + + dubbo-test-benchmark-client + jar + ${project.artifactId} + The benchmark test module of dubbo project + + true + + + + com.alibaba + dubbo + ${project.parent.version} + + + com.alibaba + dubbo-test-benchmark-api + ${project.parent.version} + + + commons-lang + commons-lang + 2.6 + + + org.javassist + javassist + + + org.jboss.netty + netty + + + org.apache.mina + mina-core + + + org.glassfish.grizzly + grizzly-core + + + org.apache.httpcomponents + httpclient + + + com.alibaba + fastjson + + + com.thoughtworks.xstream + xstream + + + org.apache.bsf + bsf-api + + + org.apache.zookeeper + zookeeper + + + com.github.sgroschupf + zkclient + + + org.apache.curator + curator-framework + + + com.googlecode.xmemcached + xmemcached + + + org.apache.cxf + cxf-rt-frontend-simple + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.thrift + libthrift + + + com.caucho + hessian + + + javax.servlet + servlet-api + + + org.mortbay.jetty + jetty + + + log4j + log4j + + + org.slf4j + slf4j-api + + + redis.clients + jedis + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + javax.cache + cache-api + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + + + + + src/main/resources + + **/*.* + + + + + + maven-dependency-plugin + + + unpack + package + + unpack + + + + + com.alibaba + dubbo + ${project.parent.version} + ${project.build.directory}/dubbo + META-INF/assembly/** + + + + + + + + maven-assembly-plugin + + src/assembly/assembly.xml + + + + make-assembly + package + + single + + + + + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-client/src/assembly/assembly.xml b/dubbo-test/dubbo-test-benchmark-client/src/assembly/assembly.xml new file mode 100644 index 000000000000..0617798a708f --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/assembly/assembly.xml @@ -0,0 +1,23 @@ + + assembly + + tar.gz + + true + + + src/cli + / + 0755 + + + src/main/resources + conf + + + + + lib + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-client/src/cli/run.bat b/dubbo-test/dubbo-test-benchmark-client/src/cli/run.bat new file mode 100644 index 000000000000..54b4406fa89b --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/cli/run.bat @@ -0,0 +1 @@ +java -Xms1g -Xmx1g -XX:PermSize=64M -XX:+UseConcMarkSweepGC -Djava.ext.dirs=lib -classpath conf com.alibaba.dubbo.rpc.benchmark.RpcBenchmarkClient > benchmark.log \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-client/src/cli/run.sh b/dubbo-test/dubbo-test-benchmark-client/src/cli/run.sh new file mode 100644 index 000000000000..7389f902f9c4 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/cli/run.sh @@ -0,0 +1 @@ +java -Xms1g -Xmx1g -XX:PermSize=64M -XX:+UseConcMarkSweepGC -Djava.ext.dirs=./lib -classpath conf com.alibaba.dubbo.rpc.benchmark.RpcBenchmarkClient > "benchmark.log" 2>&1 \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java new file mode 100644 index 000000000000..63dbf9783e4d --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java @@ -0,0 +1,251 @@ +package com.alibaba.dubbo.rpc.benchmark; + +/** + * nfs-rpc + * Apache License + * + * http://code.google.com/p/nfs-rpc (c) 2011 + */ +import java.io.BufferedWriter; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.lang.reflect.InvocationTargetException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; + +import com.alibaba.dubbo.common.utils.ConfigUtils; + +/** + * Abstract benchmark client,test for difference scenes Usage: -Dwrite.statistics=false BenchmarkClient serverIP + * serverPort concurrents timeout codectype requestSize runtime(seconds) clientNums + * + * @author bluedavy + */ +public abstract class AbstractBenchmarkClient { + + private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + private static long maxTPS = 0; + + private static long minTPS = 0; + + private static long allRequestSum; + + private static long allResponseTimeSum; + + private static long allErrorRequestSum; + + private static long allErrorResponseTimeSum; + + private static int runtime; + + // < 0 + private static long below0sum; + + // (0,1] + private static long above0sum; + + // (1,5] + private static long above1sum; + + // (5,10] + private static long above5sum; + + // (10,50] + private static long above10sum; + + // (50,100] + private static long above50sum; + + // (100,500] + private static long above100sum; + + // (500,1000] + private static long above500sum; + + // > 1000 + private static long above1000sum; + + Properties properties = ConfigUtils.getProperties(); + + public void run(String[] args) throws Exception { + + final String serverIP = properties.getProperty("serverip"); + final int serverPort = Integer.parseInt(properties.getProperty("serverport")); + final int concurrents = Integer.parseInt(properties.getProperty("concurrents")); + final int timeout = Integer.parseInt(properties.getProperty("timeout")); + runtime = Integer.parseInt(properties.getProperty("runtime")); + final long endtime = System.nanoTime() / 1000L + runtime * 1000 * 1000L; + final int clientNums = Integer.parseInt(properties.getProperty("connectionnums")); + final String protocol =properties.getProperty("protocol"); + final String serialization =properties.getProperty("serialization"); + + // Print start info + Date currentDate = new Date(); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(currentDate); + calendar.add(Calendar.SECOND, runtime); + StringBuilder startInfo = new StringBuilder(dateFormat.format(currentDate)); + startInfo.append(" ready to start client benchmark,server is "); + startInfo.append(serverIP).append(":").append(serverPort); + startInfo.append(",protocol is: ").append(protocol); + startInfo.append(",serialization is: ").append(serialization); + startInfo.append(",concurrents is: ").append(concurrents); + startInfo.append(",clientNums is: ").append(clientNums); + startInfo.append(",timeout is:").append(timeout); + startInfo.append(" s,the benchmark will end at:").append(dateFormat.format(calendar.getTime())); + System.out.println(startInfo.toString()); + + CyclicBarrier barrier = new CyclicBarrier(concurrents); + CountDownLatch latch = new CountDownLatch(concurrents); + List runnables = new ArrayList(); + // benchmark start after thirty seconds,let java app warm up + long beginTime = System.nanoTime() / 1000L + 30 * 1000 * 1000L; + for (int i = 0; i < concurrents; i++) { + ClientRunnable runnable = getClientRunnable(protocol, serialization, serverIP, serverPort, clientNums, timeout, barrier, latch, + beginTime, endtime); + runnables.add(runnable); + } + + startRunnables(runnables); + + latch.await(); + + // read results & add all + // key: runtime second range value: Long[2] array Long[0]: execute count Long[1]: response time sum + Map times = new HashMap(); + Map errorTimes = new HashMap(); + for (ClientRunnable runnable : runnables) { + List results = runnable.getResults(); + long[] responseSpreads = results.get(0); + below0sum += responseSpreads[0]; + above0sum += responseSpreads[1]; + above1sum += responseSpreads[2]; + above5sum += responseSpreads[3]; + above10sum += responseSpreads[4]; + above50sum += responseSpreads[5]; + above100sum += responseSpreads[6]; + above500sum += responseSpreads[7]; + above1000sum += responseSpreads[8]; + long[] tps = results.get(1); + long[] responseTimes = results.get(2); + long[] errorTPS = results.get(3); + long[] errorResponseTimes = results.get(4); + for (int i = 0; i < tps.length; i++) { + String key = String.valueOf(i); + if (times.containsKey(key)) { + Long[] successInfos = times.get(key); + Long[] errorInfos = errorTimes.get(key); + successInfos[0] += tps[i]; + successInfos[1] += responseTimes[i]; + errorInfos[0] += errorTPS[i]; + errorInfos[1] += errorResponseTimes[i]; + times.put(key, successInfos); + errorTimes.put(key, errorInfos); + } else { + Long[] successInfos = new Long[2]; + successInfos[0] = tps[i]; + successInfos[1] = responseTimes[i]; + Long[] errorInfos = new Long[2]; + errorInfos[0] = errorTPS[i]; + errorInfos[1] = errorResponseTimes[i]; + times.put(key, successInfos); + errorTimes.put(key, errorInfos); + } + } + } + + long ignoreRequest = 0; + long ignoreErrorRequest = 0; + int maxTimeRange = runtime - 30; + // ignore the last 10 second requests,so tps can count more accurate + for (int i = 0; i < 10; i++) { + Long[] values = times.remove(String.valueOf(maxTimeRange - i)); + if (values != null) { + ignoreRequest += values[0]; + } + Long[] errorValues = errorTimes.remove(String.valueOf(maxTimeRange - i)); + if (errorValues != null) { + ignoreErrorRequest += errorValues[0]; + } + } + + for (Map.Entry entry : times.entrySet()) { + long successRequest = entry.getValue()[0]; + long errorRequest = 0; + if (errorTimes.containsKey(entry.getKey())) { + errorRequest = errorTimes.get(entry.getKey())[0]; + } + allRequestSum += successRequest; + allResponseTimeSum += entry.getValue()[1]; + allErrorRequestSum += errorRequest; + if (errorTimes.containsKey(entry.getKey())) { + allErrorResponseTimeSum += errorTimes.get(entry.getKey())[1]; + } + long currentRequest = successRequest + errorRequest; + if (currentRequest > maxTPS) { + maxTPS = currentRequest; + } + if (minTPS == 0 || currentRequest < minTPS) { + minTPS = currentRequest; + } + } + + boolean isWriteResult = Boolean.parseBoolean(System.getProperty("write.statistics", "false")); + if (isWriteResult) { + BufferedWriter writer = new BufferedWriter(new FileWriter("benchmark.all.results")); + for (Map.Entry entry : times.entrySet()) { + writer.write(entry.getKey() + "," + entry.getValue()[0] + "," + entry.getValue()[1] + "\r\n"); + } + writer.close(); + } + + System.out.println("----------Benchmark Statistics--------------"); + System.out.println(" Concurrents: " + concurrents); + System.out.println(" ClientNums: " + clientNums); + System.out.println(" Runtime: " + runtime + " seconds"); + System.out.println(" Benchmark Time: " + times.keySet().size()); + long benchmarkRequest = allRequestSum + allErrorRequestSum; + long allRequest = benchmarkRequest + ignoreRequest + ignoreErrorRequest; + System.out.println(" Requests: " + allRequest + " Success: " + (allRequestSum + ignoreRequest) * 100 + / allRequest + "% (" + (allRequestSum + ignoreRequest) + ") Error: " + + (allErrorRequestSum + ignoreErrorRequest) * 100 / allRequest + "% (" + + (allErrorRequestSum + ignoreErrorRequest) + ")"); + System.out.println(" Avg TPS: " + benchmarkRequest / times.keySet().size() + " Max TPS: " + maxTPS + + " Min TPS: " + minTPS); + System.out.println(" Avg RT: " + (allErrorResponseTimeSum + allResponseTimeSum) / benchmarkRequest / 1000f + + "ms"); + System.out.println(" RT <= 0: " + (below0sum * 100 / allRequest) + "% " + below0sum + "/" + allRequest); + System.out.println(" RT (0,1]: " + (above0sum * 100 / allRequest) + "% " + above0sum + "/" + allRequest); + System.out.println(" RT (1,5]: " + (above1sum * 100 / allRequest) + "% " + above1sum + "/" + allRequest); + System.out.println(" RT (5,10]: " + (above5sum * 100 / allRequest) + "% " + above5sum + "/" + allRequest); + System.out.println(" RT (10,50]: " + (above10sum * 100 / allRequest) + "% " + above10sum + "/" + allRequest); + System.out.println(" RT (50,100]: " + (above50sum * 100 / allRequest) + "% " + above50sum + "/" + allRequest); + System.out.println(" RT (100,500]: " + (above100sum * 100 / allRequest) + "% " + above100sum + "/" + allRequest); + System.out.println(" RT (500,1000]: " + (above500sum * 100 / allRequest) + "% " + above500sum + "/" + + allRequest); + System.out.println(" RT > 1000: " + (above1000sum * 100 / allRequest) + "% " + above1000sum + "/" + allRequest); + System.exit(0); + } + + public abstract ClientRunnable getClientRunnable(String protocol, String serialization, String targetIP, int targetPort, int clientNums, int rpcTimeout, + CyclicBarrier barrier, CountDownLatch latch, long startTime, + long endTime) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException; + + protected void startRunnables(List runnables) { + for (int i = 0; i < runnables.size(); i++) { + final ClientRunnable runnable = runnables.get(i); + Thread thread = new Thread(runnable, "benchmarkclient-" + i); + thread.start(); + } + } + +} diff --git a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractClientRunnable.java b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractClientRunnable.java new file mode 100644 index 000000000000..9df55a6799ed --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractClientRunnable.java @@ -0,0 +1,176 @@ +package com.alibaba.dubbo.rpc.benchmark; + +/** + * nfs-rpc Apache License http://code.google.com/p/nfs-rpc (c) 2011 + */ +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Simple Processor RPC Benchmark Client Thread + * + * @author bluedavy + */ +public abstract class AbstractClientRunnable implements ClientRunnable { + + private static final Log LOGGER = LogFactory.getLog(AbstractClientRunnable.class); + + private CyclicBarrier barrier; + + private CountDownLatch latch; + + private long endTime; + + private boolean running = true; + + // response time spread + private long[] responseSpreads = new long[9]; + + // error request per second + private long[] errorTPS = null; + + // error response times per second + private long[] errorResponseTimes = null; + + // tps per second + private long[] tps = null; + + // response times per second + private long[] responseTimes = null; + + // benchmark startTime + private long startTime; + + // benchmark maxRange + private int maxRange; + + private ServiceFactory serviceFactory = new ServiceFactory(); + + public AbstractClientRunnable(String protocol, String serialization, String targetIP, int targetPort, int clientNums, int rpcTimeout, + CyclicBarrier barrier, CountDownLatch latch, long startTime, long endTime){ + + this.barrier = barrier; + this.latch = latch; + this.startTime = startTime; + this.endTime = endTime; + serviceFactory.setProtocol(protocol); + serviceFactory.setTargetIP(targetIP); + serviceFactory.setClientNums(clientNums); + serviceFactory.setTargetPort(targetPort); + serviceFactory.setConnectTimeout(rpcTimeout); + serviceFactory.setSerialization(serialization); + maxRange = (Integer.parseInt(String.valueOf((endTime - startTime))) / 1000000) + 1; + errorTPS = new long[maxRange]; + errorResponseTimes = new long[maxRange]; + tps = new long[maxRange]; + responseTimes = new long[maxRange]; + // init + for (int i = 0; i < maxRange; i++) { + errorTPS[i] = 0; + errorResponseTimes[i] = 0; + tps[i] = 0; + responseTimes[i] = 0; + } + } + + public void run() { + try { + barrier.await(); + } catch (Exception e) { + // IGNORE + } + runJavaAndHessian(); + latch.countDown(); + } + + private void runJavaAndHessian() { + while (running) { + long beginTime = System.nanoTime() / 1000L; + if (beginTime >= endTime) { + running = false; + break; + } + try { + Object result = invoke(serviceFactory); + long currentTime = System.nanoTime() / 1000L; + if (beginTime <= startTime) { + continue; + } + long consumeTime = currentTime - beginTime; + sumResponseTimeSpread(consumeTime); + int range = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000000; + if (range >= maxRange) { + System.err.println("benchmark range exceeds maxRange,range is: " + range + ",maxRange is: " + + maxRange); + continue; + } + if (result != null) { + tps[range] = tps[range] + 1; + responseTimes[range] = responseTimes[range] + consumeTime; + } else { + LOGGER.error("server return result is null"); + errorTPS[range] = errorTPS[range] + 1; + errorResponseTimes[range] = errorResponseTimes[range] + consumeTime; + } + } catch (Exception e) { + e.printStackTrace(); + LOGGER.error("client.invokeSync error", e); + long currentTime = System.nanoTime() / 1000L; + if (beginTime <= startTime) { + continue; + } + long consumeTime = currentTime - beginTime; + sumResponseTimeSpread(consumeTime); + int range = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000000; + if (range >= maxRange) { + System.err.println("benchmark range exceeds maxRange,range is: " + range + ",maxRange is: " + + maxRange); + continue; + } + errorTPS[range] = errorTPS[range] + 1; + errorResponseTimes[range] = errorResponseTimes[range] + consumeTime; + } + } + } + + public abstract Object invoke(ServiceFactory serviceFactory); + + public List getResults() { + List results = new ArrayList(); + results.add(responseSpreads); + results.add(tps); + results.add(responseTimes); + results.add(errorTPS); + results.add(errorResponseTimes); + return results; + } + + private void sumResponseTimeSpread(long responseTime) { + responseTime = responseTime / 1000L; + if (responseTime <= 0) { + responseSpreads[0] = responseSpreads[0] + 1; + } else if (responseTime > 0 && responseTime <= 1) { + responseSpreads[1] = responseSpreads[1] + 1; + } else if (responseTime > 1 && responseTime <= 5) { + responseSpreads[2] = responseSpreads[2] + 1; + } else if (responseTime > 5 && responseTime <= 10) { + responseSpreads[3] = responseSpreads[3] + 1; + } else if (responseTime > 10 && responseTime <= 50) { + responseSpreads[4] = responseSpreads[4] + 1; + } else if (responseTime > 50 && responseTime <= 100) { + responseSpreads[5] = responseSpreads[5] + 1; + } else if (responseTime > 100 && responseTime <= 500) { + responseSpreads[6] = responseSpreads[6] + 1; + } else if (responseTime > 500 && responseTime <= 1000) { + responseSpreads[7] = responseSpreads[7] + 1; + } else if (responseTime > 1000) { + responseSpreads[8] = responseSpreads[8] + 1; + } + } + +} diff --git a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidClientRunnable.java b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidClientRunnable.java new file mode 100644 index 000000000000..d136543f0ce6 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidClientRunnable.java @@ -0,0 +1,64 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; + +/** + * @author lishen + */ +public class BidClientRunnable extends AbstractClientRunnable{ + + private final BidRequest request = new BidRequest(); + + public BidClientRunnable(String protocol, String serialization, String targetIP, int targetPort, int clientNums, int rpcTimeout, + CyclicBarrier barrier, CountDownLatch latch, long startTime, + long endTime){ + super(protocol, serialization, targetIP, targetPort, clientNums, rpcTimeout, barrier, latch, startTime, endTime); + Impression imp = new Impression(); + imp.setBidFloor(1.1); + imp.setId("abc"); + List imps = new ArrayList(1); + imps.add(imp); + request.setImpressions(imps); + + Geo geo = new Geo(); + geo.setCity("beijing"); + geo.setCountry("china"); + geo.setLat(100.1f); + geo.setLon(100.1f); + + Device device = new Device(); + device.setMake("apple"); + device.setOs("ios"); + device.setVersion("7.0"); + device.setLang("zh_CN"); + device.setModel("iphone"); + device.setGeo(geo); + request.setDevice(device); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public Object invoke(ServiceFactory serviceFactory) { + EchoService echoService = (EchoService) serviceFactory.get(EchoService.class); + BidRequest result = echoService.bid(request); + return result; + } +} diff --git a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/ClientRunnable.java b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/ClientRunnable.java new file mode 100644 index 000000000000..6710ecb02727 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/ClientRunnable.java @@ -0,0 +1,20 @@ +/** + * nfs-rpc + * Apache License + * + * http://code.google.com/p/nfs-rpc (c) 2011 + */ +package com.alibaba.dubbo.rpc.benchmark; + +import java.util.List; + +/** + * client runnable,so we can collect results + * + * @author bluedavy + */ +public interface ClientRunnable extends Runnable { + + public List getResults(); + +} diff --git a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcBenchmarkClient.java b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcBenchmarkClient.java new file mode 100644 index 000000000000..5972e7577525 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcBenchmarkClient.java @@ -0,0 +1,24 @@ +package com.alibaba.dubbo.rpc.benchmark; + +import java.lang.reflect.InvocationTargetException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; + +public class RpcBenchmarkClient extends AbstractBenchmarkClient { + + @SuppressWarnings("rawtypes") + @Override + public ClientRunnable getClientRunnable(String protocol, String serialization, String targetIP, int targetPort, int clientNums, int rpcTimeout, + CyclicBarrier barrier, CountDownLatch latch, long startTime, long endTime) throws IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { + String runnable = properties.getProperty("classname"); + Class[] parameterTypes = new Class[] { String.class, String.class, String.class, int.class, int.class, int.class, CyclicBarrier.class, + CountDownLatch.class, long.class, long.class }; + Object[] parameters = new Object[] { protocol, serialization, targetIP, targetPort, clientNums, rpcTimeout, barrier, latch, startTime, + endTime }; + return (ClientRunnable) Class.forName(runnable).getConstructor(parameterTypes).newInstance(parameters); + } + + public static void main(String[] args) throws Exception { + new RpcBenchmarkClient().run(args); + } +} diff --git a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/ServiceFactory.java b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/ServiceFactory.java new file mode 100644 index 000000000000..29a497ea3288 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/ServiceFactory.java @@ -0,0 +1,118 @@ +package com.alibaba.dubbo.rpc.benchmark; + +import java.util.concurrent.ConcurrentHashMap; + +import com.alibaba.dubbo.common.utils.StringUtils; +import com.alibaba.dubbo.config.ApplicationConfig; +import com.alibaba.dubbo.config.ReferenceConfig; + +/** + * Abstract Service Factory,create custom nums Service + * + * @author tony.chenl + */ +public class ServiceFactory { + + String targetIP = null; + + int targetPort = 0; + + int connectTimeout = 0; + + int clientNums = 0; + + String protocol; + + String serialization; + + public String getTargetIP() { + return targetIP; + } + + public void setTargetIP(String targetIP) { + this.targetIP = targetIP; + } + + public int getTargetPort() { + return targetPort; + } + + public void setTargetPort(int targetPort) { + this.targetPort = targetPort; + } + + public int getConnectTimeout() { + return connectTimeout; + } + + public void setConnectTimeout(int connectTimeout) { + this.connectTimeout = connectTimeout; + } + + public int getClientNums() { + return clientNums; + } + + public void setClientNums(int clientNums) { + this.clientNums = clientNums; + } + + public String getProtocol() { + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + public String getSerialization() { + return serialization; + } + + public void setSerialization(String serialization) { + this.serialization = serialization; + } + + // Cache ExchangeClient + private static ConcurrentHashMap services = new ConcurrentHashMap(); + + @SuppressWarnings("unchecked") + public T get(final Class cls){ + String key = cls.getName(); + if (services.containsKey(key)) { + return (T) services.get(key); + + } else { + T service = createClient(cls, targetIP, targetPort, connectTimeout,clientNums, protocol, serialization); + services.put(key, service); + return (T) services.get(key); + } + } + + protected T createClient(Class cls, String targetIP, int targetPort, int connectTimeout,int clientNums, String protocol, String serialization){ + ReferenceConfig referenceConfig = new ReferenceConfig(); + referenceConfig.setInterface(cls); + StringBuilder url = new StringBuilder(); + url.append(protocol); + url.append("://"); + url.append(targetIP); + url.append(":"); + url.append(targetPort); + url.append("/"); + url.append(cls.getName()); + url.append("?optimizer=com.alibaba.dubbo.rpc.benchmark.SerializationOptimizerImpl"); + if (!StringUtils.isEmpty(serialization)) { + url.append("&serialization="); + url.append(serialization); + } + referenceConfig.setUrl(url.toString()); + // hardcode + referenceConfig.setConnections(clientNums); + ApplicationConfig application = new ApplicationConfig(); + application.setName("dubbo_consumer"); + referenceConfig.setApplication(application); + referenceConfig.setTimeout(connectTimeout); + return referenceConfig.get(); + } + +} diff --git a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/TextClientRunnable.java b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/TextClientRunnable.java new file mode 100644 index 000000000000..923e885825d1 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/TextClientRunnable.java @@ -0,0 +1,46 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +import org.apache.commons.lang.StringUtils; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; + +/** + * @author lishen + */ +public class TextClientRunnable extends AbstractClientRunnable{ + + private final Text text = new Text(StringUtils.leftPad("", 50000)); + + public TextClientRunnable(String protocol, String serialization, String targetIP, int targetPort, int clientNums, int rpcTimeout, + CyclicBarrier barrier, CountDownLatch latch, long startTime, + long endTime){ + super(protocol, serialization, targetIP, targetPort, clientNums, rpcTimeout, barrier, latch, startTime, endTime); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public Object invoke(ServiceFactory serviceFactory) { + EchoService echoService = (EchoService) serviceFactory.get(EchoService.class); + return echoService.text(text); + } +// +// public static void main(String[] args) { +// System.out.println( StringUtils.leftPad("", 1000).getBytes().length); +// } +} diff --git a/dubbo-test/dubbo-test-benchmark-client/src/main/resources/META-INF/cxf/org.apache.cxf.Logger b/dubbo-test/dubbo-test-benchmark-client/src/main/resources/META-INF/cxf/org.apache.cxf.Logger new file mode 100644 index 000000000000..be0c538174cb --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/main/resources/META-INF/cxf/org.apache.cxf.Logger @@ -0,0 +1 @@ +org.apache.cxf.common.logging.Log4jLogger \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-client/src/main/resources/dubbo.properties b/dubbo-test/dubbo-test-benchmark-client/src/main/resources/dubbo.properties new file mode 100644 index 000000000000..f28a602c6928 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/main/resources/dubbo.properties @@ -0,0 +1,30 @@ +serverip=127.0.0.1 +concurrents=10 +timeout=3000 +runtime=300 +connectionnums=10 + +classname=com.alibaba.dubbo.rpc.benchmark.BidClientRunnable +#classname=com.alibaba.dubbo.rpc.benchmark.TextClientRunnable + +protocol=rest +serverport=8888 + +#protocol=dubbo +#serverport=20880 +#serialization=kryo + +#protocol=webservice +#serverport=8892 + +#protocol=http +#serverport=8889 + +#protocol=hessian +#serverport=8890 + +#protocol=rmi +#serverport=8893 + + + diff --git a/dubbo-test/dubbo-test-benchmark-client/src/main/resources/log4j.xml b/dubbo-test/dubbo-test-benchmark-client/src/main/resources/log4j.xml new file mode 100644 index 000000000000..cd275123fd4c --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-client/src/main/resources/log4j.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-server/pom.xml b/dubbo-test/dubbo-test-benchmark-server/pom.xml new file mode 100644 index 000000000000..30eedf44fda9 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-server/pom.xml @@ -0,0 +1,195 @@ + + + 4.0.0 + + com.alibaba + dubbo-test + 2.8.0 + + dubbo-test-benchmark-server + jar + ${project.artifactId} + The benchmark test module of dubbo project + + true + + + + com.alibaba + dubbo + ${project.parent.version} + + + com.alibaba + dubbo-test-benchmark-api + ${project.parent.version} + + + org.javassist + javassist + + + org.jboss.netty + netty + + + org.apache.mina + mina-core + + + org.glassfish.grizzly + grizzly-core + + + org.apache.httpcomponents + httpclient + + + com.alibaba + fastjson + + + com.thoughtworks.xstream + xstream + + + org.apache.bsf + bsf-api + + + org.apache.zookeeper + zookeeper + + + com.github.sgroschupf + zkclient + + + org.apache.curator + curator-framework + + + com.googlecode.xmemcached + xmemcached + + + org.apache.cxf + cxf-rt-frontend-simple + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.thrift + libthrift + + + com.caucho + hessian + + + javax.servlet + servlet-api + + + org.mortbay.jetty + jetty + + + log4j + log4j + + + org.slf4j + slf4j-api + + + redis.clients + jedis + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + javax.cache + cache-api + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + + + + + src/main/resources + + **/*.* + + + + + + maven-dependency-plugin + + + unpack + package + + unpack + + + + + com.alibaba + dubbo + ${project.parent.version} + ${project.build.directory}/dubbo + META-INF/assembly/** + + + + + + + + maven-assembly-plugin + + src/assembly/assembly.xml + + + + make-assembly + package + + single + + + + + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-server/src/assembly/assembly.xml b/dubbo-test/dubbo-test-benchmark-server/src/assembly/assembly.xml new file mode 100644 index 000000000000..674a2dc869ad --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-server/src/assembly/assembly.xml @@ -0,0 +1,23 @@ + + assembly + + tar.gz + + true + + + src/cli + / + 0755 + + + src/main/resources + conf + + + + + lib + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-server/src/cli/run.bat b/dubbo-test/dubbo-test-benchmark-server/src/cli/run.bat new file mode 100644 index 000000000000..0d4c7b031f12 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-server/src/cli/run.bat @@ -0,0 +1 @@ +java -Xms1g -Xmx1g -XX:PermSize=64M -XX:+UseConcMarkSweepGC -Djava.ext.dirs=lib -classpath conf com.alibaba.dubbo.container.Main > benchmark.log \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-server/src/cli/run.sh b/dubbo-test/dubbo-test-benchmark-server/src/cli/run.sh new file mode 100644 index 000000000000..30d00abd10fb --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-server/src/cli/run.sh @@ -0,0 +1 @@ +java -Xms1g -Xmx1g -XX:PermSize=64M -XX:+UseConcMarkSweepGC -Djava.ext.dirs=./lib -classpath conf com.alibaba.dubbo.container.Main > "benchmark.log" 2>&1 \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/EchoServiceImpl.java b/dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/EchoServiceImpl.java new file mode 100644 index 000000000000..5ae5810d69b2 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/EchoServiceImpl.java @@ -0,0 +1,41 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +public class EchoServiceImpl implements EchoService { + +// private final BidResponse response = new BidResponse(); + + public EchoServiceImpl() { +// response.setId("abc"); +// +// SeatBid seatBid = new SeatBid(); +// seatBid.setGroup("group"); +// seatBid.setSeat("seat"); +// List seatBids = new ArrayList(1); +// seatBids.add(seatBid); +// +// response.setSeatBids(seatBids); + } + + public BidRequest bid(BidRequest request) { + return request; + } + + public Text text(Text text) { + return text; + } +} \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/Main.java b/dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/Main.java new file mode 100644 index 000000000000..786d1b067b0b --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/Main.java @@ -0,0 +1,24 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.benchmark; + +public class Main { + + public static void main(String[] args) { + com.alibaba.dubbo.container.Main.main(args); + } + +} \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-server/src/main/resources/META-INF/cxf/org.apache.cxf.Logger b/dubbo-test/dubbo-test-benchmark-server/src/main/resources/META-INF/cxf/org.apache.cxf.Logger new file mode 100644 index 000000000000..be0c538174cb --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-server/src/main/resources/META-INF/cxf/org.apache.cxf.Logger @@ -0,0 +1 @@ +org.apache.cxf.common.logging.Log4jLogger \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-server/src/main/resources/META-INF/spring/dubbo-provider.xml b/dubbo-test/dubbo-test-benchmark-server/src/main/resources/META-INF/spring/dubbo-provider.xml new file mode 100644 index 000000000000..ada9b4d5cd3f --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-server/src/main/resources/META-INF/spring/dubbo-provider.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-server/src/main/resources/log4j.xml b/dubbo-test/dubbo-test-benchmark-server/src/main/resources/log4j.xml new file mode 100644 index 000000000000..cd275123fd4c --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-server/src/main/resources/log4j.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-server/src/main/webapp/WEB-INF/web.xml b/dubbo-test/dubbo-test-benchmark-server/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000000..2a2f3a6cead4 --- /dev/null +++ b/dubbo-test/dubbo-test-benchmark-server/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,30 @@ + + + + + + contextConfigLocation + /WEB-INF/classes/META-INF/spring/dubbo-provider.xml + + + + + com.alibaba.dubbo.remoting.http.servlet.BootstrapListener + + + + org.springframework.web.context.ContextLoaderListener + + + + dispatcher + com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet + 1 + + + + dispatcher + /* + + \ No newline at end of file From 7d35dc3c2711a001288ccf4cc8a214882e5ef39c Mon Sep 17 00:00:00 2001 From: Li Shen Date: Mon, 20 Oct 2014 10:12:54 +0800 Subject: [PATCH 107/200] initial check-in for RESTful remoting, Kryo/FST serialization, Spring, ZkClient upgrade, etc --- README | 201 +++++---------------------------------------------------- 1 file changed, 17 insertions(+), 184 deletions(-) diff --git a/README b/README index 2f9152b04d28..cfd2895ad339 100644 --- a/README +++ b/README @@ -1,200 +1,33 @@ -鐢变簬寮婧愮珯鐐瑰洜涓哄畨鍏ㄩ棶棰樿涓嬫帀锛屽鏋滅紪璇戞椂鍑虹幇鎵句笉鍒皁pensesame渚濊禆鎯呭喌鐨勶紝璇峰厛鎵嬪姩涓嬭浇https://github.com/alibaba/opensesame -鏈湴install锛岃繖鍑犲ぉ鎴戜滑浼氭妸opensesame鍙戝埌mavan涓ぎ浠撳簱銆 +Dubbox now means Dubbo eXtensions. If you know java, javax and dubbo, you know what dubbox is :) + +Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the popular [dubbo service framework](http://github.com/alibaba/dubbo). It鈥檚 now internally used by several projects of [dangdang.com](http://www.dangdang.com), which is one of the major e-commerce companies in China. -涓存椂鏂囨。鍦板潃锛歨ttp://alibaba.github.io/dubbo-doc-static/Developer+Guide-zh.htm +Contacts: shenli@dangdang.com, wangyuxuan@dangdang.com -================================================================ +### Dubbox褰撳墠鐨勪富瑕佸姛鑳斤細 -Dubbo is a distributed service framework enpowers applications with service import/export capability with high performance RPC. +* **REST椋庢牸杩滅▼璋冪敤鏀寔 锛圚TTP + JSON/XML)**锛氬湪dubbo涓敮鎸佸熀浜嶩TTP + JSON/XML鐨勮繙绋嬭皟鐢紝浠ユ樉钁楃畝鍖栦紒涓氬唴閮ㄨ法璇█璋冪敤锛屽悓鏃舵樉钁楃畝鍖栧澶朞pen API銆佹棤绾緼PI鐢氳嚦娴忚鍣ˋJAX搴旂敤绛夌殑寮鍙戙 -It's composed of three kernel parts: +* **鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡紑婧愮殑kryo鍜宖st锛坒ast serialization锛夊簭鍒楀寲搴擄紝涓篸ubbo鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜嗚繙绋嬭皟鐢ㄦц兘銆 -Remoting: a network communication framework provides sync-over-async and request-response messaging. +* **鍩轰簬宓屽叆寮廡omcat鐨凥TTP浣撶郴锛圱o be pushed锛**锛氬熀浜庡祵鍏ュ紡tomcat瀹炵幇dubbo http浣撶郴锛堝嵆dubbo-remoting-http锛夛紝鐢ㄤ互閫愭鍙栦唬鏃х殑宓屽叆寮廽etty锛屽彲浠ユ樉钁楃殑鎻愰珮REST绛夎皟鐢ㄧ殑鎬ц兘锛屽苟灏唖ervlet API鐨勬敮鎸佷粠2.5鍗囩骇鍒3.1銆傦紙娉細闄や簡REST锛宒ubbo涓殑WebServices銆丠essian銆丠TTP Invoker绛夊崗璁兘鍩轰簬姝ttp浣撶郴锛夈 -Clustering: a remote procedure call abstraction with load-balancing/failover/clustering capabilities. +* **Spring鐨勫崌绾**锛氬皢dubbo涓璼pring鐢2.x鍗囩骇鍒扮洰鍓嶆渶甯哥敤鐨3.x鐗堟湰锛屽噺灏戠増鏈啿绐佸甫鏉ョ殑楹荤儲 -Registry: a service directory framework for service registration and service event publish/subscription +* **ZooKeeper瀹㈡埛绔殑鍗囩骇**锛氬皢dubbo涓殑zookeeper瀹㈡埛绔崌绾у埌鏈鏂扮殑鐗堟湰锛屼互淇鑰佺増鏈腑鍖呭惈鐨刡ug銆 -For more, please refer to: +* **Demo搴旂敤**锛氭殏鏃跺皢dubbo鐨刣emo搴旂敤璋冩暣骞舵敼鍐欎互涓昏婕旂ずREST鍔熻兘鍜屾柊鐨凧ava楂樻晥搴忓垪鍖栫瓑绛夈 - http://code.alibabatech.com/wiki/display/dubbo +* **淇浜嗗湪JDK1.7涓奷ubbo鐨勯儴鍒哹ug**锛氫慨姝d簡姣斿dubbo鍗忚涓璲son搴忓垪鍖栫殑闂銆備絾鏄繕娌℃湁淇鎵鏈夊彂鐜扮殑bug銆 -================================================================ -Quick Start -================================================================ +**娉細dubbox鍜宒ubbo 2.x鏄吋瀹圭殑锛屾病鏈夋敼鍙榙ubbo鐨勪换浣曞凡鏈夌殑鍔熻兘鍜岄厤缃柟寮忥紙闄や簡鍗囩骇浜唖pring涔嬬被鐨勭増鏈級** -Export remote service: +### Dubbox鏂囨。 - - - +[鍦―ubbo涓紑鍙慠EST椋庢牸鐨勮繙绋嬭皟鐢紙RESTful Remoting锛塢(http://dangdangdotcom.github.io/dubbox/rest.html) -Refer remote service: +[鍦―ubbo涓娇鐢ㄩ珮鏁堢殑Java搴忓垪鍖栵紙Kryo鍜孎ST锛塢(http://dangdangdotcom.github.io/dubbox/serialization.html) - - - - - +[Demo搴旂敤绠鍗曡繍琛屾寚鍗梋(http://dangdangdotcom.github.io/dubbox/demo.html) -================================================================ -Source Building -================================================================ - -0. Install the git and maven command line: - - yum install git - or: apt-get install git - - cd ~ - wget http://www.apache.org/dist//maven/binaries/apache-maven-2.2.1-bin.tar.gz - tar zxvf apache-maven-2.2.1-bin.tar.gz - vi .bash_profile - - edit: export PATH=$PATH:~/apache-maven-2.2.1/bin - source .bash_profile - -1. Checkout the dubbo source code: - - cd ~ - git clone https://github.com/alibaba/dubbo.git dubbo - - git checkout -b dubbo-2.4.0 - git checkout master - -2. Import the dubbo source code to eclipse project: - - cd ~/dubbo - mvn eclipse:eclipse - Eclipse -> Menu -> File -> Import -> Exsiting Projects to Workspace -> Browse -> Finish - - Context Menu -> Run As -> Java Application: - dubbo-demo-provider/src/test/java/com.alibaba.dubbo.demo.provider.DemoProvider - dubbo-demo-consumer/src/test/java/com.alibaba.dubbo.demo.consumer.DemoConsumer - dubbo-monitor-simple/src/test/java/com.alibaba.dubbo.monitor.simple.SimpleMonitor - dubbo-registry-simple/src/test/java/com.alibaba.dubbo.registry.simple.SimpleRegistry - - Edit Config: - dubbo-demo-provider/src/test/resources/dubbo.properties - dubbo-demo-consumer/src/test/resources/dubbo.properties - dubbo-monitor-simple/src/test/resources/dubbo.properties - dubbo-registry-simple/src/test/resources/dubbo.properties - -3. Build the dubbo binary package: - - cd ~/dubbo - mvn clean install -Dmaven.test.skip - cd dubbo/target - ls - -4. Install the demo provider: - - cd ~/dubbo/dubbo-demo-provider/target - tar zxvf dubbo-demo-provider-2.4.0-assembly.tar.gz - cd dubbo-demo-provider-2.4.0/bin - ./start.sh - -5. Install the demo consumer: - - cd ~/dubbo/dubbo-demo-consumer/target - tar zxvf dubbo-demo-consumer-2.4.0-assembly.tar.gz - cd dubbo-demo-consumer-2.4.0/bin - ./start.sh - cd ../logs - tail -f stdout.log - -6. Install the simple monitor: - - cd ~/dubbo/dubbo-simple-monitor/target - tar zxvf dubbo-simple-monitor-2.4.0-assembly.tar.gz - cd dubbo-simple-monitor-2.4.0/bin - ./start.sh - http://127.0.0.1:8080 - -7. Install the simple registry: - - cd ~/dubbo/dubbo-simple-registry/target - tar zxvf dubbo-simple-registry-2.4.0-assembly.tar.gz - cd dubbo-simple-registry-2.4.0/bin - ./start.sh - - cd ~/dubbo/dubbo-demo-provider/conf - vi dubbo.properties - - edit: dubbo.registry.adddress=dubbo://127.0.0.1:9090 - cd ../bin - ./restart.sh - - cd ~/dubbo/dubbo-demo-consumer/conf - vi dubbo.properties - - edit: dubbo.registry.adddress=dubbo://127.0.0.1:9090 - cd ../bin - ./restart.sh - - cd ~/dubbo/dubbo-simple-monitor/conf - vi dubbo.properties - - edit: dubbo.registry.adddress=dubbo://127.0.0.1:9090 - cd ../bin - ./restart.sh - -8. Install the zookeeper registry: - - cd ~ - wget http://www.apache.org/dist//zookeeper/zookeeper-3.3.3/zookeeper-3.3.3.tar.gz - tar zxvf zookeeper-3.3.3.tar.gz - cd zookeeper-3.3.3/conf - cp zoo_sample.cfg zoo.cfg - vi zoo.cfg - - edit: dataDir=/home/xxx/data - cd ../bin - ./zkServer.sh start - - cd ~/dubbo/dubbo-demo-provider/conf - vi dubbo.properties - - edit: dubbo.registry.adddress=zookeeper://127.0.0.1:2181 - cd ../bin - ./restart.sh - - cd ~/dubbo/dubbo-demo-consumer/conf - vi dubbo.properties - - edit: dubbo.registry.adddress=zookeeper://127.0.0.1:2181 - cd ../bin - ./restart.sh - - cd ~/dubbo/dubbo-simple-monitor/conf - vi dubbo.properties - - edit: dubbo.registry.adddress=zookeeper://127.0.0.1:2181 - cd ../bin - ./restart.sh - -9. Install the redis registry: - - cd ~ - wget http://redis.googlecode.com/files/redis-2.4.8.tar.gz - tar xzf redis-2.4.8.tar.gz - cd redis-2.4.8 - make - nohup ./src/redis-server redis.conf & - - cd ~/dubbo/dubbo-demo-provider/conf - vi dubbo.properties - - edit: dubbo.registry.adddress=redis://127.0.0.1:6379 - cd ../bin - ./restart.sh - - cd ~/dubbo/dubbo-demo-consumer/conf - vi dubbo.properties - - edit: dubbo.registry.adddress=redis://127.0.0.1:6379 - cd ../bin - ./restart.sh - - cd ~/dubbo/dubbo-simple-monitor/conf - vi dubbo.properties - - edit: dubbo.registry.adddress=redis://127.0.0.1:6379 - cd ../bin - ./restart.sh - -10. Install the admin console: - - cd ~/dubbo/dubbo-admin - mvn jetty:run -Ddubbo.registry.address=zookeeper://127.0.0.1:2181 - http://root:root@127.0.0.1:8080 From a859af18162ac3041326116274b14b7c05d7e849 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Mon, 20 Oct 2014 10:15:14 +0800 Subject: [PATCH 108/200] initial check-in for RESTful remoting, Kryo/FST serialization, Spring, ZkClient upgrade, etc --- README => README.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename README => README.md (100%) diff --git a/README b/README.md similarity index 100% rename from README rename to README.md From 64280431b44fc0d8d3c080874ac9c5326fa02a9b Mon Sep 17 00:00:00 2001 From: Li Shen Date: Mon, 20 Oct 2014 11:05:44 +0800 Subject: [PATCH 109/200] remove old files --- .../src/test/resources/dubbo.properties | 25 ------------ .../src/main/assembly/assembly.xml | 39 ------------------- .../src/main/assembly/conf/dubbo.properties | 28 ------------- .../dubbo/demo/provider/DemoServiceImpl.java | 31 --------------- .../src/test/resources/dubbo.properties | 28 ------------- .../src/test/resources/log4j.xml | 28 ------------- 6 files changed, 179 deletions(-) delete mode 100644 dubbo-demo/dubbo-demo-consumer/src/test/resources/dubbo.properties delete mode 100644 dubbo-demo/dubbo-demo-provider/src/main/assembly/assembly.xml delete mode 100644 dubbo-demo/dubbo-demo-provider/src/main/assembly/conf/dubbo.properties delete mode 100644 dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/provider/DemoServiceImpl.java delete mode 100644 dubbo-demo/dubbo-demo-provider/src/test/resources/dubbo.properties delete mode 100644 dubbo-demo/dubbo-demo-provider/src/test/resources/log4j.xml diff --git a/dubbo-demo/dubbo-demo-consumer/src/test/resources/dubbo.properties b/dubbo-demo/dubbo-demo-consumer/src/test/resources/dubbo.properties deleted file mode 100644 index 32723f9c1b30..000000000000 --- a/dubbo-demo/dubbo-demo-consumer/src/test/resources/dubbo.properties +++ /dev/null @@ -1,25 +0,0 @@ -## -# Copyright 1999-2011 Alibaba Group. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -## -dubbo.container=log4j,spring -dubbo.application.name=demo-consumer -dubbo.application.owner= -dubbo.registry.address=multicast://224.5.6.7:1234 -#dubbo.registry.address=zookeeper://127.0.0.1:2181 -#dubbo.registry.address=redis://127.0.0.1:6379 -#dubbo.registry.address=dubbo://127.0.0.1:9090 -#dubbo.monitor.protocol=registry -#dubbo.log4j.file=logs/dubbo-demo-consumer.log -#dubbo.log4j.level=WARN \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/assembly/assembly.xml b/dubbo-demo/dubbo-demo-provider/src/main/assembly/assembly.xml deleted file mode 100644 index 25235d9064e2..000000000000 --- a/dubbo-demo/dubbo-demo-provider/src/main/assembly/assembly.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - assembly - - tar.gz - - true - - - ${project.build.directory}/dubbo/META-INF/assembly/bin - bin - 0755 - - - src/main/assembly/conf - conf - 0644 - - - - - lib - - - \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/assembly/conf/dubbo.properties b/dubbo-demo/dubbo-demo-provider/src/main/assembly/conf/dubbo.properties deleted file mode 100644 index 728be32db500..000000000000 --- a/dubbo-demo/dubbo-demo-provider/src/main/assembly/conf/dubbo.properties +++ /dev/null @@ -1,28 +0,0 @@ -## -# Copyright 1999-2011 Alibaba Group. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -## -dubbo.container=log4j,spring -dubbo.application.name=demo-provider -dubbo.application.owner= -dubbo.registry.address=multicast://224.5.6.7:1234 -#dubbo.registry.address=zookeeper://127.0.0.1:2181 -#dubbo.registry.address=redis://127.0.0.1:6379 -#dubbo.registry.address=dubbo://127.0.0.1:9090 -dubbo.monitor.protocol=registry -dubbo.protocol.name=dubbo -dubbo.protocol.port=20880 -dubbo.service.loadbalance=roundrobin -dubbo.log4j.file=logs/dubbo-demo-provider.log -dubbo.log4j.level=WARN \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/provider/DemoServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/provider/DemoServiceImpl.java deleted file mode 100644 index 346ab601fb0f..000000000000 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/provider/DemoServiceImpl.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.demo.provider; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.alibaba.dubbo.demo.DemoService; -import com.alibaba.dubbo.rpc.RpcContext; - -public class DemoServiceImpl implements DemoService { - - public String sayHello(String name) { - System.out.println("[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); - return "Hello " + name + ", response form provider: " + RpcContext.getContext().getLocalAddress(); - } - -} \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/test/resources/dubbo.properties b/dubbo-demo/dubbo-demo-provider/src/test/resources/dubbo.properties deleted file mode 100644 index 600d6089adc1..000000000000 --- a/dubbo-demo/dubbo-demo-provider/src/test/resources/dubbo.properties +++ /dev/null @@ -1,28 +0,0 @@ -## -# Copyright 1999-2011 Alibaba Group. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -## -dubbo.container=log4j,spring -dubbo.application.name=demo-provider -dubbo.application.owner=william -dubbo.registry.address=multicast://224.5.6.7:1234 -#dubbo.registry.address=zookeeper://127.0.0.1:2181 -#dubbo.registry.address=redis://127.0.0.1:6379 -#dubbo.registry.address=dubbo://127.0.0.1:9090 -#dubbo.monitor.protocol=registry -dubbo.protocol.name=dubbo -dubbo.protocol.port=20880 -dubbo.service.loadbalance=roundrobin -#dubbo.log4j.file=logs/dubbo-demo-consumer.log -#dubbo.log4j.level=WARN \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/test/resources/log4j.xml b/dubbo-demo/dubbo-demo-provider/src/test/resources/log4j.xml deleted file mode 100644 index 7d7163464096..000000000000 --- a/dubbo-demo/dubbo-demo-provider/src/test/resources/log4j.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file From 6e336376085e12ccad691385f7bf4ab994874398 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Mon, 20 Oct 2014 11:36:56 +0800 Subject: [PATCH 110/200] initial check-in for RESTful remoting, Kryo/FST serialization, Spring/ZkClient upgrade, etc --- README.md | 2 +- dubbo-admin/pom.xml | 4 +- dubbo-cluster/pom.xml | 2 +- dubbo-common/pom.xml | 2 +- dubbo-config/dubbo-config-api/pom.xml | 2 +- .../alibaba/dubbo/config/ProtocolConfig.java | 10 +- dubbo-config/dubbo-config-spring/pom.xml | 2 +- dubbo-config/pom.xml | 2 +- dubbo-container/dubbo-container-api/pom.xml | 12 +- dubbo-container/dubbo-container-jetty/pom.xml | 2 +- dubbo-container/dubbo-container-log4j/pom.xml | 2 +- .../dubbo-container-logback/pom.xml | 2 +- .../dubbo-container-spring/pom.xml | 2 +- dubbo-container/pom.xml | 2 +- dubbo-demo/dubbo-demo-api/pom.xml | 4 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 4 +- dubbo-demo/dubbo-demo-provider/pom.xml | 10 +- dubbo-demo/pom.xml | 2 +- dubbo-filter/dubbo-filter-cache/pom.xml | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 2 +- dubbo-filter/pom.xml | 2 +- dubbo-maven/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +- dubbo-monitor/pom.xml | 2 +- dubbo-registry/dubbo-registry-api/pom.xml | 2 +- dubbo-registry/dubbo-registry-default/pom.xml | 2 +- .../dubbo-registry-multicast/pom.xml | 2 +- dubbo-registry/dubbo-registry-redis/pom.xml | 2 +- .../dubbo-registry-zookeeper/pom.xml | 2 +- dubbo-registry/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 18 +- .../http/tomcat/TomcatHttpBinder.java | 32 + .../http/tomcat/TomcatHttpServer.java | 91 + ...com.alibaba.dubbo.remoting.http.HttpBinder | 3 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-p2p/pom.xml | 2 +- .../dubbo-remoting-zookeeper/pom.xml | 2 +- dubbo-remoting/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-default/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rest/pom.xml | 37 +- .../src/main/java/Acme/Serve/Serve.java | 5549 ----------------- .../rpc/protocol/rest/DubboHttpServer.java | 3 +- .../dubbo/rpc/protocol/rest/RestProtocol.java | 94 + .../rpc/protocol/rest/RestServerFactory.java | 6 +- .../rpc/protocol/rest/RpcContextFilter.java | 3 + .../dubbo/rpc/protocol/rest/TjwsServer.java | 18 +- .../rpc/protocol/rest/UndertowServer.java | 75 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 2 +- dubbo-rpc/pom.xml | 2 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 4 +- dubbo-simple/dubbo-registry-simple/pom.xml | 2 +- dubbo-simple/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark-api/pom.xml | 4 +- .../dubbo-test-benchmark-client/pom.xml | 4 +- .../dubbo-test-benchmark-server/pom.xml | 4 +- dubbo-test/dubbo-test-benchmark/pom.xml | 2 +- dubbo-test/dubbo-test-compatibility/pom.xml | 2 +- dubbo-test/dubbo-test-examples/pom.xml | 2 +- dubbo-test/dubbo-test-integration/pom.xml | 2 +- dubbo-test/pom.xml | 2 +- dubbo/pom.xml | 2 +- hessian-lite/pom.xml | 2 +- pom.xml | 31 +- 75 files changed, 445 insertions(+), 5679 deletions(-) create mode 100755 dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpBinder.java create mode 100755 dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java delete mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/Acme/Serve/Serve.java diff --git a/README.md b/README.md index cfd2895ad339..3904bf5e92c5 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Contacts: shenli@dangdang.com, wangyuxuan@dangdang.com * **鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡紑婧愮殑kryo鍜宖st锛坒ast serialization锛夊簭鍒楀寲搴擄紝涓篸ubbo鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜嗚繙绋嬭皟鐢ㄦц兘銆 -* **鍩轰簬宓屽叆寮廡omcat鐨凥TTP浣撶郴锛圱o be pushed锛**锛氬熀浜庡祵鍏ュ紡tomcat瀹炵幇dubbo http浣撶郴锛堝嵆dubbo-remoting-http锛夛紝鐢ㄤ互閫愭鍙栦唬鏃х殑宓屽叆寮廽etty锛屽彲浠ユ樉钁楃殑鎻愰珮REST绛夎皟鐢ㄧ殑鎬ц兘锛屽苟灏唖ervlet API鐨勬敮鎸佷粠2.5鍗囩骇鍒3.1銆傦紙娉細闄や簡REST锛宒ubbo涓殑WebServices銆丠essian銆丠TTP Invoker绛夊崗璁兘鍩轰簬姝ttp浣撶郴锛夈 +* **鍩轰簬宓屽叆寮廡omcat鐨凥TTP浣撶郴**锛氬熀浜庡祵鍏ュ紡tomcat瀹炵幇dubbo http浣撶郴锛堝嵆dubbo-remoting-http锛夛紝鐢ㄤ互閫愭鍙栦唬鏃х殑宓屽叆寮廽etty锛屽彲浠ユ樉钁楃殑鎻愰珮REST绛夎皟鐢ㄧ殑鎬ц兘锛屽苟灏唖ervlet API鐨勬敮鎸佷粠2.5鍗囩骇鍒3.1銆傦紙娉細闄や簡REST锛宒ubbo涓殑WebServices銆丠essian銆丠TTP Invoker绛夊崗璁兘鍩轰簬姝ttp浣撶郴锛夈 * **Spring鐨勫崌绾**锛氬皢dubbo涓璼pring鐢2.x鍗囩骇鍒扮洰鍓嶆渶甯哥敤鐨3.x鐗堟湰锛屽噺灏戠増鏈啿绐佸甫鏉ョ殑楹荤儲 diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index 85a271ced58d..aceee9864be4 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-admin war @@ -99,7 +99,7 @@ javax.servlet - servlet-api + javax.servlet-api provided diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index ae5cb68f1263..3edde87c4fdb 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-cluster jar diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index 9189c0c77307..039b2a053a23 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-common jar diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 06cfd4be0631..597f2341dc9a 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.8.0 + 2.8.1 dubbo-config-api jar diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java index 26c3e22adb08..8e592bd9739a 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ProtocolConfig.java @@ -126,7 +126,7 @@ public class ProtocolConfig extends AbstractConfig { // TODO add this to provider config private String optimizer; - private String interceptor; + private String extension; // 鍙傛暟 private Map parameters; @@ -445,12 +445,12 @@ public void setOptimizer(String optimizer) { this.optimizer = optimizer; } - public String getInterceptor() { - return interceptor; + public String getExtension() { + return extension; } - public void setInterceptor(String interceptor) { - this.interceptor = interceptor; + public void setExtension(String extension) { + this.extension = extension; } public void destory() { diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index a0ed8aa251f7..3183a22cbf1d 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.8.0 + 2.8.1 dubbo-config-spring jar diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index ee05f2f2a41f..6a31488a7921 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index df12441401f5..c237c424cfec 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.0 + 2.8.1 dubbo-container-api jar @@ -37,7 +37,17 @@ org.mortbay.jetty jetty + + + org.mortbay.jetty + servlet-api + + + + javax.servlet + javax.servlet-api + diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index 197043c8b216..b550162c3bf2 100644 --- a/dubbo-container/dubbo-container-jetty/pom.xml +++ b/dubbo-container/dubbo-container-jetty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.0 + 2.8.1 dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index b43cc72bb2a2..958983820aab 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.0 + 2.8.1 dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index 013ffe08e337..deea9f2a23a7 100644 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ b/dubbo-container/dubbo-container-logback/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.0 + 2.8.1 dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index e87dda5a01a2..bf1f7d84b3a7 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.0 + 2.8.1 dubbo-container-spring jar diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index ac95c0a1efda..2b6dcfee279e 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-container pom diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index b6561e5a6c0b..bcc64dfe62c1 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.0 + 2.8.1 dubbo-demo-api jar @@ -41,7 +41,7 @@ javax.servlet - servlet-api + javax.servlet-api \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml index 21319fa4e344..446e83944485 100644 --- a/dubbo-demo/dubbo-demo-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.0 + 2.8.1 dubbo-demo-consumer jar @@ -105,7 +105,7 @@ javax.servlet - servlet-api + javax.servlet-api org.mortbay.jetty diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml index 9a74589aa796..74073b07e0c1 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.0 + 2.8.1 dubbo-demo-provider war @@ -105,11 +105,17 @@ javax.servlet - servlet-api + javax.servlet-api org.mortbay.jetty jetty + + + org.mortbay.jetty + servlet-api + + log4j diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index cb6a89d08cb0..50a282bb1ce0 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-demo pom diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 972ec28d5990..529269934995 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.8.0 + 2.8.1 dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index 502a38d8ead4..e1d82950a214 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.8.0 + 2.8.1 dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index f943e4b7b9b0..d3c3e9651fa1 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-filter pom diff --git a/dubbo-maven/pom.xml b/dubbo-maven/pom.xml index 3df8cb6e8f8e..bdc00ad29a59 100644 --- a/dubbo-maven/pom.xml +++ b/dubbo-maven/pom.xml @@ -143,7 +143,7 @@ javax.servlet - servlet-api + javax.servlet-api 2.5 provided diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index e251779d84ff..55ee12cbda7d 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.8.0 + 2.8.1 dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index 2f3a96937208..83b2d02803aa 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.8.0 + 2.8.1 dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index 522dbd72981a..c865c9af5482 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 8bccba3b8a7b..8851097487d7 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.0 + 2.8.1 dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index d7b902b861f9..7a39f9539d09 100644 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ b/dubbo-registry/dubbo-registry-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.0 + 2.8.1 dubbo-registry-default jar diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index 149035f3cb2d..0708d4bd2305 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.0 + 2.8.1 dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index 5ecb5b09aecd..e1ba73b1ce6f 100644 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ b/dubbo-registry/dubbo-registry-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.0 + 2.8.1 dubbo-registry-redis jar diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index 2addc8a06c19..2492aeb85a71 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.0 + 2.8.1 dubbo-registry-zookeeper jar diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index f6a4131b25be..85df9750224a 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-registry pom diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index 2b88e58ad3b9..f5c8bc682a3a 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.0 + 2.8.1 dubbo-remoting-api jar diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml index 5214cff542b0..0cb92809f65a 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml +++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.0 + 2.8.1 dubbo-remoting-grizzly jar diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index fd530280e519..194a21336e3b 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.0 + 2.8.1 dubbo-remoting-http jar @@ -37,6 +37,22 @@ org.mortbay.jetty jetty + + + org.mortbay.jetty + servlet-api + + + + org.apache.tomcat.embed + tomcat-embed-core + 8.0.11 + + + org.apache.tomcat.embed + tomcat-embed-logging-juli + 8.0.11 + \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpBinder.java new file mode 100755 index 000000000000..fd6a05eb36ca --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpBinder.java @@ -0,0 +1,32 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.http.tomcat; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.http.HttpBinder; +import com.alibaba.dubbo.remoting.http.HttpHandler; +import com.alibaba.dubbo.remoting.http.HttpServer; + +/** + * @author lishen + */ +public class TomcatHttpBinder implements HttpBinder { + + public HttpServer bind(URL url, HttpHandler handler) { + return new TomcatHttpServer(url, handler); + } + +} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java new file mode 100755 index 000000000000..01bb1b80bea4 --- /dev/null +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java @@ -0,0 +1,91 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.remoting.http.tomcat; + + +import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.remoting.http.HttpHandler; +import com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet; +import com.alibaba.dubbo.remoting.http.servlet.ServletManager; +import com.alibaba.dubbo.remoting.http.support.AbstractHttpServer; +import org.apache.catalina.Context; +import org.apache.catalina.LifecycleException; +import org.apache.catalina.startup.Tomcat; + +import java.io.File; + + +/** + * @author lishen + */ +public class TomcatHttpServer extends AbstractHttpServer { + + private static final Logger logger = LoggerFactory.getLogger(TomcatHttpServer.class); + + private final Tomcat tomcat; + + private final URL url; + + public TomcatHttpServer(URL url, final HttpHandler handler) { + super(url, handler); + + this.url = url; + DispatcherServlet.addHttpHandler(url.getPort(), handler); + tomcat = new Tomcat(); + tomcat.setPort(url.getPort()); + tomcat.getConnector().setProperty( + "maxThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS))); +// tomcat.getConnector().setProperty( +// "minSpareThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS))); + + tomcat.getConnector().setProperty( + "maxConnections", String.valueOf(url.getParameter(Constants.ACCEPTS_KEY, -1))); + + tomcat.getConnector().setProperty("URIEncoding", "UTF-8"); + tomcat.getConnector().setProperty("connectionTimeout", "60000"); + + tomcat.getConnector().setProperty("maxKeepAliveRequests", "-1"); + tomcat.getConnector().setProtocol("org.apache.coyote.http11.Http11NioProtocol"); + + + File baseDir = new File(System.getProperty("java.io.tmpdir")); + Context context = tomcat.addContext("/", baseDir.getAbsolutePath()); + Tomcat.addServlet(context, "dispatcher", new DispatcherServlet()); + context.addServletMapping("/*", "dispatcher"); + ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext()); + + try { + tomcat.start(); + } catch (LifecycleException e) { + throw new IllegalStateException("Failed to start tomcat server at " + url.getAddress(), e); + } + } + + public void close() { + super.close(); + + ServletManager.getInstance().removeServletContext(url.getPort()); + + try { + tomcat.stop(); + } catch (Exception e) { + logger.warn(e.getMessage(), e); + } + } +} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.http.HttpBinder b/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.http.HttpBinder index b1be1077e582..a241d7d5637f 100644 --- a/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.http.HttpBinder +++ b/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.http.HttpBinder @@ -1,2 +1,3 @@ servlet=com.alibaba.dubbo.remoting.http.servlet.ServletHttpBinder -jetty=com.alibaba.dubbo.remoting.http.jetty.JettyHttpBinder \ No newline at end of file +jetty=com.alibaba.dubbo.remoting.http.jetty.JettyHttpBinder +tomcat=com.alibaba.dubbo.remoting.http.tomcat.TomcatHttpBinder \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml index 832576b3b37e..4594bb3c2985 100644 --- a/dubbo-remoting/dubbo-remoting-mina/pom.xml +++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.0 + 2.8.1 dubbo-remoting-mina jar diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index 26b6caa7e24c..21c4facd2923 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.0 + 2.8.1 dubbo-remoting-netty jar diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml index 83d9289be859..0f7be3eca20b 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml +++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.0 + 2.8.1 dubbo-remoting-p2p jar diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index c975d09871fc..0f6cbc8b85bb 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.0 + 2.8.1 dubbo-remoting-zookeeper jar diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 4a7aeb87b821..8742605b9619 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -18,7 +18,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-remoting pom diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index ab6d33f156c9..439502aae176 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.0 + 2.8.1 dubbo-rpc-api jar diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index 3f30f76d8705..2b1801751b77 100644 --- a/dubbo-rpc/dubbo-rpc-default/pom.xml +++ b/dubbo-rpc/dubbo-rpc-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.0 + 2.8.1 dubbo-rpc-default jar diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index 599f89df667d..8b79311a1883 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.0 + 2.8.1 dubbo-rpc-hessian jar diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index bea05ed129fe..8dd468a54d11 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.0 + 2.8.1 dubbo-rpc-http jar diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index 0d662ec3545d..c6180d7c5663 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml +++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.0 + 2.8.1 dubbo-rpc-injvm jar diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml index 1659017b55a3..24c2c47249ed 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml +++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.0 + 2.8.1 dubbo-rpc-memcached jar diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml index 789e7e71d15a..134fb9d65019 100644 --- a/dubbo-rpc/dubbo-rpc-redis/pom.xml +++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.0 + 2.8.1 dubbo-rpc-redis jar diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml index 336705306864..4a4c724c3b48 100644 --- a/dubbo-rpc/dubbo-rpc-rest/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml @@ -1,10 +1,25 @@ + 4.0.0 com.alibaba dubbo-rpc - 2.8.0 + 2.8.1 dubbo-rpc-rest jar @@ -93,17 +108,27 @@ 3.0.7.Final - - org.jboss.resteasy - tjws - 3.0.7.Final - + + + + + org.jboss.resteasy resteasy-undertow 3.0.7.Final + + io.undertow + undertow-servlet + 1.0.1.Final + + + io.undertow + undertow-core + 1.0.1.Final + org.jboss.resteasy diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/Acme/Serve/Serve.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/Acme/Serve/Serve.java deleted file mode 100644 index a8930469556c..000000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/Acme/Serve/Serve.java +++ /dev/null @@ -1,5549 +0,0 @@ -// Serve - minimal Java servlet container class -// -// Copyright (C)1996,1998 by Jef Poskanzer . All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -// OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -// SUCH DAMAGE. -// -// Visit the ACME Labs Java page for up-to-date versions of this and other -// fine Java utilities: http://www.acme.com/java/ -// - -// All enhancements Copyright (C)1998-2010 by Dmitriy Rogatkin -// This version is compatible with JSDK 2.5 -// http://tjws.sourceforge.net -// $Id: Serve.java,v 1.194 2009/12/31 05:02:13 dmitriy Exp $ - -package Acme.Serve; - -import Acme.Utils; - -import javax.servlet.*; -import javax.servlet.http.*; -import java.io.*; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.InetAddress; -import java.net.MalformedURLException; -import java.net.Socket; -import java.net.URL; -import java.security.SecureRandom; -import java.text.MessageFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -// TODO Added this class for now since looks like there's a bug in resteasy... - -/// Minimal Java servlet container class. -//

-// This class implements a very small embeddable servlet container. -// It runs Servlets compatible with the API used by Sun's -// Java System Application server. -// Servlet API can be found here. -// It comes with default Servlets which provide the usual -// httpd services, returning files and directory listings. -//

-// This is not in any sense a competitor for Java System Application server. -// Java System Application server is a full-fledged HTTP server and more. -// Acme.Serve is tiny, about 5000 lines, and provides only the -// functionality necessary to deliver an Applet's .class files -// and then start up a Servlet talking to the Applet. -// They are both written in Java, they are both web servers, and -// they both implement the Servlet API; other than that they couldn't -// be more different. -//

-// This is actually the second HTTP server I've written. -// The other one is called -// thttpd, -// it's written in C, and is also pretty small although much more -// featureful than this. -//

-// Other Java HTTP servers: -//

-//

-// A June 1997 BYTE -// magazine article mentioning this server.
-// A December 1997 BYTE -// magazine article giving it an Editor's Choice Award of Distinction.
-// Fetch the -// software.
-// Fetch the entire Acme package. -//

-// @see Acme.Serve.servlet.http.HttpServlet -// @see FileServlet -// @see CgiServlet -//

Post notes

-// Currently the server 3 more times complex and can compete with -// most popular app and web servers used for deploying of web -// Java applications. - -// Inheritance can extend usage of this server -public class Serve implements ServletContext, Serializable -{ - - public static final String ARG_PORT = "port"; - - public static final String ARG_THROTTLES = "throttles"; - - public static final String ARG_SERVLETS = "servlets"; - - public static final String ARG_REALMS = "realms"; - - public static final String ARG_ALIASES = "aliases"; - - public static final String ARG_BINDADDRESS = "bind-address"; - - public static final String ARG_BACKLOG = "backlog"; - - public static final String ARG_CGI_PATH = "cgi-path"; - - public static final String ARG_ERR = "error-stream"; - - public static final String ARG_OUT = "out-stream"; - - public static final String ARG_SESSION_TIMEOUT = "session-timeout"; - - public static final String ARG_LOG_DIR = "log-dir"; - - public static final String ARG_LOG_OPTIONS = "log-options"; - - public static final String ARG_NOHUP = "nohup"; - - public static final String ARG_JSP = "JSP"; - - public static final String ARG_WAR = "war-deployer"; - - public static final String ARG_KEEPALIVE = "keep-alive"; - - public static final String DEF_LOGENCODING = "tjws.serve.log.encoding"; - - public static final String ARG_KEEPALIVE_TIMEOUT = "timeout-keep-alive"; - - public static final String ARG_MAX_CONN_USE = "max-alive-conn-use"; - - public static final String ARG_SESSION_PERSIST = "sssn-persistance"; - - public static final String ARG_MAX_ACTIVE_SESSIONS = "max-active-sessions"; - - public static final String ARG_ACCESS_LOG_FMT = "access-log-format"; - - public static final String ARG_ACCEPTOR_CLASS = "acceptorImpl"; - - public static final String ARG_WORK_DIRECTORY = "workdirectory"; - - public static final String ARG_SESSION_SEED = "SessionSeed"; - - public static final String ARG_THREAD_POOL_SIZE = Utils.ThreadPool.MAXNOTHREAD; - - - protected static final int DEF_SESSION_TIMEOUT = 30; // in minutes - - protected static final int DEF_MIN_ACT_SESS = 10; - - protected static final int DESTROY_TIME_SEC = 15; - - protected static final int HTTP_MAX_HDR_LEN = 1024 * 1024 * 10; - - public static final int DEF_PORT = 8080; - - public static final String BGCOLOR = "BGCOLOR=\"#D1E9FE\""; - - /** - * max number of alive connections default value - */ - protected static final int DEF_MAX_CONN_USE = 100; - - public static final String UTF8 = "UTF-8"; // default encoding - - protected String hostName; - - private transient PrintStream logStream; - - private boolean useAccLog; - - private boolean keepAlive; - - private int timeoutKeepAlive; - - private int maxAliveConnUse; - - private boolean showUserAgent; - - private boolean showReferer; - - protected String keepAliveHdrParams; - - protected transient PathTreeDictionary registry; - - protected transient PathTreeDictionary realms; - - protected transient PathTreeDictionary mappingtable; - - private Hashtable attributes; - - protected transient KeepAliveCleaner keepAliveCleaner; - - protected transient ThreadGroup serverThreads; - - protected transient Utils.ThreadPool threadPool; - - protected transient Constructor gzipInStreamConstr; - - // for sessions - private byte[] uniqer = new byte[20]; // TODO consider configurable strength - - private SecureRandom srandom; - - protected HttpSessionContextImpl sessions; - - protected int expiredIn; - - public Map arguments; - - public Properties mime; - - protected List connections = new ArrayList(); - - // / Constructor. - public Serve(Map arguments, PrintStream logStream) - { - this.arguments = arguments; - this.logStream = logStream; - registry = new PathTreeDictionary(); - realms = new PathTreeDictionary(); - attributes = new Hashtable(); - serverThreads = new ThreadGroup("TJWS threads"); - Properties props = new Properties(); - props.putAll(arguments); - // TODO do not create thread pool unless requested - threadPool = new Utils.ThreadPool(props, new Utils.ThreadFactory() - { - public Thread create(Runnable runnable) - { - Thread result = new Thread(serverThreads, runnable); - result.setDaemon(true); - return result; - } - }); - setAccessLogged(); - // modified by lishen - keepAlive = arguments.get(ARG_KEEPALIVE) == null || ((Boolean) arguments.get(ARG_KEEPALIVE)).booleanValue(); -// keepAlive = false; - System.out.println("KEEPALIVE!: " + keepAlive); - int timeoutKeepAliveSec; - try - { - timeoutKeepAliveSec = Integer.parseInt((String) arguments.get(ARG_KEEPALIVE_TIMEOUT)); - } - catch (Exception ex) - { - timeoutKeepAliveSec = 30; - } - timeoutKeepAlive = timeoutKeepAliveSec * 1000; - try - { - maxAliveConnUse = Integer.parseInt((String) arguments.get(ARG_MAX_CONN_USE)); - } - catch (Exception ex) - { - maxAliveConnUse = DEF_MAX_CONN_USE; - } - keepAliveHdrParams = "timeout=" + timeoutKeepAliveSec + ", max=" + maxAliveConnUse; - - expiredIn = arguments.get(ARG_SESSION_TIMEOUT) != null ? ((Integer) arguments.get(ARG_SESSION_TIMEOUT)) - .intValue() : DEF_SESSION_TIMEOUT; - srandom = new SecureRandom((arguments.get(ARG_SESSION_SEED) == null ? "TJWS" + new Date() : (String) arguments.get(ARG_SESSION_SEED)).getBytes()); - try - { - gzipInStreamConstr = Class.forName("java.util.zip.GZIPInputStream").getConstructor(new Class[]{InputStream.class}); - } - catch (ClassNotFoundException cne) - { - - } - catch (NoSuchMethodException nsm) - { - - } - initMime(); - } - - /** - * Default constructor to create TJWS as a bean - */ - public Serve() - { - this(new HashMap(), System.err); - } - - protected void setAccessLogged() - { - String logflags = (String) arguments.get(ARG_LOG_OPTIONS); - if (logflags != null) - { - useAccLog = true; - showUserAgent = logflags.indexOf('A') >= 0; - showReferer = logflags.indexOf('R') >= 0; - } - } - - protected boolean isAccessLogged() - { - return useAccLog; - } - - protected boolean isShowReferer() - { - return showReferer; - } - - protected boolean isShowUserAgent() - { - return showUserAgent; - } - - protected boolean isKeepAlive() - { - return keepAlive; - } - - protected int getKeepAliveDuration() - { - return timeoutKeepAlive; - } - - protected String getKeepAliveParamStr() - { - return keepAliveHdrParams; - } - - protected int getMaxTimesConnectionUse() - { - return maxAliveConnUse; - } - - protected void initMime() - { - mime = new Properties(); - try - { - mime.load(getClass().getClassLoader().getResourceAsStream("Acme/Resource/mime.properties")); - } - catch (Exception ex) - { - log("MIME map can't be loaded:" + ex); - } - } - - // / Register a Servlet by class name. Registration consists of a URL - // pattern, which can contain wildcards, and the class name of the Servlet - // to launch when a matching URL comes in. Patterns are checked for - // matches in the order they were added, and only the first match is run. - public void addServlet(String urlPat, String className) - { - addServlet(urlPat, className, (Hashtable) null); - } - - /** - * Adds a servlet to run - * - * @param urlPat servlet invoker URL pattern - * @param className servlet class name - * @param initParams servlet init parameters - */ - public void addServlet(String urlPat, String className, Hashtable initParams) - { - // Check if we're allowed to make one of these. - SecurityManager security = System.getSecurityManager(); - if (security != null) - { - int i = className.lastIndexOf('.'); - if (i > 0) - { - security.checkPackageAccess(className.substring(0, i)); - security.checkPackageDefinition(className.substring(0, i)); - } - } - - // Make a new one. - try - { - addServlet(urlPat, (Servlet) Class.forName(className).newInstance(), initParams); - } - catch (ClassNotFoundException e) - { - log("Class not found: " + className); - ClassLoader cl = getClass().getClassLoader(); - log("Class loader: " + cl); - if (cl instanceof java.net.URLClassLoader) - log("CP: " + java.util.Arrays.asList(((java.net.URLClassLoader) cl).getURLs())); - } - catch (ClassCastException e) - { - log("Servlet class doesn't implement javax.servlet.Servlet: " + e.getMessage()); - } - catch (InstantiationException e) - { - log("Can't instantiate servlet: " + e.getMessage()); - } - catch (IllegalAccessException e) - { - log("Illegal class access: " + e.getMessage()); - } - catch (Exception e) - { - log("Unexpected problem of servlet creation: " + e, e); - } - } - - /** - * Register a Servlet. Registration consists of a URL pattern, - * which can contain wildcards, and the Servlet to - * launch when a matching URL comes in. Patterns are checked for - * matches in the order they were added, and only the first match is run. - * - * @param urlPat servlet invoker URL pattern - * @param servlet already instantiated servlet but init - */ - public void addServlet(String urlPat, Servlet servlet) - { - addServlet(urlPat, servlet, (Hashtable) null); - } - - /** - * Register a Servlet - * - * @param urlPat - * @param servlet - * @param initParams - */ - public synchronized void addServlet(String urlPat, Servlet servlet, Hashtable initParams) - { - try - { - if (getServlet(urlPat) != null) - log("Servlet overriden by " + servlet + ", for path:" + urlPat); - servlet.init(new ServeConfig((ServletContext) this, initParams, urlPat)); - registry.put(urlPat, servlet); - } - catch (ServletException e) - { // - // it handles UnavailableException as well without an attempt to re-adding - log("Problem initializing servlet, it won't be used: " + e); - } - } - - public Servlet unloadServlet(Servlet servlet) - { - Servlet result = null; - synchronized (registry) - { - result = (Servlet) registry.remove(servlet)[0]; - } - return result; - } - - public synchronized void unloadServlet(String urlPat) - { - Servlet servlet = (Servlet) registry.remove(urlPat)[0]; - if (servlet != null) - servlet.destroy(); // sessions associated with it have to be invalidated to free up any the servlet specific object - // TODO decide if UnavailableException should be thrown at access - } - - // / Register a standard set of Servlets. These will return - // files or directory listings, and run CGI programs, much like a - // standard HTTP server. - //

- // Because of the pattern checking order, this should be called - // after you've added any custom Servlets. - //

- // The current set of default servlet mappings: - //

    - //
  • If enabled, *.cgi goes to CgiServlet, and gets run as a CGI program. - //
  • * goes to FileServlet, and gets served up as a file or directory. - //
- // @param cgi whether to run CGI programs - // TODO: provide user specified CGI directory - public void addDefaultServlets(String cgi) - { - try - { - addDefaultServlets(cgi, null); - } - catch (IOException ioe) - { /* ignore, makes sense only for throtles */ - } - } - - /** - * Register a standard set of Servlets, with optional throttles. These will return files or directory listings, and run CGI programs, much like a standard - * HTTP server. - *

- * Because of the pattern checking order, this should be called after you've added any custom Servlets. - *

- * The current set of default servlet mappings: - *

    - *
  • If enabled, *.cgi goes to CgiServlet, and gets run as a CGI program. - *
  • * goes to FileServlet, and gets served up as a file or directory. - *
- * - * @param cgi whether to run CGI programs - * @param throttles filename to read FileServlet throttle settings from, can be null - * @throws java.io.IOException - */ - public void addDefaultServlets(String cgi, String throttles) throws IOException - { - // TODO: provide user specified CGI directory - if (cgi != null) - { - if (getServlet("/" + cgi) == null) - addServlet("/" + cgi, new Acme.Serve.CgiServlet()); - else - log("Servlet for path '/" + cgi + "' already defined and no default will be used."); - } - if (getServlet("/") == null) - if (throttles != null) - addServlet("/", new Acme.Serve.FileServlet(throttles, null)); - else - addServlet("/", new Acme.Serve.FileServlet()); - else - log("Servlet for path '/' already defined and no default will be used."); - } - - protected void addWarDeployer(String deployerFactory, String throttles) - { - if (deployerFactory == null) // try to use def - deployerFactory = "rogatkin.web.WarRoller"; - try - { - WarDeployer wd = (WarDeployer) Class.forName(deployerFactory).newInstance(); - wd.deploy(this); - } - catch (ClassNotFoundException cnf) - { - log("Problem initializing war deployer: " + cnf); - } - catch (Exception e) - { - log("Problem war(s) deployment", e); - } - } - - protected File getPersistentFile() - { - if (arguments.get(ARG_SESSION_PERSIST) == null || (Boolean) arguments.get(ARG_SESSION_PERSIST) == Boolean.FALSE) - return null; - String workPath = (String) arguments.get(ARG_WORK_DIRECTORY); - if (workPath == null) - workPath = "."; - return new File(workPath, hostName + '-' - + (arguments.get(ARG_PORT) == null ? String.valueOf(DEF_PORT) : arguments.get(ARG_PORT)) - + "-session.obj"); - } - - // Run the server. Returns only on errors. - transient boolean running = true; - - protected transient Acceptor acceptor; - - protected transient Thread ssclThread; - - protected transient boolean initialized; - - protected CountDownLatch shutdownLatch; - protected Thread backgroundThread; - - public void runInBackground() - { - shutdownLatch = new CountDownLatch(1); - try - { - init(); - } - catch (IOException e) - { - throw new RuntimeException(e); - } - backgroundThread = new Thread() - { - public void run() - { - try - { - serve(); - } - finally - { - shutdownLatch.countDown(); - } - } - }; - backgroundThread.start(); - - } - - public void stopBackground() - { - try - { - notifyStop(); - } - catch (Throwable ignored) - { - } - try - { - if (shutdownLatch.await(100, TimeUnit.MILLISECONDS) == false) - { - try - { - backgroundThread.interrupt(); - } - catch (Exception ignored) - { - } - } - shutdownLatch.await(1, TimeUnit.SECONDS); - } - catch (InterruptedException e) - { - } - synchronized(connections) - { - for (ServeConnection conn : connections) - { - conn.closeSocket(); - } - connections.clear(); - } - } - - /** - * Launches the server - * It doesn't exist until server runs, so start it in a dedicated thread. - * - * @return 0 if the server successfully terminated, 1 if it can't be started and -1 if it - * was terminated during some errors - */ - public int serve() - { - try - { - while (running) - { - try - { - Socket socket = acceptor.accept(); - // TODO consider to use ServeConnection object pool - if (keepAliveCleaner != null) // we need to add regardless of keep alive - keepAliveCleaner.addConnection(new ServeConnection(socket, this)); - else - new ServeConnection(socket, this); // TODO consider req/resp objects pooling - } - catch (IOException e) - { - log("Accept: " + e); - } - catch (SecurityException se) - { - log("Illegal access: " + se); - } - catch (IllegalStateException is) - { - log("Illegal state: " + is); - } - } - } - catch (Throwable t) - { - log("Unhandled exception: " + t + ", server is terminating.", t); - if (t instanceof ThreadDeath) - throw (Error) t; - return -1; - } - finally - { - try - { - if (acceptor != null) - acceptor.destroy(); - } - catch (IOException e) - { - } - } - return 0; - } - - public void init() throws IOException - { - shutdownLatch = new CountDownLatch(1); - acceptor = createAcceptor(); - - if (expiredIn > 0) - { - ssclThread = new Thread(serverThreads, new Runnable() - { - public void run() - { - while (running) - { - try - { - Thread.sleep(expiredIn * 60 * 1000); - } - catch (InterruptedException ie) - { - if (running == false) - break; - } - Enumeration e = sessions.keys(); - while (e.hasMoreElements()) - { - Object sid = e.nextElement(); - if (sid != null) - { - AcmeSession as = (AcmeSession) sessions.get(sid); - if (as != null && (as.checkExpired() || !as.isValid())) - { // log("sesion - as = (AcmeSession) sessions.remove(sid); - if (as != null && as.isValid()) - try - { - as.invalidate(); - } - catch (IllegalStateException ise) - { - - } - } - } - } - } - } - }, "Session cleaner"); - ssclThread.setPriority(Thread.MIN_PRIORITY); - // ssclThread.setDaemon(true); - ssclThread.start(); - } // else - // expiredIn = -expiredIn; - if (isKeepAlive()) - { - keepAliveCleaner = new KeepAliveCleaner(); - keepAliveCleaner.start(); - } - File fsessions = getPersistentFile(); - if (fsessions != null && fsessions.exists()) - { - BufferedReader br = null; - try - { - br = new BufferedReader(new FileReader(fsessions)); - sessions = HttpSessionContextImpl.restore(br, Math.abs(expiredIn) * 60, this); - } - catch (IOException ioe) - { - log("Problem in restoring sessions.", ioe); - } - catch (Exception e) - { - log("Unexpected problem in restoring sessions.", e); - } - finally - { - if (br != null) - try - { - br.close(); - } - catch (IOException ioe) - { - } - } - } - if (sessions == null) - sessions = new HttpSessionContextImpl(); - // TODO: display address as name and as ip - System.out.println("[" + new Date() + "] TJWS httpd " + hostName + " - " + acceptor + " is listening."); - } - - /** - * Tells the server to stop - * - * @throws java.io.IOException - */ - public void notifyStop() throws IOException - { - running = false; - acceptor.destroy(); - acceptor = null; - if (ssclThread != null) - ssclThread.interrupt(); - } - - public static interface Acceptor - { - public void init(Map inProperties, Map outProperties) throws IOException; - - public Socket accept() throws IOException; - - public void destroy() throws IOException; - } - - protected Acceptor createAcceptor() throws IOException - { - String acceptorClass = (String) arguments.get(ARG_ACCEPTOR_CLASS); - if (acceptorClass == null) - acceptorClass = "Acme.Serve.SimpleAcceptor"; - // assured defaulting here - try - { - acceptor = (Acceptor) Class.forName(acceptorClass).newInstance(); - } - catch (InstantiationException e) - { - log("Couldn't instantiate Acceptor, the Server is inoperable", e); - } - catch (IllegalAccessException e) - { - Constructor c; - try - { - c = Class.forName(acceptorClass).getDeclaredConstructor(Utils.EMPTY_CLASSES); - c.setAccessible(true); - acceptor = (Acceptor) c.newInstance(Utils.EMPTY_OBJECTS); - } - catch (Exception e1) - { - log("Acceptor is not accessable or can't be instantiated, the Server is inoperable", e); - } - } - catch (ClassNotFoundException e) - { - log("Acceptor class not found, the Server is inoperable", e); - } - Map acceptorProperties = new Properties(); - acceptor.init(arguments, acceptorProperties); - hostName = (String) acceptorProperties.get(ARG_BINDADDRESS); - return acceptor; - } - - // Methods from ServletContext. - - // / Gets a servlet by name. - // @param name the servlet name - // @return null if the servlet does not exist - - public Servlet getServlet(String name) - { - try - { - return (Servlet) registry.get(name)[0]; - } - catch (NullPointerException npe) - { - return null; - } - } - - // / Enumerates the servlets in this context (server). Only servlets that - // are accesible will be returned. This enumeration always includes the - // servlet itself. - public Enumeration getServlets() - { - return registry.elements(); - } - - // / Enumerates the names of the servlets in this context (server). Only - // servlets that are accesible will be returned. This enumeration always - // includes the servlet itself. - public Enumeration getServletNames() - { - return registry.keys(); - } - - // / Destroys all currently-loaded servlets. - public synchronized void destroyAllServlets() - { - //log("Entering destroyAllServlets()", new Exception("Entering destroyAllServlets()")); - // serialize sessions - - // invalidate all sessions - // TODO consider merging two pieces below, generally if session is stored, - // it shouldn't be invalidated - File sf = getPersistentFile(); - if (sf != null && sessions != null) - { - Writer w = null; - try - { - w = new FileWriter(sf); - sessions.save(w); - log("Sessions stored."); - } - catch (IOException ioe) - { - log("IO problem in storing sessions " + ioe); - } - catch (Throwable t) - { - log("Problem in storing sessions " + t); - } - finally - { - try - { - w.close(); - } - catch (Exception e) - { - } - } - - Enumeration e = sessions.keys(); - while (e.hasMoreElements()) - { - Object sid = e.nextElement(); - if (sid != null) - { - AcmeSession as = (AcmeSession) sessions.get(sid); - if (as != null) - { - as = (AcmeSession) sessions.remove(sid); - if (as != null && as.isValid()) - try - { - as.invalidate(); - } - catch (IllegalStateException ise) - { - - } - } - } - } - } - // destroy servlets - final Enumeration en = registry.elements(); - Runnable servletDestroyer = new Runnable() - { - public void run() - { - ((Servlet) en.nextElement()).destroy(); - } - }; - int dhc = 0; - while (en.hasMoreElements()) - { - Thread destroyThread = new Thread(servletDestroyer, "Destroy"); - destroyThread.setDaemon(true); - destroyThread.start(); - try - { - destroyThread.join(DESTROY_TIME_SEC * 1000); - } - catch (InterruptedException e) - { - } - if (destroyThread.isAlive()) - { - log("Destroy thread didn't terminate in " + DESTROY_TIME_SEC); - destroyThread.setName("Destroy too long " + (dhc++)); // let it running with different name - //destroyThread.stop(); - } - } - // clean access tree - registry = new PathTreeDictionary(); - } - - protected void setMappingTable(PathTreeDictionary mappingtable) - { - this.mappingtable = mappingtable; - } - - protected void setRealms(PathTreeDictionary realms) - { - this.realms = realms; - } - - AcmeSession getSession(String id) - { - return (AcmeSession) sessions.get(id); - } - - HttpSession createSession() - { - Integer ms = (Integer) this.arguments.get(ARG_MAX_ACTIVE_SESSIONS); - if (ms != null && ms.intValue() < sessions.size()) - return null; - HttpSession result = new AcmeSession(generateSessionId(), Math.abs(expiredIn) * 60, this, sessions); - synchronized (sessions) - { - sessions.put(result.getId(), result); - } - return result; - } - - void removeSession(String id) - { - synchronized (sessions) - { - sessions.remove(id); - } - } - - // / Write information to the servlet log. - // @param message the message to log - public void log(String message) - { - Date date = new Date(System.currentTimeMillis()); - logStream.println("[" + date.toString() + "] " + message); - } - - public void log(String message, Throwable throwable) - { - if (throwable != null) - { - StringWriter sw; - PrintWriter pw = new PrintWriter(sw = new StringWriter()); - throwable.printStackTrace(pw); - // printCauses(throwable, pw); - message = message + '\n' + sw; - } - log(message); - } - - // protected void printCauses(Throwable throwable, PrintWriter printWriter) { - // try { - // throwable = throwable instanceof ServletException ? ((ServletException) throwable).getRootCause() - // : (Throwable) throwable.getClass().getMethod("getCause", new Class[] {}).invoke(throwable, - // new Object[] {}); - // if (throwable != null) { - // printWriter.write("Caused by:\n"); - // throwable.printStackTrace(printWriter); - // printCauses(throwable, printWriter); - // } - // } catch (Exception e) { - // } - // } - - // / Write a stack trace to the servlet log. - // @param exception where to get the stack trace - // @param message the message to log - - public void log(Exception exception, String message) - { - log(message, exception); - } - - // / Applies alias rules to the specified virtual path and returns the - // corresponding real path. It returns null if the translation - // cannot be performed. - // @param path the path to be translated - public String getRealPath(String path) - { - // try { - // path = new String(path.getBytes("ISO-8859-1"), UTF8); - // } catch (Exception ee) { // no encoding - // } - // System.err.print("[" + path + "]->["); - if (mappingtable != null) - { - // try find first sub-path - Object[] os = mappingtable.get(path); - // System.err.println("Searching for path: "+path+" found: "+os[0]); - if (os[0] == null) - return null; - int slpos = ((Integer) os[1]).intValue(); - int pl = path.length(); - if (slpos > 0) - { - if (path.length() > slpos) - path = path.substring(slpos + 1); - else - path = ""; - } - else if (pl > 0) - { - for (int i = 0; i < pl; i++) - { - char s = path.charAt(i); - if (s == '/' || s == '\\') - continue; - else - { - if (i > 0) - path = path.substring(i); - break; - } - } - } - // System.err.println("Path after processing :"+path+" slash was at - // "+slpos); - return new File((File) os[0], path).getPath(); - } - return path; - } - - /** - * @return - */ - public String getContextPath() - { - return ""; - } - - // / Returns the MIME type of the specified file. - // @param file file name whose MIME type is required - public String getMimeType(String file) - { - int dp = file.lastIndexOf('.'); - if (dp > 0) - { - return mime.getProperty(file.substring(dp + 1).toUpperCase()); - } - return null; - } - - // / Returns the name and version of the web server under which the servlet - // is running. - // Same as the CGI variable SERVER_SOFTWARE. - public String getServerInfo() - { - return Serve.Identification.serverName + " " + Serve.Identification.serverVersion + " (" - + Serve.Identification.serverUrl + ")"; - } - - // / Returns the value of the named attribute of the network service, or - // null if the attribute does not exist. This method allows access to - // additional information about the service, not already provided by - // the other methods in this interface. - public Object getAttribute(String name) - { - return attributes.get(name); - } - - // ///////////////// JSDK 2.1 extensions ////////////////////////// - public void removeAttribute(String name) - { - attributes.remove(name); - } - - public void setAttribute(String name, Object object) - { - if (object != null) - attributes.put(name, object); - else - attributes.remove(name); - } - - public Enumeration getAttributeNames() - { - return attributes.keys(); - } - - public ServletContext getContext(String uripath) - { - // TODO check webapp servlets to find out conexts for uri - return this; // only root context supported - } - - public int getMajorVersion() - { - return 2; // support 2.x - } - - public int getMinorVersion() - { - return 5; // support 2.5 - } - - // 2.3 - - /** - * Returns a directory-like listing of all the paths to resources within the web application whose longest sub-path matches the supplied path argument. - * Paths indicating subdirectory paths end with a '/'. The returned paths are all relative to the root of the web application and have a leading '/'. For - * example, for a web application containing - *

- * /welcome.html
- * /catalog/index.html
- * /catalog/products.html
- * /catalog/offers/books.html
- * /catalog/offers/music.html
- * /customer/login.jsp
- * /WEB-INF/web.xml
- * /WEB-INF/classes/com.acme.OrderServlet.class, - *

- * getResourcePaths("/") returns {"/welcome.html", "/catalog/", "/customer/", "/WEB-INF/"}
- * getResourcePaths("/catalog/") returns {"/catalog/index.html", "/catalog/products.html", "/catalog/offers/"}. - *

- * - * @param the - - * partial path used to match the resources, which must start with a / - * @return a Set containing the directory listing, or null if there are no resources in the web application whose path begins with the supplied path. - * @since Servlet 2.3 - */ - public java.util.Set getResourcePaths(String path) - { - String realPath = getRealPath(path); - if (realPath != null) - { - - String[] dir = new File(realPath).list(); - if (dir.length > 0) - { - HashSet set = new HashSet(dir.length); - for (int i = 0; i < dir.length; i++) - set.add(dir[i]); - return set; - } - } - return null; - } - - /** - * Returns the name of this web application correponding to this ServletContext as specified in the deployment descriptor for this web application by the - * display-name element. - * - * @return The name of the web application or null if no name has been declared in the deployment descriptor. - * @since Servlet 2.3 - */ - public String getServletContextName() - { - return null; - } - - /** - * Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context - * root. - *

- *

- * This method allows the servlet container to make a resource available to servlets from any source. Resources can be located on a local or remote file - * system, in a database, or in a .war file. - *

- *

- * The servlet container must implement the URL handlers and URLConnection objects that are necessary to access the resource. - *

- *

- * This method returns null if no resource is mapped to the pathname. - *

- *

- * Some containers may allow writing to the URL returned by this method using the methods of the URL class. - *

- *

- * The resource content is returned directly, so be aware that requesting a .jsp page returns the JSP source code. Use a - * RequestDispatcher instead to include results of an execution. - *

- *

- * This method has a different purpose than java.lang.Class.getResource, which looks up resources based on a class loader. This method does - * not use class loaders. - * - * @param path a String specifying the path to the resource - * @return the resource located at the named path, or null if there is no resource at that path - * @throws java.net.MalformedURLException if the pathname is not given in the correct form - */ - public URL getResource(String path) throws MalformedURLException - { - if (path == null || path.length() == 0 || path.charAt(0) != '/') - throw new MalformedURLException("Path " + path + " is not in acceptable form."); - File resFile = new File(getRealPath(path)); - if (resFile.exists()) // TODO get canonical path is more robust - return new URL("file", "localhost", resFile.getPath()); - return null; - } - - /** - * Returns the resource located at the named path as an InputStream object. - *

- *

- * The data in the InputStream can be of any type or length. The path must be specified according to the rules given in - * getResource. This method returns null if no resource exists at the specified path. - *

- *

- * Meta-information such as content length and content type that is available via getResource method is lost when using this method. - *

- *

- * The servlet container must implement the URL handlers and URLConnection objects necessary to access the resource. - *

- *

- * This method is different from java.lang.Class.getResourceAsStream, which uses a class loader. This method allows servlet containers to - * make a resource available to a servlet from any location, without using a class loader. - * - * @param path a String specifying the path to the resource - * @return the InputStream returned to the servlet, or null if no resource exists at the specified path - */ - public InputStream getResourceAsStream(String path) - { - try - { - return getResource(path).openStream(); - } - catch (Exception e) - { - } - return null; - } - - public RequestDispatcher getRequestDispatcher(String urlpath) - { - if (urlpath == null || urlpath.length() == 0 || urlpath.charAt(0) != '/') - return null; - try - { - return new SimpleRequestDispatcher(urlpath); - } - catch (NullPointerException npe) - { - return null; - } - } - - // no way to specify parameters for context - public String getInitParameter(String param) - { - return null; - } - - public Enumeration getInitParameterNames() - { - return Utils.EMPTY_ENUMERATION; - } - - public RequestDispatcher getNamedDispatcher(String name) - { - // named resources are not supported - return null; - } - - synchronized String generateSessionId() - { - srandom.nextBytes(uniqer); - // TODO swap randomly bytes - return Utils.base64Encode(uniqer); - } - - protected class SimpleRequestDispatcher implements RequestDispatcher - { - HttpServlet servlet; - - String dispatchPath; - - String dispatchQuery; - - int dispatchLen; - - SimpleRequestDispatcher(String path) - { - Object[] os = registry.get(path); - servlet = (HttpServlet) os[0]; - //log("Dispatch to: " + path + ", servlet "+servlet); - if (servlet == null) - throw new NullPointerException(); - dispatchLen = ((Integer) os[1]).intValue(); - int qmp = path.indexOf('?'); - if (qmp < 0 || qmp >= path.length() - 1) - dispatchPath = path; - else - { - dispatchPath = path.substring(0, qmp); - dispatchQuery = path.substring(qmp + 1); - } - } - - public void forward(ServletRequest _request, ServletResponse _response) throws ServletException, - IOException - { - _request.removeAttribute("javax.servlet.forward.request_uri"); // reset in case of nested - _response.reset(); - servlet.service(new HttpServletRequestWrapper((HttpServletRequest) _request) - { - public String getPathInfo() - { - return dispatchLen >= dispatchPath.length() ? null : dispatchPath.substring(dispatchLen); - } - - public String getRequestURI() - { - return dispatchPath; - } - - public String getQueryString() - { - return dispatchQuery; - } - - public String getPathTranslated() - { - //System.out.println("Path t path i: "+getPathInfo()+", dp: "+dispatchPath); - return getRequest().getRealPath(getPathInfo()); - } - - public String getServletPath() - { - return dispatchLen <= 0 ? "" : dispatchPath.substring(0, dispatchLen); - } - - public synchronized Enumeration getAttributeNames() - { - if (super.getAttribute("javax.servlet.forward.request_uri") == null) - { - setAttribute("javax.servlet.forward.request_uri", super.getRequestURI()); - setAttribute("javax.servlet.forward.context_path", this.getContextPath()); - setAttribute("javax.servlet.forward.servlet_path", super.getServletPath()); - setAttribute("javax.servlet.forward.path_info", super.getPathInfo()); - setAttribute("javax.servlet.forward.query_string", super.getQueryString()); - } - return super.getAttributeNames(); - } - - public Object getAttribute(String name) - { - getAttributeNames(); // here is some overhead - return super.getAttribute(name); - } - - }, _response); - // TODO think when response isn't actual response ServeConnection - ((ServeConnection) _response).closeStreams(); // do not allow to continue - } - - public void include(ServletRequest _request, ServletResponse _response) throws ServletException, - IOException - { - _request.removeAttribute("javax.servlet.include.request_uri"); // reset in case of nested - ((Serve.ServeConnection) _response).setInInclude(true); - try - { - servlet.service(new HttpServletRequestWrapper((HttpServletRequest) _request) - { - public synchronized Enumeration getAttributeNames() - { - if (super.getAttribute("javax.servlet.include.request_uri") == null) - { - setAttribute("javax.servlet.include.request_uri", dispatchPath); - setAttribute("javax.servlet.include.context_path", this.getContextPath()); - setAttribute("javax.servlet.include.servlet_path", dispatchLen <= 0 ? "" : dispatchPath - .substring(0, dispatchLen)); - setAttribute("javax.servlet.include.path_info", dispatchLen >= dispatchPath.length() ? null - : dispatchPath.substring(dispatchLen)); - setAttribute("javax.servlet.include.query_string", dispatchQuery); - } - return super.getAttributeNames(); - } - - public Object getAttribute(String name) - { - getAttributeNames(); // here is some overhead - return super.getAttribute(name); - } - - }, _response); - } - finally - { - ((Serve.ServeConnection) _response).setInInclude(false); - } - } - - } - - // Keep Alive supporter, JDK 1.4 based for backwar compatibility - class KeepAliveCleaner extends Thread - { - protected List connections; - - protected List ingoings; - - protected volatile boolean stopped; - - private boolean noCheckClose; - - KeepAliveCleaner() - { - super("KeepAlive cleaner"); - connections = new ArrayList(); - ingoings = new ArrayList(); - setDaemon(true); - } - - public void end() - { - stopped = true; - this.interrupt(); - } - - synchronized void addConnection(ServeConnection conn) - { - synchronized (ingoings) - { - if (stopped == false) - ingoings.add(conn); - } - } - - public void run() - { - long d = getKeepAliveDuration(); - int maxUse = getMaxTimesConnectionUse(); - while (true) - { - synchronized (ingoings) - { - Iterator i = ingoings.iterator(); - while (i.hasNext()) - { - connections.add(i.next()); - i.remove(); - } - } - Iterator i = connections.iterator(); - long ct = System.currentTimeMillis(); - d = getKeepAliveDuration(); - while (i.hasNext()) - { - ServeConnection conn = (ServeConnection) i.next(); - boolean closed = conn.socket == null; - if (noCheckClose == false) - synchronized (conn) - { - if (conn.socket != null) - try - { - closed = ((Boolean) conn.socket.getClass().getMethod("isClosed", - Utils.EMPTY_CLASSES).invoke(conn.socket, Utils.EMPTY_OBJECTS)) - .booleanValue(); - } - catch (IllegalArgumentException e) - { - } - catch (SecurityException e) - { - } - catch (IllegalAccessException e) - { - } - catch (InvocationTargetException e) - { - } - catch (NoSuchMethodException e) - { - noCheckClose = true; - } - } - if (closed || (conn.keepAlive && (ct - conn.lastWait > d && conn.lastRun < conn.lastWait)) - || stopped - /* || conn.timesRequested > maxUse */) - { - i.remove(); - synchronized (conn) - { - if (conn.socket != null) - try - { - //System.err.println("Closing socket:"+conn.socket.getClass().getName()); // !!! - //conn.socket.close(); - conn.socket.getInputStream().close(); - } - catch (IOException ioe) - { - // ignore - } - //System.err.println("done"); - } - } - } - if (stopped && connections.size() == 0) - break; - try - { - sleep(d); - } - catch (InterruptedException ie) - { - stopped = true; // not thread safe - } - } - } - } - - final static class Identification - { - public static final String serverName = "D. Rogatkin's TJWS based on Acme.Serve"; - - public static final String serverVersion = "Version 1.70, $Revision: 1.194 $"; - - public static final String serverUrl = "http://tjws.sourceforge.net"; - - public static final String serverIdHtml = "

" + serverName + " " + serverVersion + "
"; - } - - // //////////////////////////////////////////////////////////////// - - protected static class ServeConfig implements ServletConfig - { - - private ServletContext context; - - private Hashtable init_params; - - private String servletName; - - public ServeConfig(ServletContext context) - { - this(context, null, "undefined"); - } - - public ServeConfig(ServletContext context, Hashtable initParams, String servletName) - { - this.context = context; - this.init_params = initParams; - this.servletName = servletName; - } - - // Methods from ServletConfig. - - // / Returns the context for the servlet. - - public ServletContext getServletContext() - { - return context; - } - - // / Gets an initialization parameter of the servlet. - // @param name the parameter name - public String getInitParameter(String name) - { - // This server supports servlet init params. :) - if (init_params != null) - return (String) init_params.get(name); - return null; - } - - // / Gets the names of the initialization parameters of the servlet. - // @param name the parameter name - public Enumeration getInitParameterNames() - { - // This server does:) support servlet init params. - if (init_params != null) - return init_params.keys(); - return new Vector().elements(); - } - - // 2.2 - public String getServletName() - { - return servletName; - } - } - - // ///////////////////////////////////////////////////////////////////// - /** - * provides request/response - */ - public static class ServeConnection implements Runnable, HttpServletRequest, HttpServletResponse - { - private Socket socket; - - private Hashtable sslAttributes; - - private Serve serve; - - private ServletInputStream in; - - private ServletOutputStream out; - - private String scheme; - - public final static String WWWFORMURLENCODE = "application/x-www-form-urlencoded"; - - public final static String TRANSFERENCODING = "transfer-encoding".toLowerCase(); - - public final static String KEEPALIVE = "Keep-Alive".toLowerCase(); - - public final static String CONTENT_ENCODING = "Content-Encoding".toLowerCase(); - - public final static String CONNECTION = "Connection".toLowerCase(); - - public final static String CHUNKED = "chunked"; - - public final static String CONTENTLENGTH = "Content-Length".toLowerCase(); - - public final static String CONTENTTYPE = "Content-Type".toLowerCase(); - - public final static String SETCOOKIE = "Set-Cookie".toLowerCase(); - - public final static String HOST = "Host".toLowerCase(); - - public final static String COOKIE = "Cookie".toLowerCase(); - - public final static String ACCEPT_LANGUAGE = "Accept-Language".toLowerCase(); - - public final static String SESSION_COOKIE_NAME = "JSESSIONID"; - - public final static String SESSION_URL_NAME = ";$sessionid$"; // ;jsessionid= - - private static final Map EMPTYHASHTABLE = new Hashtable(); - - // URL rewriting - // http://www.myserver.com/catalog/index.html;jsessionid=mysession1928 - // like: - // http://www.sun.com/2001-0227/sunblade/;$sessionid$AD5RQ0IAADJAZAMTA1LU5YQ - - private String reqMethod; // == null by default - - private String reqUriPath, reqUriPathUn; - - private String reqProtocol; - - private String charEncoding; // req and resp - - private String remoteUser; - - private String authType; - - private boolean oneOne; // HTTP/1.1 or better - - private boolean reqMime; - - private Vector reqHeaderNames = new Vector(); - - private Vector reqHeaderValues = new Vector(); - - private Locale locale; // = java.util.Locale.getDefault(); - - private int uriLen; - - protected boolean keepAlive = true; - - protected int timesRequested; - - protected long lastRun, lastWait; - - private Vector outCookies; - - private Vector inCookies; - - private String sessionCookieValue, sessionUrlValue, sessionValue; - - protected String reqQuery; - - private PrintWriter pw; - - private ServletOutputStream rout; - - private Map formParameters; - - private Hashtable attributes = new Hashtable(); - - private int resCode = -1; - - private String resMessage; - - private Hashtable resHeaderNames = new Hashtable(); - - private String[] postCache; - - private boolean headersWritten; - - private MessageFormat accessFmt; - - private Object[] logPlaceholders; - - // TODO consider creation an instance per thread in a pool, thread memory can be used - - private final SimpleDateFormat expdatefmt = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss 'GMT'", Locale.US); // used for cookie - - private final SimpleDateFormat rfc850DateFmt = new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss 'GMT'", - Locale.US); // rfc850-date - - private final SimpleDateFormat headerdateformat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", - Locale.US); // rfc1123-date - - private final SimpleDateFormat asciiDateFmt = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy", Locale.US); // ASCII date, used in headers - - private static final TimeZone tz = TimeZone.getTimeZone("GMT"); - - static - { - tz.setID("GMT"); - } - - /* - * protected void finalize() throws Throwable { serve.log("Connection collected"); super.finalize(); } - */ - - // / Constructor. - - public ServeConnection(Socket socket, Serve serve) - { - // Save arguments. - this.socket = socket; - this.serve = serve; - expdatefmt.setTimeZone(tz); - headerdateformat.setTimeZone(tz); - rfc850DateFmt.setTimeZone(tz); - asciiDateFmt.setTimeZone(tz); - if (serve.isAccessLogged()) - { - // not format string must be not tull - accessFmt = new MessageFormat((String) serve.arguments.get(ARG_ACCESS_LOG_FMT)); - logPlaceholders = new Object[12]; - } - serve.threadPool.executeThread(this); - synchronized(serve.connections) - { - serve.connections.add(this); - } - } - - private void initSSLAttrs() - { - if (socket.getClass().getName().indexOf("SSLSocket") > 0) - { - try - { - sslAttributes = new Hashtable(); - Object sslSession = socket.getClass().getMethod("getSession", Utils.EMPTY_CLASSES).invoke(socket, - Utils.EMPTY_OBJECTS); - if (sslSession != null) - { - sslAttributes.put("javax.net.ssl.session", sslSession); - Method m = sslSession.getClass().getMethod("getCipherSuite", Utils.EMPTY_CLASSES); - m.setAccessible(true); - sslAttributes.put("javax.net.ssl.cipher_suite", m.invoke(sslSession, Utils.EMPTY_OBJECTS)); - m = sslSession.getClass().getMethod("getPeerCertificates", Utils.EMPTY_CLASSES); - m.setAccessible(true); - sslAttributes.put("javax.net.ssl.peer_certificates", m.invoke(sslSession, Utils.EMPTY_OBJECTS)); - } - } - catch (IllegalAccessException iae) - { - sslAttributes = null; - //iae.printStackTrace(); - } - catch (NoSuchMethodException nsme) - { - sslAttributes = null; - //nsme.printStackTrace(); - } - catch (InvocationTargetException ite) - { - // note we do not clear attributes, because SSLPeerUnverifiedException - // happens in the last call, when no client sertificate - //sslAttributes = null; - //ite.printStackTrace(); - } - catch (IllegalArgumentException iae) - { - //sslAttributes = null; - //iae.printStackTrace(); - } - //System.err.println("Socket SSL attrs: "+sslAttributes); - } - } - - /** - * it closes stream awaring of keep -alive - * - * @throws java.io.IOException - */ - public void closeStreams() throws IOException - { - //System.err.println("===>CLOSE()"); - IOException ioe = null; - try - { - if (pw != null) - pw.flush(); - else - out.flush(); - } - catch (IOException io1) - { - ioe = io1; - } - try - { - out.close(); - } - catch (IOException io1) - { - if (ioe != null) - ioe = (IOException) ioe.initCause(io1); - else - ioe = io1; - } - try - { - in.close(); - } - catch (IOException io1) - { - if (ioe != null) - ioe = (IOException) ioe.initCause(io1); - else - ioe = io1; - } - if (ioe != null) - throw ioe; - } - - public void closeSocket() - { - if (socket != null) - { - try - { - socket.close(); - } - catch (IOException e) - { - } - } - } - - // protected void finalize() throws Throwable { - // System.err.println("Connection object gone"); // !!! - // super.finalize(); - // } - - private void restart() - { - // new Exception("RESTART").printStackTrace(); - reqMethod = null; - reqUriPath = reqUriPathUn = null; - reqProtocol = null; - charEncoding = null; - remoteUser = null; - authType = null; - oneOne = false; - reqMime = false; - // considering that clear() works faster than new - if (reqHeaderNames == null) - reqHeaderNames = new Vector(); - else - reqHeaderNames.clear(); - if (reqHeaderValues == null) - reqHeaderValues = new Vector(); - else - reqHeaderValues.clear(); - locale = null; - uriLen = 0; - outCookies = null; - inCookies = null; - sessionCookieValue = null; - sessionUrlValue = null; - sessionValue = null; - reqQuery = null; - pw = null; - rout = null; - formParameters = null; - if (attributes == null) - attributes = new Hashtable(); - else - attributes.clear(); - if (sslAttributes != null) - attributes.putAll(sslAttributes); - resCode = -1; - resMessage = null; - resHeaderNames.clear(); - headersWritten = false; - postCache = null; - ((ServeInputStream) in).refresh(); - ((ServeOutputStream) out).refresh(); - } - - // Methods from Runnable. - public void run() - { - try - { - initSSLAttrs(); - in = new ServeInputStream(socket.getInputStream(), this); - out = new ServeOutputStream(socket.getOutputStream(), this); - do - { - restart(); - // Get the streams. - parseRequest(); - if (reqMethod != null && serve.isAccessLogged()) - { - // consider caching socket stuff for faster logging - // {0} {1} {2} [{3,date,dd/MMM/yyyy:HH:mm:ss Z}] \"{4} {5} {6}\" {7,number,#} {8,number} {9} {10} - // ARG_ACCESS_LOG_FMT - logPlaceholders[0] = socket.getInetAddress(); // IP - logPlaceholders[1] = "-"; // the RFC 1413 identity of the client - logPlaceholders[2] = remoteUser == null ? "-" : remoteUser; // remote user - logPlaceholders[3] = new Date(lastRun); // time stamp {3,date,dd/MMM/yyyy:HH:mm:ss Z} {3,time,} - logPlaceholders[4] = reqMethod; // method - logPlaceholders[5] = reqUriPathUn; // resource - logPlaceholders[6] = reqProtocol; // protocol - logPlaceholders[7] = new Integer(resCode); // res code - logPlaceholders[8] = new Long(((ServeOutputStream) out).lengthWritten()); - logPlaceholders[9] = new Integer(socket.getLocalPort()); - logPlaceholders[10] = serve.isShowReferer() ? getHeader("Referer") : "-"; - logPlaceholders[11] = serve.isShowUserAgent() ? getHeader("User-Agent") : "-"; - serve.logStream.println(accessFmt.format(logPlaceholders)); - } - lastRun = 0; - timesRequested++; - } while (keepAlive && serve.isKeepAlive() && timesRequested < serve.getMaxTimesConnectionUse()); - } - catch (IOException ioe) - { - //System.err.println("Drop "+ioe); - String errMsg = ioe.getMessage(); - if ((errMsg == null || errMsg.indexOf("ocket closed") < 0) && ioe instanceof java.nio.channels.AsynchronousCloseException == false) - serve.log("IO error: " + ioe + " in processing a request from " + socket.getInetAddress() + ":" - + socket.getLocalPort() + " / " + socket.getClass().getName()/*, ioe*/); - else - synchronized (this) - { - //serve.log("Exception considered as socket closed:"+ioe, ioe); - socket = null; - } - } - finally - { - synchronized (this) - { - synchronized(serve.connections) - { - serve.connections.remove(this); - } - if (socket != null) - try - { - socket.close(); - } - catch (IOException e) - { /* ignore */ - } - socket = null; - } - } - } - - private void parseRequest() throws IOException - { - byte[] lineBytes = new byte[4096]; - int len; - String line; - // / TODO put time mark here for start waiting for receiving requests - lastWait = System.currentTimeMillis(); - // Read the first line of the request. - len = in.readLine(lineBytes, 0, lineBytes.length); - if (len == -1 || len == 0) - { - if (keepAlive) - { - keepAlive = false; - // connection seems be closed - - } - else - { - problem("Status-Code 400: Bad Request(empty)", SC_BAD_REQUEST); - } - return; - } - if (len >= lineBytes.length) - { - problem("Status-Code 414: Request-URI Too Long", SC_REQUEST_URI_TOO_LONG); - return; - } - // //lastRun = 0; // to avoid closing socket in long process - line = new String(lineBytes, 0, len, UTF8); - StringTokenizer ust = new StringTokenizer(line); - if (ust.hasMoreTokens()) - { - reqMethod = ust.nextToken(); - if (ust.hasMoreTokens()) - { - reqUriPathUn = ust.nextToken(); - // TODO make it only when URL overwrite enambled - int uop = reqUriPathUn.indexOf(SESSION_URL_NAME); - if (uop > 0) - { - sessionUrlValue = reqUriPathUn.substring(uop + SESSION_URL_NAME.length()); - reqUriPathUn = reqUriPathUn.substring(0, uop); - try - { - serve.getSession(sessionUrlValue).userTouch(); - } - catch (NullPointerException npe) - { - sessionUrlValue = null; - } - catch (IllegalStateException ise) - { - sessionUrlValue = null; - } - } - if (ust.hasMoreTokens()) - { - reqProtocol = ust.nextToken(); - oneOne = !reqProtocol.toUpperCase().equals("HTTP/1.0"); - reqMime = true; - // Read the rest of the lines. - String s; - while ((s = ((ServeInputStream) in).readLine(HTTP_MAX_HDR_LEN)) != null) - { - if (s.length() == 0) - break; - int c = s.indexOf(':', 0); - if (c > 0) - { - String key = s.substring(0, c).trim().toLowerCase(); - String value = s.substring(c + 1).trim(); - reqHeaderNames.addElement(key); - reqHeaderValues.addElement(value); - if (CONNECTION.equalsIgnoreCase(key)) - if (oneOne) - keepAlive = "close".equalsIgnoreCase(value) == false; - else - keepAlive = KEEPALIVE.equalsIgnoreCase(value); - else if (KEEPALIVE.equalsIgnoreCase(key)) - { /// FF specific ? - // parse value to extract the connection specific timeoutKeepAlive and maxAliveConnUse - // todo that introduce the value in req/resp and copy defaults from Serve - - } - } - else - serve.log("header field '" + s + "' without ':'"); - } - } - else - { - reqProtocol = "HTTP/0.9"; - oneOne = false; - reqMime = false; - } - } - } - - if (reqProtocol == null) - { - problem("Status-Code 400: Malformed request line:" + line, SC_BAD_REQUEST); - return; - } - // Check Host: header in HTTP/1.1 requests. - if (oneOne) - { - String host = getHeader(HOST); - if (host == null) - { - problem("'Host' header missing in HTTP/1.1 request", SC_BAD_REQUEST); - return; - } - } - - // Split off query string, if any. - int qmark = reqUriPathUn.indexOf('?'); - if (qmark > -1) - { - if (qmark < reqUriPathUn.length() - 1) - reqQuery = reqUriPathUn.substring(qmark + 1); - reqUriPathUn = reqUriPathUn.substring(0, qmark); - } - reqUriPath = Utils.decode(reqUriPathUn, UTF8); - // TDOD check if reqUriPathUn starts with http://host:port - if (CHUNKED.equals(getHeader(TRANSFERENCODING))) - { - setHeader(CONTENTLENGTH, null); - ((ServeInputStream) in).chunking(true); - } - String contentEncoding = extractEncodingFromContentType(getHeader(CONTENTTYPE)); - // TODO: encoding in request can be invalid, then do default - setCharacterEncoding(contentEncoding != null ? contentEncoding : UTF8); - String contentLength = getHeader(CONTENTLENGTH); - if (contentLength != null) - try - { - ((ServeInputStream) in).setContentLength(Long.parseLong(contentLength)); - } - catch (NumberFormatException nfe) - { - serve.log("Invalid value of input content-length: " + contentLength); - } - // the code was originally in processing headers loop, however hhas been moved here - String encoding = getHeader(CONTENT_ENCODING); - /* Don't do content encoding. Let RESTEASY handle it - if (encoding != null) - { - if ((encoding.equalsIgnoreCase("gzip") || encoding.equalsIgnoreCase("compressed")) - && null != serve.gzipInStreamConstr && ((ServeInputStream) in).compressed(true)) - { - } - else - { - problem("Status-Code 415: Unsupported media type:" + encoding, SC_UNSUPPORTED_MEDIA_TYPE); - return; - } - } - */ - if (assureHeaders() && socket.getKeepAlive() == false) - socket.setKeepAlive(true); - // TODO new SimpleRequestDispatcher(reqUriPathUn).forward((ServletRequest) this, (ServletResponse) this); - Object[] os = serve.registry.get(reqUriPath); - if (os[0] != null) - { // note, os always not null - // / TODO put time mark here to monitor actual servicing - lastRun = System.currentTimeMillis(); - // System.err.println("Servlet "+os[0]+" for path "+reqUriPath); - uriLen = ((Integer) os[1]).intValue(); - runServlet((HttpServlet) os[0]); - } - else - { - problem("No any servlet found for serving " + reqUriPath, SC_BAD_REQUEST); - } - } - - private boolean assureHeaders() - { - if (reqMime) - setHeader("MIME-Version", "1.0"); - setDateHeader("Date", System.currentTimeMillis()); - setHeader("Server", Serve.Identification.serverName + "/" + Serve.Identification.serverVersion); - if (keepAlive && serve.isKeepAlive()) - { - if (reqMime) - { - setHeader(CONNECTION, KEEPALIVE); // set for 1.1 too, because some client do not follow a standard - if (oneOne) - setHeader(KEEPALIVE, serve.getKeepAliveParamStr()); - } - return true; - } - else - setHeader(CONNECTION, "close"); - return false; - } - - private void runServlet(HttpServlet servlete) throws IOException - { - // Set default response fields. - setStatus(SC_OK); - try - { - parseCookies(); - if (sessionValue == null) // not from cookie - sessionValue = sessionUrlValue; - if (authenificate()) - { - if (servlete instanceof SingleThreadModel) - synchronized (servlete) - { - servlete.service((ServletRequest) this, (ServletResponse) this); - } - else - servlete.service((ServletRequest) this, (ServletResponse) this); - } - // old close - } - catch (UnavailableException e) - { - if (e.isPermanent()) - { - serve.registry.remove(servlete); - servlete.destroy(); - } - else if (e.getUnavailableSeconds() > 0) - serve.log("Temporary unavailability feature is not supported " + servlete); - problem(e.getMessage(), SC_SERVICE_UNAVAILABLE); - } - catch (ServletException e) - { - serve.log("Servlet exception", e); - Throwable rootCause = e.getRootCause(); - while (rootCause != null) - { - serve.log("Caused by", rootCause); - if (rootCause instanceof ServletException) - rootCause = ((ServletException) rootCause).getRootCause(); - else - rootCause = rootCause.getCause(); /* 1.4 */ - } - problem(e.toString(), SC_INTERNAL_SERVER_ERROR); - } - catch (IOException ioe) - { - throw ioe; - } - catch (Exception e) - { - serve.log("Unexpected problem running servlet", e); - problem("Unexpected problem running servlet: " + e.toString(), SC_INTERNAL_SERVER_ERROR); - } - finally - { - closeStreams(); - // socket will be closed by a caller if no keep-alive - } - } - - private boolean authenificate() throws IOException - { - Object[] o = serve.realms.get(reqUriPath); // by Niel Markwick - BasicAuthRealm realm = null; - if (o != null) - realm = (BasicAuthRealm) o[0]; - // System.err.println("looking for realm for path "+getPathInfo()+" - // in - // "+serve.realms+" found "+realm); - if (realm == null) - return true; - - String credentials = getHeader("Authorization"); - - if (credentials != null) - { - credentials = Acme.Utils.base64Decode(credentials.substring(credentials.indexOf(' ') + 1), - getCharacterEncoding()); - int i = credentials.indexOf(':'); - String user = credentials.substring(0, i); - String password = credentials.substring(i + 1); - remoteUser = user; - authType = "BASIC"; // support only basic authenification (FORM, CLIENT_CERT, DIGEST ) - String realPassword = (String) realm.get(user); - // System.err.println("User "+user+" Password "+password+" real - // "+realPassword); - if (realPassword != null && realPassword.equals(password)) - return true; - } - - setStatus(SC_UNAUTHORIZED); - setHeader("WWW-Authenticate", "basic realm=\"" + realm.name() + '"'); - //writeHeaders(); // because sendError() is used - realSendError(); - return false; - } - - private void problem(String logMessage, int resCode) - { - serve.log(logMessage); - try - { - sendError(resCode, logMessage); - } - catch (IllegalStateException e) - { /* ignore */ - } - catch (IOException e) - { /* ignore */ - } - } - - private static final int MAYBEVERSION = 1; - - private static final int INVERSION = 2; - - private static final int OLD_INNAME = 3; - - private static final int OLD_INVAL = 4; - - private static final int INVERSIONNUM = 5; - - private static final int RECOVER = 6; - - private static final int NEW_INNAME = 7; - - private static final int NEW_INVAL = 8; - - private static final int INPATH = 9; - - private static final int MAYBEINPATH = 10; - - private static final int INPATHVALUE = 11; - - private static final int MAYBEPORT = 12; - - private static final int INDOMAIN = 13; - - private static final int MAYBEDOMAIN = 14; - - private static final int INPORT = 15; - - private static final int INDOMAINVALUE = 16; - - private static final int INPORTVALUE = 17; - - private void parseCookies() throws IOException - { - if (inCookies == null) - inCookies = new Vector(); - String cookies = getHeader(COOKIE); - if (cookies == null) - return; - try - { - String cookie_name = null; - String cookie_value = null; - String cookie_path = null; - String cookie_domain = null; - if (cookies.length() > 300 * 4096) - throw new IOException("Cookie string too long:" + cookies.length()); - //System.err.println("We received:" + cookies); - char[] cookiesChars = cookies.toCharArray(); - int state = MAYBEVERSION; - StringBuffer token = new StringBuffer(256); - boolean quoted = false; - for (int i = 0; i < cookiesChars.length; i++) - { - char c = cookiesChars[i]; - - switch (state) - { - case MAYBEVERSION: - if (c != ' ') - { - token.append(c); - if (c == '$') - { - state = INVERSION; // RFC 2965 - } - else - // RFC 2109 - state = OLD_INNAME; - } - break; - case OLD_INNAME: - if (c == '=') - { - state = OLD_INVAL; - cookie_name = token.toString(); - token.setLength(0); - } - else if (c != ' ' || token.length() > 0) - token.append(c); - break; - // TODO introduce val_start. then quoted value and value - case OLD_INVAL: - if (quoted == false) - { - if (c == ';') - { - state = OLD_INNAME; - cookie_value = token.toString(); - token.setLength(0); - addCookie(cookie_name, cookie_value, null, null); - } - else if (c == '"' && token.length() == 0) - quoted = true; - else - token.append(c); - } - else - { - if (c == '"') - quoted = false; - else - token.append(c); - } - break; - case INVERSION: - if (c == '=') - { - if ("$Version".equals(token.toString())) - state = INVERSIONNUM; - else - { - state = OLD_INVAL; // consider name starts with $ - cookie_name = token.toString(); - } - token.setLength(0); - } - else - token.append(c); - break; - case INVERSIONNUM: - if (c == ',' || c == ';') - { - token.setLength(0); - state = NEW_INNAME; - } - else if (Character.isDigit(c) == false) - { - state = RECOVER; - } - else - token.append(c); - break; - case NEW_INNAME: - if (c == '=') - { - state = NEW_INVAL; - cookie_name = token.toString(); - token.setLength(0); - } - else if (c != ' ' || token.length() > 0) - token.append(c); - break; - case NEW_INVAL: - if (c == ';') - { - state = MAYBEINPATH; - cookie_value = token.toString(); - token.setLength(0); - cookie_path = null; - } - else if (c == ',') - { - state = NEW_INNAME; - cookie_value = token.toString(); - token.setLength(0); - addCookie(cookie_name, cookie_value, null, null); - } - else - token.append(c); - break; - case MAYBEINPATH: - if (c != ' ') - { - token.append(c); - if (c == '$') - { - state = INPATH; - } - else - { - addCookie(cookie_name, cookie_value, null, null); - state = NEW_INNAME; - } - } - break; - case INPATH: - if (c == '=') - { - if ("$Path".equals(token.toString())) - state = INPATHVALUE; - else - { - addCookie(cookie_name, cookie_value, null, null); - state = NEW_INVAL; // consider name starts with $ - cookie_name = token.toString(); - } - token.setLength(0); - } - else - token.append(c); - break; - case INPATHVALUE: - if (c == ',') - { - cookie_path = token.toString(); - state = NEW_INNAME; - addCookie(cookie_name, cookie_value, cookie_path, null); - token.setLength(0); - } - else if (c == ';') - { - state = MAYBEDOMAIN; - cookie_path = token.toString(); - token.setLength(0); - } - else - token.append(c); - break; - case MAYBEDOMAIN: - if (c != ' ') - { - token.append(c); - if (c == '$') - { - state = INDOMAIN; - } - else - { - addCookie(cookie_name, cookie_value, cookie_path, null); - state = NEW_INNAME; - } - } - break; - case INDOMAIN: - if (c == '=') - { - if ("$Domain".equals(token.toString())) - state = INDOMAINVALUE; - else - { - addCookie(cookie_name, cookie_value, cookie_path, null); - state = NEW_INVAL; // consider name starts with $ - cookie_name = token.toString(); - } - token.setLength(0); - } - break; - case INDOMAINVALUE: - if (c == ',') - { - state = NEW_INNAME; - addCookie(cookie_name, cookie_value, cookie_path, token.toString()); - token.setLength(0); - } - else if (c == ';') - { - cookie_domain = token.toString(); - state = MAYBEPORT; - } - else - token.append(c); - break; - case MAYBEPORT: - if (c != ' ') - { - token.append(c); - if (c == '$') - { - state = INPORT; - } - else - { - addCookie(cookie_name, cookie_value, cookie_path, cookie_domain); - state = NEW_INNAME; - } - } - break; - case INPORT: - if (c == '=') - { - if ("$Port".equals(token.toString())) - state = INPORTVALUE; - else - { - addCookie(cookie_name, cookie_value, cookie_path, cookie_domain); - state = NEW_INVAL; // consider name starts with $ - cookie_name = token.toString(); - } - token.setLength(0); - } - break; - case INPORTVALUE: - if (c == ',' || c == ';') - { - int port = Integer.parseInt(token.toString()); - state = NEW_INNAME; - addCookie(cookie_name, cookie_value, cookie_path, cookie_domain); - token.setLength(0); - } - else if (Character.isDigit(c) == false) - { - state = RECOVER; - } - else - token.append(c); - break; - case RECOVER: - serve.log("Parsing recover of cookie string " + cookies, null); - if (c == ';' || c == ',') - { - token.setLength(0); - state = NEW_INNAME; - } - break; - } - } - if (state == OLD_INVAL || state == NEW_INVAL) - { - cookie_value = token.toString(); - addCookie(cookie_name, cookie_value, null, null); - } - else if (state == INPATHVALUE) - { - addCookie(cookie_name, cookie_value, token.toString(), null); - } - else if (state == INDOMAINVALUE) - { - addCookie(cookie_name, cookie_value, cookie_path, token.toString()); - } - else if (state == INPORTVALUE) - addCookie(cookie_name, cookie_value, cookie_path, cookie_domain); - } - catch (Error e) - { - serve.log("Error in parsing cookies: " + cookies, e); - } - catch (Exception e) - { - serve.log("An exception in parsing cookies: " + cookies, e); - } - } - - private void addCookie(String name, String value, String path, String domain) - { - if (SESSION_COOKIE_NAME.equals(name) && sessionCookieValue == null) - { - sessionCookieValue = value; - try - { - serve.getSession(sessionCookieValue).userTouch(); - sessionValue = sessionCookieValue; - sessionUrlValue = null; - } - catch (IllegalStateException ise) - { - sessionCookieValue = null; - } - catch (NullPointerException npe) - { - sessionCookieValue = null; - } - } - else - { - Cookie c; - inCookies.addElement(c = new Cookie(name, value)); - if (path != null) - { - c.setPath(path); - if (domain != null) - c.setDomain(domain); - } - } - } - - // Methods from ServletRequest. - - // / Returns the size of the request entity data, or -1 if not known. - // Same as the CGI variable CONTENT_LENGTH. - - public int getContentLength() - { - return getIntHeader(CONTENTLENGTH); - } - - // / Returns the MIME type of the request entity data, or null if - // not known. - // Same as the CGI variable CONTENT_TYPE. - public String getContentType() - { - return getHeader(CONTENTTYPE); - } - - // / Returns the protocol and version of the request as a string of - // the form /.. - // Same as the CGI variable SERVER_PROTOCOL. - public String getProtocol() - { - return reqProtocol; - } - - // / Returns the scheme of the URL used in this request, for example - // "http", "https", or "ftp". Different schemes have different rules - // for constructing URLs, as noted in RFC 1738. The URL used to create - // a request may be reconstructed using this scheme, the server name - // and port, and additional information such as URIs. - public String getScheme() - { - if (scheme == null) - // lazy stuf dlc - synchronized (this) - { - if (scheme == null) - scheme = socket.getClass().getName().indexOf("SSLSocket") > 0 ? "https" : "http"; - } - return scheme; - } - - // / Returns the host name of the server as used in the part of - // the request URI. - // Same as the CGI variable SERVER_NAME. - public String getServerName() - { - String serverName; - serverName = getHeader(HOST); - if (serverName != null && serverName.length() > 0) - { - int colon = serverName.indexOf(':'); - if (colon >= 0) - { - if (colon < serverName.length()) - serverName = serverName.substring(0, colon); - } - } - - if (serverName == null) - { - try - { - serverName = InetAddress.getLocalHost().getHostName(); - } - catch (java.net.UnknownHostException ignore) - { - serverName = "127.0.0.0"; - } - } - - int slash = serverName.indexOf("/"); - if (slash >= 0) - serverName = serverName.substring(slash + 1); - return serverName; - } - - // / Returns the port number on which this request was received as used - // in - // the part of the request URI. - // Same as the CGI variable SERVER_PORT. - public int getServerPort() - { - return socket.getLocalPort(); - } - - // / Returns the IP address of the agent that sent the request. - // Same as the CGI variable REMOTE_ADDR. - public String getRemoteAddr() - { - return socket.getInetAddress().getHostAddress(); - } - - // / Returns the fully qualified host name of the agent that sent the - // request. - // Same as the CGI variable REMOTE_HOST. - public String getRemoteHost() - { - String result = socket.getInetAddress().getHostName(); - return result != null ? result : getRemoteAddr(); - } - - // / Applies alias rules to the specified virtual path and returns the - // corresponding real path, or null if the translation can not be - // performed for any reason. For example, an HTTP servlet would - // resolve the path using the virtual docroot, if virtual hosting is - // enabled, and with the default docroot otherwise. Calling this - // method with the string "/" as an argument returns the document root. - public String getRealPath(String path) - { - return serve.getRealPath(path); - } - - // / Returns an input stream for reading request data. - // @exception IllegalStateException if getReader has already been called - // @exception IOException on other I/O-related errors - public ServletInputStream getInputStream() throws IOException - { - synchronized (in) - { - if (((ServeInputStream) in).isReturnedAsReader()) - throw new IllegalStateException("Already returned as a reader."); - ((ServeInputStream) in).setReturnedAsStream(true); - } - return in; - } - - // / Returns a buffered reader for reading request data. - // @exception UnsupportedEncodingException if the character set encoding - // isn't supported - // @exception IllegalStateException if getInputStream has already been - // called - // @exception IOException on other I/O-related errors - public BufferedReader getReader() - { - synchronized (in) - { - if (((ServeInputStream) in).isReturnedAsStream()) - throw new IllegalStateException("Already returned as a stream."); - ((ServeInputStream) in).setReturnedAsReader(true); - } - if (charEncoding != null) - try - { - return new BufferedReader(new InputStreamReader(in, charEncoding)); - } - catch (UnsupportedEncodingException uee) - { - } - return new BufferedReader(new InputStreamReader(in)); - } - - private synchronized Map getParametersFromRequest() - { - Map result = null; - if ("GET".equals(reqMethod)) - { - if (reqQuery != null) - try - { - result = Acme.Utils.parseQueryString(reqQuery, charEncoding); - } - catch (IllegalArgumentException ex) - { - serve.log("Exception " + ex + " at parsing 'get' data " + reqQuery); - } - } - else if ("POST".equals(reqMethod)) - { - String contentType = getContentType(); - if (contentType != null && WWWFORMURLENCODE.regionMatches(true, 0, contentType, 0, WWWFORMURLENCODE.length())) - { - if (postCache == null) - { - postCache = new String[1]; - InputStream is = null; - try - { - result = Acme.Utils.parsePostData(getContentLength(), is = getInputStream(), charEncoding, - postCache); - } - catch (Exception ex) - { - serve.log("Exception " + ex + " at parsing 'POST' data of length " + getContentLength()); - // TODO propagate the exception ? - return EMPTYHASHTABLE; - } - } - else - result = Acme.Utils.parseQueryString(postCache[0], charEncoding); - if (reqQuery != null && reqQuery.length() > 0) - result.putAll(Acme.Utils.parseQueryString(reqQuery, charEncoding)); - } - else if (reqQuery != null) - result = Acme.Utils.parseQueryString(reqQuery, charEncoding); - } - return result != null ? result : EMPTYHASHTABLE; - } - - // / Returns the parameter names for this request. - public synchronized Enumeration getParameterNames() - { - if (formParameters == null) - formParameters = getParametersFromRequest(); - return ((Hashtable) formParameters).keys(); - } - - // / Returns the value of the specified query string parameter, or null - // if not found. - // @param name the parameter name - public String getParameter(String name) - { - String[] params = getParameterValues(name); - if (params == null || params.length == 0) - return null; - - return params[0]; - } - - // / Returns the values of the specified parameter for the request as an - // array of strings, or null if the named parameter does not exist. - public synchronized String[] getParameterValues(String name) - { - if (formParameters == null) - getParameterNames(); - - return (String[]) formParameters.get(name); - } - - // / Returns the value of the named attribute of the request, or null if - // the attribute does not exist. This method allows access to request - // information not already provided by the other methods in this - // interface. - public Object getAttribute(String name) - { - // System.err.println("!!!Get att orig:"+name+"="+attributes.get(name)); - return attributes.get(name); - } - - // Methods from HttpServletRequest. - - // / Gets the array of cookies found in this request. - - public Cookie[] getCookies() - { - Cookie[] cookieArray = new Cookie[inCookies.size()]; - inCookies.copyInto(cookieArray); - return cookieArray; - } - - // / Returns the method with which the request was made. This can be - // "GET", - // "HEAD", "POST", or an extension method. - // Same as the CGI variable REQUEST_METHOD. - public String getMethod() - { - return reqMethod; - } - - /** - * **************************************************************************************************************************************************** - * Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request. To reconstruct an URL - * with a scheme and host, use HttpUtils.getRequestURL(javax.servlet.http.HttpServletRequest). - */ - // / Returns the full request URI. - public String getRequestURI() - { - return reqUriPathUn; - } - - /** - * Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port number, and server path, but it - * does not include query string parameters.
- * Because this method returns a StringBuffer, not a string, you can modify the URL easily, for example, to append query parameters. - *

- * This method is useful for creating redirect messages and for reporting errors. - * - * @return a StringBuffer object containing the reconstructed URL - * @since 2.3 - */ - public StringBuffer getRequestURL() - { - int port = getServerPort(); - return new StringBuffer().append(getScheme()).append("://").append(getServerName()).append( - "https".equals(getScheme()) && port == 443 || port == 80 ? "" : ":" + String.valueOf(port)).append( - getRequestURI()); - } - - // / Returns the part of the request URI that referred to the servlet - // being - // invoked. - // Analogous to the CGI variable SCRIPT_NAME. - public String getServletPath() - { - // In this server, the entire path is regexp-matched against the - // servlet pattern, so there's no good way to distinguish which - // part refers to the servlet. - return uriLen > 0 ? reqUriPath.substring(0, uriLen) : ""; - } - - // / Returns optional extra path information following the servlet path, - // but - // immediately preceding the query string. Returns null if not - // specified. - // Same as the CGI variable PATH_INFO. - public String getPathInfo() - { - // In this server, the entire path is regexp-matched against the - // servlet pattern, so there's no good way to distinguish which - // part refers to the servlet. - return uriLen >= reqUriPath.length() ? null : reqUriPath.substring(uriLen); - } - - // / Returns extra path information translated to a real path. Returns - // null if no extra path information was specified. - // Same as the CGI variable PATH_TRANSLATED. - public String getPathTranslated() - { - // In this server, the entire path is regexp-matched against the - // servlet pattern, so there's no good way to distinguish which - // part refers to the servlet. - return getRealPath(getPathInfo()); - } - - // / Returns the query string part of the servlet URI, or null if not - // known. - // Same as the CGI variable QUERY_STRING. - public String getQueryString() - { - return reqQuery; - } - - // / Returns the name of the user making this request, or null if not - // known. - // Same as the CGI variable REMOTE_USER. - public String getRemoteUser() - { - return remoteUser; - } - - // / Returns the authentication scheme of the request, or null if none. - // Same as the CGI variable AUTH_TYPE. - public String getAuthType() - { - return authType; - } - - // / Returns the value of a header field, or null if not known. - // Same as the information passed in the CGI variabled HTTP_*. - // @param name the header field name - public String getHeader(String name) - { - int i = reqHeaderNames.indexOf(name.toLowerCase()); - if (i == -1) - return null; - return (String) reqHeaderValues.elementAt(i); - } - - public int getIntHeader(String name) - { - String val = getHeader(name); - if (val == null) - return -1; - return Integer.parseInt(val); - } - - public long getDateHeader(String name) - { - String val = getHeader(name); - if (val == null) - return -1; - try - { - return headerdateformat.parse(val).getTime(); - } - catch (ParseException pe) - { - try - { - return rfc850DateFmt.parse(val).getTime(); - } - catch (ParseException pe1) - { - try - { - return asciiDateFmt.parse(val).getTime(); - } - catch (ParseException pe3) - { - throw new IllegalArgumentException("Value " + val - + " can't be converted to Date using any of formats: [" + headerdateformat.toPattern() - + "][ " + rfc850DateFmt.toPattern() + "][" + asciiDateFmt.toPattern()); - } - } - } - } - - // / Returns an Enumeration of the header names. - public Enumeration getHeaderNames() - { - return reqHeaderNames.elements(); - } - - // / Gets the current valid session associated with this request, if - // create is false or, if necessary, creates a new session for the - // request, if create is true. - //

- // Note: to ensure the session is properly maintained, the servlet - // developer must call this method (at least once) before any output - // is written to the response. - //

- // Additionally, application-writers need to be aware that newly - // created sessions (that is, sessions for which HttpSession.isNew - // returns true) do not have any application-specific state. - public synchronized HttpSession getSession(boolean create) - { - HttpSession result = null; - if (sessionValue != null) - { - result = serve.getSession(sessionValue); - if (result != null && ((AcmeSession) result).isValid() == false) - { - serve.removeSession(sessionValue); - result = null; - } - //System.err.println("^^^^^^^req sess: "+sessionValue+", found:"+result); - } - if (result == null && create) - { - result = serve.createSession(); - if (result != null) - { - sessionValue = result.getId(); - } - else - throw new RuntimeException("A session can't be created"); - //System.err.println("^~~~~~created: "+sessionValue); - } - return result; - } - - // JSDK 2.1 - public HttpSession getSession() - { - return getSession(true); - } - - public boolean isRequestedSessionIdFromURL() - { - return isRequestedSessionIdFromUrl(); - } - - // from ServletRequest - public Enumeration getAttributeNames() - { - return attributes.keys(); - } - - /** - * Stores an attribute in this request. Attributes are reset between requests. - * This method is most often used in conjunction with RequestDispatcher. - *

Attribute names should follow the same conventions as package names. - * Names beginning with java.*, javax.*, and com.sun.*, are reserved for - * use by Sun Microsystems. If the object passed in is null, the effect is - * the same as calling removeAttribute(java.lang.String). - *

- * It is warned that when the request is dispatched from the servlet resides - * in a different web application by RequestDispatcher, the object set by - * this method may not be correctly retrieved in the caller servlet. - * - * @param name - a String specifying the name of the attribute - * @param o - the Object to be stored - */ - public void setAttribute(String key, Object o) - { - //System.err.println("!!!Set att orig:"+key+"="+o); - //if ("javax.servlet.jsp.jspException".equals(key) && o instanceof Throwable) - //((Throwable)o).printStackTrace(); - - if (o != null) - attributes.put(key, o); - else - attributes.remove(key); - } - - // / Gets the session id specified with this request. This may differ - // from the actual session id. For example, if the request specified - // an id for an invalid session, then this will get a new session with - // a new id. - public String getRequestedSessionId() - { - return sessionValue; - } - - // / Checks whether this request is associated with a session that is - // valid in the current session context. If it is not valid, the - // requested session will never be returned from the getSession - // method. - public boolean isRequestedSessionIdValid() - { - if (sessionValue != null) - { - AcmeSession session = serve.getSession(sessionValue); - return (session != null && session.isValid()); - } - return false; - } - - /** - * Checks whether the session id specified by this request came in as a cookie. (The requested session may not be one returned by the getSession - * method.) - */ - public boolean isRequestedSessionIdFromCookie() - { - return sessionCookieValue != null; - } - - // / Checks whether the session id specified by this request came in as - // part of the URL. (The requested session may not be the one returned - // by the getSession method.) - public boolean isRequestedSessionIdFromUrl() - { - return sessionUrlValue != null; - } - - // Methods from ServletResponse. - - // / Sets the content length for this response. - // @param length the content length - - public void setContentLength(int length) - { - if (length >= 0) - setIntHeader(CONTENTLENGTH, length); - else - setHeader(CONTENTLENGTH, null); - } - - // / Sets the content type for this response. - // @param type the content type - public void setContentType(String type) - { - setHeader(CONTENTTYPE, type != null ? type : "Unknown"); - } - - // / Returns an output stream for writing response data. - public ServletOutputStream getOutputStream() - { - synchronized (out) - { - if (rout == null) - { - if (pw != null) - throw new IllegalStateException("Already returned as a writer"); - rout = out; - } - } - return rout; - } - - // / Returns a print writer for writing response data. The MIME type of - // the response will be modified, if necessary, to reflect the character - // encoding used, through the charset=... property. This means that the - // content type must be set before calling this method. - // @exception UnsupportedEncodingException if no such encoding can be - // provided - // @exception IllegalStateException if getOutputStream has been called - // @exception IOException on other I/O errors - public PrintWriter getWriter() throws IOException - { - synchronized (out) - { - if (pw == null) - { - if (rout != null) - throw new IllegalStateException("Already was returned as servlet output stream"); - String encoding = getCharacterEncoding(); - if (encoding != null) - pw = new PrintWriter(new OutputStreamWriter(out, encoding)); - else - pw = new PrintWriter(out); - } - } - return pw; - } - - // / Returns the character set encoding used for this MIME body. The - // character encoding is either the one specified in the assigned - // content type, or one which the client understands. If no content - // type has yet been assigned, it is implicitly set to text/plain. - public String getCharacterEncoding() - { - String ct = (String) resHeaderNames.get(CONTENTTYPE.toLowerCase()); - if (ct != null) - { - String enc = extractEncodingFromContentType(ct); - if (enc != null) - return enc; - } - return charEncoding; - } - - private String extractEncodingFromContentType(String ct) - { - if (ct == null) - return null; - int scp = ct.indexOf(';'); - if (scp > 0) - { - scp = ct.toLowerCase().indexOf("charset=", scp); - if (scp >= 0) - { - ct = ct.substring(scp + "charset=".length()).trim(); - scp = ct.indexOf(';'); - if (scp > 0) - ct = ct.substring(0, scp); - int l = ct.length(); - if (l > 2 && ct.charAt(0) == '"') - return ct.substring(1, l - 1); - return ct; - } - } - return null; - } - - // 2.2 - // do not use buffer - public void flushBuffer() throws IOException - { - ((ServeOutputStream) out).flush(); - } - - /** - * Clears the content of the underlying buffer in the response without clearing headers or status code. If the response has been committed, this method - * throws an IllegalStateException. - * - * @since 2.3 - */ - public void resetBuffer() - { - ((ServeOutputStream) out).reset(); - synchronized (this) - { - headersWritten = false; - } - } - - public int getBufferSize() - { - return ((ServeOutputStream) out).getBufferSize(); - } - - public void setBufferSize(int size) - { - ((ServeOutputStream) out).setBufferSize(size); - } - - /** - * Returns a boolean indicating if the response has been committed. A commited response has already had its status code and headers written. - * - * @return a boolean indicating if the response has been committed - * @see setBufferSize(int), getBufferSize(), flushBuffer(), reset() - */ - // a caller should think about syncronization - public boolean isCommitted() - { - return headersWritten && ((ServeOutputStream) out).lengthWritten() > 0; - } - - /** - * Clears any data that exists in the buffer as well as the status code and headers. If the response has been committed, this method throws an - * IllegalStateException. - * - * @throws IllegalStateException - * - - * if the response has already been committed - * @see setBufferSize(int), getBufferSize(), flushBuffer(), isCommitted() - */ - public void reset() throws IllegalStateException - { - // new Exception("RESET").printStackTrace(); - if (!isCommitted()) - { - if (outCookies != null) - outCookies.clear(); - resHeaderNames.clear(); - pw = null; - rout = null; - ((ServeOutputStream) out).reset(); - assureHeaders(); - } - else - throw new IllegalStateException("Header have already been committed."); - } - - /** - * Sets the locale of the response, setting the headers (including the Content-Type's charset) as appropriate. This method should be called before a - * call to getWriter(). By default, the response locale is the default locale for the server. - * - * @param loc - - * the locale of the response - * @see getLocale() - */ - public void setLocale(Locale locale) - { - this.locale = locale; - } - - /** - * For request: Returns the preferred Locale that the client will accept content in, based on the Accept-Language header. If the client request doesn't - * provide an Accept-Language header, this method returns the default locale for the server. - *

- * For response: Returns the locale specified for this response using the setLocale(java.util.Locale) method. Calls made to setLocale after the response - * is committed have no effect. If no locale has been specified, the container's default locale is returned. - */ - public Locale getLocale() - { - if (locale != null) - return locale; - Enumeration e = getLocales(); - if (e.hasMoreElements()) - return (Locale) e.nextElement(); - return Locale.getDefault(); - } - - /** - * Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the - * client based on the Accept-Language header. If the client request doesn't provide an Accept-Language header, this method returns an Enumeration - * containing one Locale, the default locale for the server. - */ - public Enumeration getLocales() - { - // TODO: cache result - String al = getHeader(ACCEPT_LANGUAGE); - TreeSet ts = new TreeSet(); - if (al != null) - { - // System.err.println("Accept lang:"+al); - StringTokenizer st = new StringTokenizer(al, ";", false); - try - { - while (st.hasMoreTokens()) - { - String langs = st.nextToken(";"); - // System.err.println("Langs:"+langs); - String q = st.nextToken(";="); - // System.err.println("q:"+q); - q = st.nextToken("=,"); - // System.err.println("q:"+q); - float w = 0; - try - { - w = Float.valueOf(q).floatValue(); - } - catch (NumberFormatException nfe) - { - } - if (w > 0) - { - StringTokenizer lst = new StringTokenizer(langs, ", ", false); - while (lst.hasMoreTokens()) - { - String lan = lst.nextToken(); - int di = lan.indexOf('-'); - if (di < 0) - ts.add(new LocaleWithWeight(new Locale(lan.trim()) /* 1.4 */, w)); - else - ts.add(new LocaleWithWeight(new Locale(lan.substring(0, di), lan.substring(di + 1) - .trim().toUpperCase()), w)); - } - } - } - } - catch (NoSuchElementException ncee) - { - // can't parse - } - } - if (ts.size() == 0) - ts.add(new LocaleWithWeight(Locale.getDefault(), 1)); - return new AcceptLocaleEnumeration(ts); - } - - /** - * Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or - * reading input using getReader(). - * - * @param a - - * String containing the name of the chararacter encoding. - * @throws java.io.UnsupportedEncodingException - * - - * if this is not a valid encoding - * @since JSDK 2.3 - */ - public void setCharacterEncoding(String _enc) - { - // TODO: check if encoding is valid - charEncoding = _enc; - synchronized (this) - { - formParameters = null; - } - } - - public void addDateHeader(String header, long date) - { - addHeader(header, headerdateformat.format(new Date(date))); - } - - public void addHeader(String header, String value) - { - header = header.trim().toLowerCase(); - Object o = resHeaderNames.get(header); - if (o == null) - setHeader(header, value); - else - { - if (o instanceof String[]) - { - String[] oldVal = (String[]) o; - String[] newVal = new String[oldVal.length + 1]; - System.arraycopy(oldVal, 0, newVal, 0, oldVal.length); - newVal[oldVal.length] = value; - resHeaderNames.put(header, newVal); - } - else if (o instanceof String) - { - String[] newVal = new String[2]; - newVal[0] = (String) o; - newVal[1] = value; - resHeaderNames.put(header, newVal); - } - else - throw new RuntimeException("Invalid content of header hash - " + o.getClass().getName()); - } - } - - public void addIntHeader(String header, int value) - { - addHeader(header, Integer.toString(value)); - } - - public RequestDispatcher getRequestDispatcher(String urlpath) - { - if (urlpath.length() > 0 && urlpath.charAt(0) != '/') - { - String dispatchPath = getContextPath(); - String pathInfo = getPathInfo(); - String servletPath = getServletPath(); - ; - if (pathInfo != null) - { - dispatchPath += servletPath; - int slp = pathInfo.indexOf('/', 1); - if (slp > 0) // can it ever happen? - dispatchPath += pathInfo.substring(0, slp - 1); - } - else - { - int spsp = servletPath.lastIndexOf('/'); - if (spsp >= 0) - dispatchPath += servletPath.substring(0, spsp); - } - // serve.log("Dispatch path:"+dispatchPath); - urlpath = dispatchPath + '/' + urlpath; - } - return serve.getRequestDispatcher(urlpath); - } - - public boolean isSecure() - { - return "https".equals(getScheme()); - } - - public void removeAttribute(String name) - { - attributes.remove(name); - } - - // only root context supported - public String getContextPath() - { - return ""; - } - - public Enumeration getHeaders(String header) - { - Vector result = new Vector(); - int i = -1; - while ((i = reqHeaderNames.indexOf(header.toLowerCase(), i + 1)) >= 0) - result.addElement(reqHeaderValues.elementAt(i)); - return result.elements(); - } - - public java.security.Principal getUserPrincipal() - { - return null; - } - - public boolean isUserInRole(String user) - { - return false; - } - - /** - * Returns a java.util.Map of the parameters of this request. Request parameters are extra information sent with the request. For HTTP servlets, - * parameters are contained in the query string or posted form data. - * - * @return an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type - * String. The values in the parameter map are of type String array. - * @since 2.3 - */ - public synchronized Map getParameterMap() - { - if (formParameters == null) - getParameterNames(); - return formParameters; - } - - // Methods from HttpServletResponse. - - // / Adds the specified cookie to the response. It can be called - // multiple times to set more than one cookie. - - public void addCookie(Cookie cookie) - { - if (outCookies == null) - outCookies = new Vector(); - - outCookies.addElement(cookie); - } - - // / Checks whether the response message header has a field with the - // specified name. - public boolean containsHeader(String name) - { - return resHeaderNames.contains(name); - } - - // JSDK 2.1 extension - public String encodeURL(String url) - { - int uop = url.indexOf(SESSION_URL_NAME); - // TODO not robust enough - if (uop > 0) - url = url.substring(0, uop); - if (sessionValue == null || isRequestedSessionIdFromCookie()) - return url; - try - { - new URL(url); // for testing syntac - int ehp = url.indexOf('/'); - if (ehp < 0) - ehp = url.indexOf('?'); - if (ehp < 0) - ehp = url.indexOf('#'); - if (ehp < 0) - ehp = url.length(); - if (url.regionMatches(true, 0, getRequestURL().toString(), 0, ehp) == false) - return url; - } - catch (MalformedURLException e) - { - } - - return url + SESSION_URL_NAME + sessionValue; - } - - public String encodeRedirectURL(String url) - { - return encodeURL(url); - } - - /** - * Returns the Internet Protocol (IP) source port of the client or last proxy that sent the request. - * - * @return an integer specifying the port number - * @since 2.4 - */ - public int getRemotePort() - { - return socket.getPort(); // TODO not quite robust - } - - /** - * Returns the host name of the Internet Protocol (IP) interface on which the request was received. - * - * @return a String containing the host name of the IP on which the request was received. - * @since 2.4 - */ - public String getLocalName() - { - InetAddress ia = socket/* serve.serverSocket */.getLocalAddress(); - return ia == null ? null : ia.getHostAddress(); - } - - /** - * Returns the Internet Protocol (IP) address of the interface on which the request was received. - * - * @return a String containing the IP address on which the request was received. - * @since 2.4 - */ - public String getLocalAddr() - { - InetAddress ia = /* serve.serverSocket */socket.getLocalAddress(); - return ia == null ? null : ia.getCanonicalHostName(); /* 1.4 */ - } - - /** - * Returns the Internet Protocol (IP) port number of the interface on which the request was received. - * - * @return an integer specifying the port number - * @since 2.4 - */ - public int getLocalPort() - { - return getServerPort(); - } - - // / Sets the status code and message for this response. - // @param resCode the status code - // @param resMessage the status message - public void setStatus(int resCode, String resMessage) - { - // if (((ServeOutputStream) out).isInInclude()) - // return; - this.resCode = resCode; - this.resMessage = resMessage; - } - - // / Sets the status code and a default message for this response. - // @param resCode the status code - public void setStatus(int resCode) - { - switch (resCode) - { - case SC_CONTINUE: - setStatus(resCode, "Continue"); - break; - case SC_SWITCHING_PROTOCOLS: - setStatus(resCode, "Switching protocols"); - break; - case SC_OK: - setStatus(resCode, "Ok"); - break; - case SC_CREATED: - setStatus(resCode, "Created"); - break; - case SC_ACCEPTED: - setStatus(resCode, "Accepted"); - break; - case SC_NON_AUTHORITATIVE_INFORMATION: - setStatus(resCode, "Non-authoritative"); - break; - case SC_NO_CONTENT: - setStatus(resCode, "No content"); - break; - case SC_RESET_CONTENT: - setStatus(resCode, "Reset content"); - break; - case SC_PARTIAL_CONTENT: - setStatus(resCode, "Partial content"); - break; - case SC_MULTIPLE_CHOICES: - setStatus(resCode, "Multiple choices"); - break; - case SC_MOVED_PERMANENTLY: - setStatus(resCode, "Moved permanentently"); - break; - case SC_MOVED_TEMPORARILY: - setStatus(resCode, "Moved temporarily"); - break; - case SC_SEE_OTHER: - setStatus(resCode, "See other"); - break; - case SC_NOT_MODIFIED: - setStatus(resCode, "Not modified"); - break; - case SC_USE_PROXY: - setStatus(resCode, "Use proxy"); - break; - case SC_BAD_REQUEST: - setStatus(resCode, "Bad request"); - break; - case SC_UNAUTHORIZED: - setStatus(resCode, "Unauthorized"); - break; - case SC_PAYMENT_REQUIRED: - setStatus(resCode, "Payment required"); - break; - case SC_FORBIDDEN: - setStatus(resCode, "Forbidden"); - break; - case SC_NOT_FOUND: - setStatus(resCode, "Not found"); - break; - case SC_METHOD_NOT_ALLOWED: - setStatus(resCode, "Method not allowed"); - break; - case SC_NOT_ACCEPTABLE: - setStatus(resCode, "Not acceptable"); - break; - case SC_PROXY_AUTHENTICATION_REQUIRED: - setStatus(resCode, "Proxy auth required"); - break; - case SC_REQUEST_TIMEOUT: - setStatus(resCode, "Request timeout"); - break; - case SC_CONFLICT: - setStatus(resCode, "Conflict"); - break; - case SC_GONE: - setStatus(resCode, "Gone"); - break; - case SC_LENGTH_REQUIRED: - setStatus(resCode, "Length required"); - break; - case SC_PRECONDITION_FAILED: - setStatus(resCode, "Precondition failed"); - break; - case SC_REQUEST_ENTITY_TOO_LARGE: - setStatus(resCode, "Request entity too large"); - break; - case SC_REQUEST_URI_TOO_LONG: - setStatus(resCode, "Request URI too long"); - break; - case SC_UNSUPPORTED_MEDIA_TYPE: - setStatus(resCode, "Unsupported media type"); - break; - case SC_INTERNAL_SERVER_ERROR: - setStatus(resCode, "Internal server error"); - break; - case SC_NOT_IMPLEMENTED: - setStatus(resCode, "Not implemented"); - break; - case SC_BAD_GATEWAY: - setStatus(resCode, "Bad gateway"); - break; - case SC_SERVICE_UNAVAILABLE: - setStatus(resCode, "Service unavailable"); - break; - case SC_GATEWAY_TIMEOUT: - setStatus(resCode, "Gateway timeout"); - break; - case SC_HTTP_VERSION_NOT_SUPPORTED: - setStatus(resCode, "HTTP version not supported"); - break; - case 207: - setStatus(resCode, "Multi Status"); - break; - default: - setStatus(resCode, ""); - break; - } - } - - // / Sets the value of a header field. - // @param name the header field name - // @param value the header field value - public void setHeader(String header, String value) - { - header = header.trim().toLowerCase(); // normilize header - if (value == null) - resHeaderNames.remove(header); - else - { - resHeaderNames.put(header, value); - //if (header.equals(CONTENTTYPE)) { - // String enc = extractEncodingFromContentType(value); - // if (enc != null) - // setCharacterEncoding(enc); - //} - } - } - - // / Sets the value of an integer header field. - // @param name the header field name - // @param value the header field integer value - public void setIntHeader(String header, int value) - { - setHeader(header, Integer.toString(value)); - } - - // / Sets the value of a long header field. - // @param name the header field name - // @param value the header field long value - public void setLongHeader(String header, long value) - { - setHeader(header, Long.toString(value)); - } - - // / Sets the value of a date header field. - // @param name the header field name - // @param value the header field date value - public void setDateHeader(String header, long value) - { - setHeader(header, headerdateformat.format(new Date(value))); - } - - // / Writes the status line and message headers for this response to the - // output stream. - // @exception IOException if an I/O error has occurred - void writeHeaders() throws IOException - { - synchronized (this) - { - // TODO: possible to write trailer when chunked out, - // so chunked out should be global flag - if (headersWritten) - return; - - headersWritten = true; - } - if (reqMime) - { - boolean chunked_out = false; - boolean wasContentLen = false; - if (resMessage.length() < 256) - out.println(reqProtocol + " " + resCode + " " + resMessage.replace('\r', '/').replace('\n', '/')); - else - out.println(reqProtocol + " " + resCode + " " - + resMessage.substring(0, 255).replace('\r', '/').replace('\n', '/')); - Enumeration he = resHeaderNames.keys(); - while (he.hasMoreElements()) - { - String name = (String) he.nextElement(); - Object o = resHeaderNames.get(name); - if (o instanceof String) - { - String value = (String) o; - if (value != null) - {// just in case - out.println(name + ": " + value); - if (wasContentLen == false) - if (CONTENTLENGTH.equals(name)) - try - { - wasContentLen = Long.parseLong(value) > 0; - } - catch (NumberFormatException nfe) - { - } - if (chunked_out == false) - if (TRANSFERENCODING.equals(name) && CHUNKED.equals(value)) - chunked_out = true; - } - } - else if (o instanceof String[]) - { - String[] values = (String[]) o; - out.print(name + ": " + values[0]); - for (int i = 1; i < values.length; i++) - out.print("," + values[i]); - out.println(); - } - } - StringBuffer sb = null; - StringBuffer sb2 = null; - Cookie cc = null; - // add session cookie - if (sessionValue != null) - { - HttpSession session = serve.getSession(sessionValue); - if (session != null) - { - if (((AcmeSession) session).isValid()) - { - if (session.isNew()) - { - cc = new Cookie(SESSION_COOKIE_NAME, sessionValue); - if (serve.expiredIn < 0) - cc.setMaxAge(Math.abs(serve.expiredIn) * 60); - ServletContext sc = ((AcmeSession) session).getServletContext(); - try - { - String cp = (String) sc.getClass().getMethod("getContextPath", Utils.EMPTY_CLASSES) - .invoke(sc, Utils.EMPTY_OBJECTS); - if (cp.length() == 0) - cp = "/"; - cc.setPath(cp); - } - catch (Exception e) - { - - } - - addCookie(cc); - } - } - else - { - cc = new Cookie(SESSION_COOKIE_NAME, ""); - cc.setMaxAge(0); - addCookie(cc); - } - } - } - - // how to remove a cookie - // cc = new Cookie(cookieName, ""); - // cc.setMaxAge(0); - // - for (int i = 0; outCookies != null && i < outCookies.size(); i++) - { - cc = (Cookie) outCookies.elementAt(i); - if (cc.getSecure() && isSecure() == false) - continue; - int version = cc.getVersion(); - String token; - if (version > 1) - { - if (sb2 == null) - sb2 = new StringBuffer(SETCOOKIE + "2: "); - else - sb2.append(','); - sb2.append(cc.getName()); - sb2.append("=\""); - sb2.append(cc.getValue()).append('"'); - token = cc.getComment(); - if (token != null) - sb2.append("; Comment=\"").append(token).append('"'); - token = cc.getDomain(); - if (token != null) - sb2.append("; Domain=\"").append(token).append('"'); - if (cc.getMaxAge() >= 0) - sb2.append("; Max-Age=\"").append(cc.getMaxAge()).append('"'); - token = cc.getPath(); - if (token != null) - sb2.append("; Path=\"").append(token).append('"'); - if (cc.getSecure()) - { - sb2.append("; Secure"); - } - sb2.append("; Version=\"").append(version).append('"'); - } - else - { - if (sb == null) - sb = new StringBuffer(SETCOOKIE + ": "); - else - //sb.append(','); - sb.append("\r\n" + SETCOOKIE + ": "); // for IE not - sb.append(cc.getName()); - sb.append('='); - sb.append(cc.getValue());//.append('"'); - if (cc.getDomain() != null && cc.getDomain().length() > 0) - { - sb.append("; domain=" + cc.getDomain()); - } - if (cc.getMaxAge() >= 0) - { - sb.append("; expires="); - sb.append(expdatefmt.format(new Date(new Date().getTime() + 1000l * cc.getMaxAge()))); - } - if (cc.getPath() != null && cc.getPath().length() > 0) - { - sb.append("; path=" + cc.getPath()); - } - if (cc.getSecure()) - { - sb.append("; secure"); - } - } - } - if (sb != null) - { - out.println(sb.toString()); - //System.err.println("We sent cookies: " + sb); - } - if (sb2 != null) - { - out.println(sb2.toString()); - //System.err.println("We sent cookies 2: " + sb2); - } - // Test for existence of message body - if (containsBody() && wasContentLen == false && chunked_out == false && serve.isKeepAlive()) - { - out.println(TRANSFERENCODING + ": " + CHUNKED); - chunked_out = true; - } - out.println(); - out.flush(); - ((ServeOutputStream) out).setChunked(chunked_out); - } - } - - private boolean containsBody() - { - return !("HEAD".equalsIgnoreCase(reqMethod) || (100 <= resCode && resCode < 200) || resCode == 204 || resCode == 304); - } - - // / Writes an error response using the specified status code and - // message. - // @param resCode the status code - // @param resMessage the status message - // @exception IOException if an I/O error has occurred - public void sendError(int resCode, String resMessage) throws IOException - { - setStatus(resCode, resMessage); - realSendError(); - } - - // / Writes an error response using the specified status code and a - // default - // message. - // @param resCode the status code - // @exception IOException if an I/O error has occurred - public void sendError(int resCode) throws IOException - { - setStatus(resCode); - realSendError(); - } - - public void setInInclude(boolean set) - { - ((ServeOutputStream) out).setInInclude(set); - } - - private void realSendError() throws IOException - { - if (isCommitted()) - throw new IllegalStateException("Can not send an error, headers have been already written"); - // if (((ServeOutputStream) out).isInInclude()) // ignore - // return; - setContentType("text/html"); - StringBuffer sb = new StringBuffer(100); - int lsp = resMessage.indexOf('\n'); - sb.append("").append( - "" + resCode + " " + (lsp < 0 ? resMessage : resMessage.substring(0, lsp)) + "") - .append("

" + resCode + " " + (lsp < 0 ? resMessage : resMessage.substring(0, lsp)) + "

"); - if (lsp > 0) - sb.append("
").append(Utils.htmlEncode(resMessage.substring(lsp), false)).append("
"); - sb.append("
"); - sb.append(Identification.serverIdHtml); - sb.append(""); - setContentLength(sb.length()); - out.print(sb.toString()); - closeStreams(); - } - - // / Sends a redirect message to the client using the specified redirect - // location URL. - // @param location the redirect location URL - // @exception IOException if an I/O error has occurred - public void sendRedirect(String location) throws IOException - { - if (isCommitted()) - throw new IllegalStateException("Can not redirect, headers have been already written"); - if (location.indexOf(":/") < 0) - { // relative - String portString = ""; - if ("https".equalsIgnoreCase(getScheme())) - { - if (getServerPort() != 443) - portString = ":" + getServerPort(); - } - else if (getServerPort() != 80) - portString = ":" + getServerPort(); - - if (location.length() > 0 && location.charAt(0) == '/') - { - location = getScheme() + "://" + getServerName() + portString + location; - } - else - { - int sp = reqUriPathUn.lastIndexOf('/'); - String uri; - if (sp < 0) - { - uri = reqUriPathUn + '/'; - sp = uri.length(); - } - else - { - uri = reqUriPathUn; - sp++; - } - location = getScheme() + "://" + getServerName() + portString + uri.substring(0, sp) + location; - } - } - // serve.log("location:"+location); - setHeader("Location", location); - setStatus(SC_MOVED_TEMPORARILY); - setContentType("text/html"); - StringBuffer sb = new StringBuffer(200); - sb.append("" + "" + SC_MOVED_TEMPORARILY + " Moved" + "

" + SC_MOVED_TEMPORARILY + " Moved

" + "This document has moved here.
"); - sb.append(Identification.serverIdHtml); - sb.append(""); - setContentLength(sb.length()); - // to avoid further out - out.print(sb.toString()); - closeStreams(); - } - - // URL session-encoding stuff. Not implemented, but the API is here - // for compatibility. - - // / Encodes the specified URL by including the session ID in it, or, if - // encoding is not needed, returns the URL unchanged. The - // implementation of this method should include the logic to determine - // whether the session ID needs to be encoded in the URL. For example, - // if the browser supports cookies, or session tracking is turned off, - // URL encoding is unnecessary. - //

- // All URLs emitted by a Servlet should be run through this method. - // Otherwise, URL rewriting cannot be used with browsers which do not - // support cookies. - // @deprecated - - public String encodeUrl(String url) - { - return encodeURL(url); - } - - // / Encodes the specified URL for use in the sendRedirect method or, if - // encoding is not needed, returns the URL unchanged. The - // implementation of this method should include the logic to determine - // whether the session ID needs to be encoded in the URL. Because the - // rules for making this determination differ from those used to - // decide whether to encode a normal link, this method is seperate - // from the encodeUrl method. - //

- // All URLs sent to the HttpServletResponse.sendRedirect method should - // be - // run through this method. Otherwise, URL rewriting cannot be used with - // browsers which do not support cookies. - public String encodeRedirectUrl(String url) - { - return encodeRedirectURL(url); - } - - public Socket getSocket() - { - // TODO apply security check - return socket; - } - } - - protected static class BasicAuthRealm extends Hashtable - { - String name; - - BasicAuthRealm(String name) - { - this.name = name; - } - - String name() - { - return name; - } - } - - public static class ServeInputStream extends ServletInputStream - { - private final static boolean STREAM_DEBUG = false; - - /** - * The actual input stream (buffered). - */ - private InputStream in, origIn; - - private ServeConnection conn; - - private int chunksize = 0; - - private boolean chunking = false, compressed; - - private boolean returnedAsReader, returnedAsStream; - - private long contentLength = -1; - - private long readCount; - - private byte[] oneReadBuf = new byte[1]; - - private boolean closed; - - /* ------------------------------------------------------------ */ - /** - * Constructor - */ - public ServeInputStream(InputStream in, ServeConnection conn) - { - this.conn = conn; - this.in = new BufferedInputStream(in); - } - - void refresh() - { - returnedAsReader = false; - returnedAsStream = false; - contentLength = -1; - readCount = 0; - chunksize = 0; - closed = false; - compressed(false); - } - - /* ------------------------------------------------------------ */ - /** - * @param chunking - */ - public void chunking(boolean chunking) - { - if (contentLength == -1) - this.chunking = chunking; - } - - boolean compressed(boolean on) - { - if (on) - { - if (compressed == false) - { - origIn = in; - try - { - ServeInputStream sis = new ServeInputStream(in, conn); - if (chunking) - { - sis.chunking(true); - chunking(false); - } - in = (InputStream) conn.serve.gzipInStreamConstr.newInstance(new Object[]{sis}); - compressed = true; - //conn.serve.log("Compressed stream was created with success", null); - } - catch (Exception ex) - { - if (ex instanceof InvocationTargetException) - conn.serve.log("Problem in compressed stream creation", ((InvocationTargetException) ex).getTargetException()); - else - conn.serve.log("Problem in compressed stream obtaining", ex); - } - } - } - else if (compressed) - { - compressed = false; - in = origIn; - } - return compressed; - } - - /** - * sets max read byte in input - */ - void setContentLength(long contentLength) - { - if (this.contentLength == -1 && contentLength >= 0 && chunking == false) - { - this.contentLength = contentLength; - readCount = 0; - } - } - - /* ------------------------------------------------------------ */ - /** - * Read a line ended by CRLF, used internally only for reading headers. - * No char encoding, ASCII only - */ - protected String readLine(int maxLen) throws IOException - { - if (maxLen <= 0) - throw new IllegalArgumentException("Max len:" + maxLen); - StringBuffer buf = new StringBuffer(Math.min(1024, maxLen)); - - int c; - boolean cr = false; - int i = 0; - while ((c = in.read()) != -1) - { - if (c == 10) - { // LF - if (cr) - break; - break; - //throw new IOException ("LF without CR"); - } - else if (c == 13) // CR - cr = true; - else - { - //if (cr) - //throw new IOException ("CR without LF"); - // see http://www.w3.org/Protocols/HTTP/1.1/rfc2616bis/draft-lafon-rfc2616bis-03.html#tolerant.applications - cr = false; - if (i >= maxLen) - throw new IOException("Line lenght exceeds " + maxLen); - buf.append((char) c); - i++; - } - } - if (STREAM_DEBUG) - System.err.println(buf); - if (c == -1 && buf.length() == 0) - return null; - - return buf.toString(); - } - - /* ------------------------------------------------------------ */ - public int read() throws IOException - { - int result = read(oneReadBuf, 0, 1); - if (result == 1) - return 255 & oneReadBuf[0]; - return -1; - } - - /* ------------------------------------------------------------ */ - public int read(byte b[]) throws IOException - { - return read(b, 0, b.length); - } - - /* ------------------------------------------------------------ */ - public synchronized int read(byte b[], int off, int len) throws IOException - { - if (closed) - throw new IOException("The stream is already closed"); - if (chunking) - { - if (chunksize <= 0 && getChunkSize() <= 0) - return -1; - if (len > chunksize) - len = chunksize; - len = in.read(b, off, len); - chunksize = (len < 0) ? -1 : (chunksize - len); - } - else - { - if (contentLength >= 0) - { - if (contentLength - readCount < Integer.MAX_VALUE) - - len = Math.min(len, (int) (contentLength - readCount)); - if (len <= 0) - { - if (STREAM_DEBUG) - System.err.print("EOF"); - return -1; - } - len = in.read(b, off, len); - if (len > 0) - readCount += len; - } - else - // to avoid extra if - len = in.read(b, off, len); - } - if (STREAM_DEBUG && len > 0) - System.err.print(new String(b, off, len)); - - return len; - } - - /* ------------------------------------------------------------ */ - public long skip(long len) throws IOException - { - if (STREAM_DEBUG) - System.err.println("instream.skip() :" + len); - if (closed) - throw new IOException("The stream is already closed"); - if (chunking) - { - if (chunksize <= 0 && getChunkSize() <= 0) - return -1; - if (len > chunksize) - len = chunksize; - len = in.skip(len); - chunksize = (len < 0) ? -1 : (chunksize - (int) len); - } - else - { - if (contentLength >= 0) - { - len = Math.min(len, contentLength - readCount); - if (len <= 0) - return -1; - len = in.skip(len); - readCount += len; - } - else - len = in.skip(len); - } - return len; - } - - /* ------------------------------------------------------------ */ - /** - * Available bytes to read without blocking. If you are unlucky may return 0 when there are more - */ - public int available() throws IOException - { - if (STREAM_DEBUG) - System.err.println("instream.available()"); - if (closed) - throw new IOException("The stream is already closed"); - if (chunking) - { - int len = in.available(); - if (len <= chunksize) - return len; - return chunksize; - } - - if (contentLength >= 0) - { - int len = in.available(); - if (contentLength - readCount < Integer.MAX_VALUE) - return Math.min(len, (int) (contentLength - readCount)); - return len; - } - else - return in.available(); - } - - /* ------------------------------------------------------------ */ - public void close() throws IOException - { - // keep alive, will be closed by socket - // in.close(); - if (STREAM_DEBUG) - System.err.println("instream.close() " + closed); - if (closed) - return; //throw new IOException("The stream is already closed"); - // read until end of chunks or content length - if (chunking) - while (read() >= 0) ; - else if (contentLength < 0) ; - else - { - long skipCount = contentLength - readCount; - while (skipCount > 0) - { - long skipped = skip(skipCount); - if (skipped <= 0) - break; - skipCount -= skipped; - } - } - if (conn.keepAlive == false) - in.close(); - closed = true; - } - - /* ------------------------------------------------------------ */ - /** - * Mark is not supported - * - * @return false - */ - public boolean markSupported() - { - return false; - } - - /* ------------------------------------------------------------ */ - /** - * - */ - public void reset() throws IOException - { - // no buffering, so not possible - if (closed) - throw new IOException("The stream is already closed"); - if (STREAM_DEBUG) - System.err.println("instream.reset()"); - in.reset(); - } - - /* ------------------------------------------------------------ */ - /** - * Not Implemented - * - * @param readlimit - */ - public void mark(int readlimit) - { - // not supported - if (STREAM_DEBUG) - System.err.println("instream.mark(" + readlimit + ")"); - } - - /* ------------------------------------------------------------ */ - private int getChunkSize() throws IOException - { - if (chunksize < 0) - return -1; - - chunksize = -1; - - // Get next non blank line - chunking = false; - String line = readLine(60); - while (line != null && line.length() == 0) - line = readLine(60); - chunking = true; - - // Handle early EOF or error in format - if (line == null) - return -1; - - // Get chunksize - int i = line.indexOf(';'); - if (i > 0) - line = line.substring(0, i).trim(); - try - { - chunksize = Integer.parseInt(line, 16); - } - catch (NumberFormatException nfe) - { - throw new IOException("Chunked stream is broken, " + line); - } - - // check for EOF - if (chunksize == 0) - { - chunksize = -1; - // Look for footers - readLine(60); - chunking = false; - } - return chunksize; - } - - boolean isReturnedAsStream() - { - return returnedAsStream; - } - - void setReturnedAsStream(boolean _on) - { - returnedAsStream = _on; - } - - boolean isReturnedAsReader() - { - return returnedAsReader; - } - - void setReturnedAsReader(boolean _on) - { - returnedAsReader = _on; - } - } - - public static class ServeOutputStream extends ServletOutputStream - { - - private static final boolean STREAM_DEBUG = false; - - private boolean chunked; - - private boolean closed; - - // TODO: predefine as static byte[] used by chunked - // underneath stream - private OutputStream out; - - // private BufferedWriter writer; // for top speed - private ServeConnection conn; - - private int inInclude; - - private String encoding; - - private/*volatile*/ long lbytes; - - private Utils.SimpleBuffer buffer; - - public ServeOutputStream(OutputStream out, ServeConnection conn) - { - this.out = out; - this.conn = conn; - buffer = new Utils.SimpleBuffer(); - encoding = conn.getCharacterEncoding(); - if (encoding == null) - encoding = Utils.ISO_8859_1; - } - - void refresh() - { - chunked = false; - closed = false; - inInclude = 0; - lbytes = 0; - buffer.reset(); - encoding = conn.getCharacterEncoding(); - if (encoding == null) - encoding = Utils.ISO_8859_1; - } - - protected void reset() - { - if (lbytes == 0) - buffer.reset(); - else - throw new IllegalStateException("Result was already committed"); - } - - protected int getBufferSize() - { - return buffer.getSize(); - } - - protected void setBufferSize(int size) - { - if (lbytes > 0) - throw new IllegalStateException("Bytes already written in response"); - buffer.setSize(size); - } - - protected void setChunked(boolean set) - { - chunked = set; - } - - public void print(String s) throws IOException - { - write(s.getBytes(encoding)); - } - - public void write(int b) throws IOException - { - write(new byte[]{(byte) b}, 0, 1); - } - - public void write(byte[] b) throws IOException - { - write(b, 0, b.length); - } - - public void write(byte[] b, int off, int len) throws IOException - { - if (closed) - { - if (STREAM_DEBUG) - System.err.println((b == null ? "null" : new String(b, off, len)) + "\n won't be written, stream closed."); - throw new IOException("An attempt of writing " + len + " bytes to a closed out."); - } - - if (len == 0) - return; - // - conn.writeHeaders(); - b = buffer.put(b, off, len); - len = b.length; - if (len == 0) - return; - off = 0; - if (chunked) - { - String hexl = Integer.toHexString(len); - out.write((hexl + "\r\n").getBytes()); // no encoding Ok - lbytes += 2 + hexl.length(); - out.write(b, off, len); - lbytes += len; - out.write("\r\n".getBytes()); - lbytes += 2; - } - else - { - out.write(b, off, len); - lbytes += len; - } - - if (STREAM_DEBUG) - { - if (chunked) - System.err.println(Integer.toHexString(len)); - System.err.print(new String(b, off, len)); - if (chunked) - System.err.println(); - } - } - - public void flush() throws IOException - { - if (closed) - return; - // throw new IOException("An attempt of flushig closed out."); - conn.writeHeaders(); - byte[] b = buffer.get(); - if (b.length > 0) - { - if (chunked) - { - String hexl = Integer.toHexString(b.length); - out.write((hexl + "\r\n").getBytes()); // no encoding Ok - lbytes += 2 + hexl.length(); - out.write(b); - lbytes += b.length; - out.write("\r\n".getBytes()); - lbytes += 2; - if (STREAM_DEBUG) - { - System.err.println(hexl); - System.err.print(new String(b)); - System.err.println(); - } - } - else - { - out.write(b); - lbytes += b.length; - if (STREAM_DEBUG) - { - System.err.print(new String(b)); - } - } - } - out.flush(); - } - - public void close() throws IOException - { - if (closed) - return; - // throw new IOException("Stream is already closed."); - // new IOException("Stream closing").printStackTrace(); - try - { - flush(); - if (inInclude == 0) - { - if (chunked) - { - out.write("0\r\n\r\n".getBytes()); - lbytes += 5; - if (STREAM_DEBUG) - System.err.print("0\r\n\r\n"); - // TODO: here is possible to write trailer headers - out.flush(); - } - if (conn.keepAlive == false) - out.close(); - } - } - finally - { - closed = true; - } - } - - private long lengthWritten() - { - return lbytes; - } - - boolean isInInclude() - { - return inInclude == 0; - } - - void setInInclude(boolean _set) - { - inInclude = _set ? 1 : 0; - /*if (_set) - inInclude++; - else - inInclude--; - if (inInclude < 0) - throw new IllegalStateException("Not matching include set");*/ - } - } - - /** - * Class PathTreeDictionary - this class allows to put path elements in format n1/n2/n2[/*.ext] and get match to a pattern and a unmatched tail - */ - public static class PathTreeDictionary - { - Node root_node; - - public PathTreeDictionary() - { - root_node = new Node(); - } - - public synchronized void put(String path, Object value) - { - StringTokenizer st = new StringTokenizer(path, "\\/"); - Node cur_node = root_node; - while (st.hasMoreTokens()) - { - String nodename = st.nextToken(); - Node node = (Node) cur_node.get(nodename); - if (node == null) - { - node = new Node(); - cur_node.put(nodename, node); - } - cur_node = node; - } - cur_node.object = value; - } - - public synchronized Object[] remove(Object value) - { - return remove(root_node, value); - } - - public synchronized Object[] remove(String path) - { - Object[] result = get(path); - if (result[1] != null) - return remove(result[1]); - return result; - } - - public Object[] remove(Node node, Object value) - { - // TODO make full path, not only last element - Enumeration e = node.keys(); - while (e.hasMoreElements()) - { - String path = (String) e.nextElement(); - Node childNode = (Node) node.get(path); - if (childNode.object == value) - {// it's safe because the same instance can't be shared for several paths in this design - childNode.object = null; - return new Object[]{value, new Integer(0)}; - } - Object[] result = remove(childNode, value); - if (result[0] != null) - return result; - } - - return new Object[]{null, null}; - } - - /** - * This function looks up in the directory to find the perfect match and remove matching part from path, so if you need to keep original path, save it - * somewhere - */ - public Object[] get(String path) - { - Object[] result = new Object[2]; - if (path == null) - return result; - char[] ps = path.toCharArray(); - Node cur_node = root_node; - int p0 = 0, lm = 0; // last match - result[0] = cur_node.object; - boolean div_state = true; - for (int i = 0; i < ps.length; i++) - { - if (ps[i] == '/' || ps[i] == '\\') - { - if (div_state) - continue; - Node node = (Node) cur_node.get(new String(ps, p0, i - p0)); - if (node == null) - { - result[1] = new Integer(lm); - return result; - } - if (node.object != null) - { - result[0] = node.object; - lm = i; - } - cur_node = node; - div_state = true; - } - else - { - if (div_state) - { - p0 = i; - div_state = false; - } - } - } - cur_node = (Node) cur_node.get(new String(ps, p0, ps.length - p0)); - if (cur_node != null && cur_node.object != null) - { - result[0] = cur_node.object; - lm = ps.length; - } - result[1] = new Integer(lm); - return result; - } - - public Enumeration keys() - { - Vector result = new Vector(); - addSiblingNames(root_node, result, ""); - return result.elements(); - } - - public void addSiblingNames(Node node, Vector result, String path) - { - Enumeration e = node.keys(); - while (e.hasMoreElements()) - { - String pc = (String) e.nextElement(); - Node childNode = (Node) node.get(pc); - pc = path + '/' + pc; - if (childNode.object != null) - result.addElement(pc); - addSiblingNames(childNode, result, pc); - } - } - - public Enumeration elements() - { - Vector result = new Vector(); - addSiblingObjects(root_node, result); - return result.elements(); - } - - public void addSiblingObjects(Node node, Vector result) - { - Enumeration e = node.keys(); - while (e.hasMoreElements()) - { - Node childNode = (Node) node.get(e.nextElement()); - if (childNode.object != null) - result.addElement(childNode.object); - addSiblingObjects(childNode, result); - } - } - - class Node extends Hashtable - { - Object object; - } - } - - /** - * Http session support - *

- * TODO: provide lazy session restoring, it should allow to load classes from wars 1st step it read serialization data and store under session attribute 2nd - * when the session requested, it tries to deserialize all session attributes considered that all classes available - */ - public static class AcmeSession extends Hashtable implements HttpSession - { - private long createTime; - - private long lastAccessTime; - - private String id; - - private int inactiveInterval; // in seconds - - private boolean expired; - - private transient ServletContext servletContext; - - private transient HttpSessionContext sessionContext; - - private transient List listeners; - - // TODO: check in documentation what is default inactive interval and - // what - // means 0 - // and what is mesurement unit - AcmeSession(String id, ServletContext servletContext, HttpSessionContext sessionContext) - { - this(id, 0, servletContext, sessionContext); - } - - AcmeSession(String id, int inactiveInterval, ServletContext servletContext, HttpSessionContext sessionContext) - { - // new Exception("Session created with: "+servletContext).printStackTrace(); //!!! - createTime = System.currentTimeMillis(); - this.id = id; - this.inactiveInterval = inactiveInterval; - this.servletContext = servletContext; - this.sessionContext = sessionContext; - } - - public long getCreationTime() - { - return createTime; - } - - public String getId() - { - return id; - } - - public long getLastAccessedTime() - { - return lastAccessTime; - } - - public void setMaxInactiveInterval(int interval) - { - inactiveInterval = interval; - } - - public int getMaxInactiveInterval() - { - return inactiveInterval; - } - - /** - * @deprecated - */ - public HttpSessionContext getSessionContext() - { - return sessionContext; - } - - /** - * Returns the ServletContext to which this session belongs. - * - * @return The ServletContext object for the web application - * @ince 2.3 - */ - public ServletContext getServletContext() - { - // System.err.println("ctx from:"+servletContext); //!!! - return servletContext; - } - - public Object getAttribute(String name) throws IllegalStateException - { - if (expired) - throw new IllegalStateException(); - return get((Object) name); - } - - public Object getValue(String name) throws IllegalStateException - { - return getAttribute(name); - } - - public Enumeration getAttributeNames() throws IllegalStateException - { - if (expired) - throw new IllegalStateException(); - return keys(); - } - - public String[] getValueNames() throws IllegalStateException - { - Enumeration e = getAttributeNames(); - Vector names = new Vector(); - while (e.hasMoreElements()) - names.addElement(e.nextElement()); - String[] result = new String[names.size()]; - names.copyInto(result); - return result; - } - - public void setAttribute(String name, Object value) throws IllegalStateException - { - if (expired) - throw new IllegalStateException(); - Object oldValue = value != null ? put((Object) name, value) : remove(name); - if (oldValue != null) - if (oldValue instanceof HttpSessionBindingListener) - ((HttpSessionBindingListener) oldValue).valueUnbound(new HttpSessionBindingEvent(this, name)); - else if (oldValue instanceof HttpSessionAttributeListener) - ((HttpSessionAttributeListener) oldValue).attributeReplaced(new HttpSessionBindingEvent(this, name, - value)); - if (value instanceof HttpSessionBindingListener) - ((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name)); - else if (value instanceof HttpSessionAttributeListener) - ((HttpSessionAttributeListener) value).attributeAdded(new HttpSessionBindingEvent(this, name)); - } - - public void putValue(String name, Object value) throws IllegalStateException - { - setAttribute(name, value); - } - - public void removeAttribute(String name) throws IllegalStateException - { - if (expired) - throw new IllegalStateException(); - Object value = remove((Object) name); - if (value != null) - if (value instanceof HttpSessionBindingListener) - ((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name)); - else if (value instanceof HttpSessionAttributeListener) - ((HttpSessionAttributeListener) value).attributeRemoved(new HttpSessionBindingEvent(this, name)); - } - - public void removeValue(String name) throws IllegalStateException - { - removeAttribute(name); - } - - public synchronized void invalidate() throws IllegalStateException - { - if (expired) - throw new IllegalStateException(); - notifyListeners(); - Enumeration e = getAttributeNames(); - while (e.hasMoreElements()) - { - removeAttribute((String) e.nextElement()); - } - setExpired(true); - // would be nice remove it from hash table also - } - - public boolean isNew() throws IllegalStateException - { - if (expired) - throw new IllegalStateException(); - return lastAccessTime == 0; - } - - public synchronized void setListeners(List l) - { - if (listeners == null) - { - listeners = l; - if (listeners != null) - { - HttpSessionEvent event = new HttpSessionEvent(this); - for (int i = 0; i < listeners.size(); i++) - try - { - ((HttpSessionListener) listeners.get(0)).sessionCreated(event); - } - catch (ClassCastException cce) - { - // log("Wrong session listener type."+cce); - } - catch (NullPointerException npe) - { - // log("Null session listener."); - } - } - } - } - - /** - * something hack, to update servlet context since session created out of scope - * - * @param sc - */ - public synchronized void setServletContext(ServletContext sc) - { - // System.err.println("ctx to:"+servletContext); //!!! - servletContext = sc; - } - - private void notifyListeners() - { - if (listeners != null) - { - HttpSessionEvent event = new HttpSessionEvent(this); - for (int i = 0; i < listeners.size(); i++) - try - { - ((HttpSessionListener) listeners.get(i)).sessionDestroyed(event); - } - catch (ClassCastException cce) - { - // log("Wrong session listener type."+cce); - } - catch (NullPointerException npe) - { - // log("Null session listener."); - } - } - } - - private void setExpired(boolean expired) - { - this.expired = expired; - } - - boolean isValid() - { - return !expired; - } - - boolean checkExpired() - { - return inactiveInterval > 0 && (inactiveInterval * 1000 < System.currentTimeMillis() - lastAccessTime); - } - - void userTouch() - { - if (isValid()) - lastAccessTime = System.currentTimeMillis(); - else - throw new IllegalStateException(); - } - - // storing session in format - // id:latency:contextname:tttt - // entry:base64 ser data - // entry:base64 ser data - // $$ - void save(Writer w) throws IOException - { - if (expired) - return; - // can't use append because old JDK - w.write(id); - w.write(':'); - w.write(Integer.toString(inactiveInterval)); - w.write(':'); - w.write(servletContext == null || servletContext.getServletContextName() == null ? "" : servletContext - .getServletContextName()); - w.write(':'); - w.write(Long.toString(lastAccessTime)); - w.write("\r\n"); - Enumeration e = getAttributeNames(); - ByteArrayOutputStream os = new ByteArrayOutputStream(1024 * 16); - while (e.hasMoreElements()) - { - String aname = (String) e.nextElement(); - Object so = get(aname); - if (so instanceof Serializable) - { - os.reset(); - ObjectOutputStream oos = new ObjectOutputStream(os); - try - { - oos.writeObject(so); - w.write(aname); - w.write(":"); - w.write(Utils.base64Encode(os.toByteArray())); - w.write("\r\n"); - } - catch (IOException ioe) - { - servletContext.log("Problem storing a session value of " + aname, ioe); - } - } - else - servletContext.log("Non serializable object " + so.getClass().getName() + " skiped in storing of " + aname, null); - if (so instanceof HttpSessionActivationListener) - ((HttpSessionActivationListener) so).sessionWillPassivate(new HttpSessionEvent(this)); - } - w.write("$$\r\n"); - } - - static AcmeSession restore(BufferedReader r, int inactiveInterval, ServletContext servletContext, - HttpSessionContext sessionContext) throws IOException - { - String s = r.readLine(); - if (s == null) // eos - return null; - int cp = s.indexOf(':'); - if (cp < 0) - throw new IOException("Invalid format for a session header, no session id: " + s); - String id = s.substring(0, cp); - int cp2 = s.indexOf(':', cp + 1); - if (cp2 < 0) - throw new IOException("Invalid format for a session header, no latency: " + s); - try - { - inactiveInterval = Integer.parseInt(s.substring(cp + 1, cp2)); - } - catch (NumberFormatException nfe) - { - servletContext.log("Session latency is invalid:" + s.substring(cp + 1, cp2) + " " + nfe); - } - cp = s.indexOf(':', cp2 + 1); - if (cp < 0) - throw new IOException("Invalid format for a session header, context name: " + s); - String contextName = s.substring(cp2 + 1, cp); - // consider servletContext.getContext("/"+contextName) - AcmeSession result = new AcmeSession(id, inactiveInterval, contextName.length() == 0 ? servletContext - : null, sessionContext); - try - { - result.lastAccessTime = Long.parseLong(s.substring(cp + 1)); - } - catch (NumberFormatException nfe) - { - servletContext.log("Last access time is invalid:" + s.substring(cp + 1) + " " + nfe); - } - do - { - s = r.readLine(); - if (s == null) - throw new IOException("Unexpected end of a stream."); - if ("$$".equals(s)) - return result; - cp = s.indexOf(':'); - if (cp < 0) - throw new IOException("Invalid format for a session entry: " + s); - String aname = s.substring(0, cp); - // if (lazyRestore) - // result.put(aname, s.substring(cp+1)); - ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(Utils.decode64(s - .substring(cp + 1)))); - Throwable restoreError; - try - { - Object so; - result.put(aname, so = ois.readObject()); - restoreError = null; - if (so instanceof HttpSessionActivationListener) - ((HttpSessionActivationListener) so).sessionDidActivate(new HttpSessionEvent(result)); - - } - catch (ClassNotFoundException cnfe) - { - restoreError = cnfe; - - } - catch (NoClassDefFoundError ncdfe) - { - restoreError = ncdfe; - } - catch (IOException ioe) - { - restoreError = ioe; - } - if (restoreError != null) - servletContext.log("Can't restore :" + aname + ", " + restoreError); - } while (true); - } - } - - protected static class LocaleWithWeight implements Comparable - { - protected float weight; // should be int - - protected Locale locale; - - LocaleWithWeight(Locale l, float w) - { - locale = l; - weight = w; - // System.err.println("Created "+l+", with:"+w); - } - - public int compareTo(Object o) - { - if (o instanceof LocaleWithWeight) - return (int) (((LocaleWithWeight) o).weight - weight) * 100; - throw new IllegalArgumentException(); - } - - public Locale getLocale() - { - return locale; - } - } - - protected static class AcceptLocaleEnumeration implements Enumeration - { - Iterator i; - - public AcceptLocaleEnumeration(TreeSet/* */ts) - { - i = ts.iterator(); - } - - public boolean hasMoreElements() - { - return i.hasNext(); - } - - public Object nextElement() - { - return ((LocaleWithWeight) i.next()).getLocale(); - /* - * Locale l =((LocaleWithWeight)i.next()).getLocale(); System.err.println("Returned l:"+l); return l; - */ - } - } - - // TODO: reconsider implementation by providing - // inner class implementing HttpSessionContext - // and returning it on request - // to avoid casting this class to Hashtable - - protected static class HttpSessionContextImpl extends Hashtable implements HttpSessionContext - { - - public Enumeration getIds() - { - return keys(); - } - - public HttpSession getSession(String sessionId) - { - return (HttpSession) get(sessionId); - } - - void save(Writer w) throws IOException - { - Enumeration e = elements(); - while (e.hasMoreElements()) - ((AcmeSession) e.nextElement()).save(w); - } - - static HttpSessionContextImpl restore(BufferedReader br, int inactiveInterval, ServletContext servletContext) - throws IOException - { - HttpSessionContextImpl result = new HttpSessionContextImpl(); - AcmeSession session; - while ((session = AcmeSession.restore(br, inactiveInterval, servletContext, result)) != null) - if (session.checkExpired() == false) - result.put(session.getId(), session); - return result; - } - } -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java index a4bc90fa0c9b..92d259907db4 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/DubboHttpServer.java @@ -82,8 +82,7 @@ protected ResteasyDeployment getDeployment() { private class RestHandler implements HttpHandler { public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - // use the below approach if we want to minimize the dependencies on resteasy's internal stuff - // RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); + RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); dispatcher.service(request, response); } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java index 35036e0753e8..3bbfadfb3954 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java @@ -22,10 +22,18 @@ import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; import com.alibaba.dubbo.rpc.protocol.ServiceImplHolder; +import org.apache.http.HeaderElement; +import org.apache.http.HeaderElementIterator; +import org.apache.http.HttpResponse; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; +import org.apache.http.message.BasicHeaderElementIterator; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; +import org.apache.http.protocol.HTTP; +import org.apache.http.protocol.HttpContext; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; @@ -34,8 +42,12 @@ import javax.ws.rs.ProcessingException; import javax.ws.rs.WebApplicationException; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; /** * @author lishen @@ -48,6 +60,11 @@ public class RestProtocol extends AbstractProxyProtocol { private final RestServerFactory serverFactory = new RestServerFactory(); + // TODO in the future maybe we can just use a single rest client and connection manager + private final List clients = Collections.synchronizedList(new LinkedList()); + + private volatile ConnectionMonitor connectionMonitor; + public RestProtocol() { super(WebApplicationException.class, ProcessingException.class); } @@ -84,24 +101,50 @@ public void run() { } protected T doRefer(Class serviceType, URL url) throws RpcException { + if (connectionMonitor == null) { + connectionMonitor = new ConnectionMonitor(); + } + // TODO more configs to add PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(); // 20 is the default maxTotal of current PoolingClientConnectionManager connectionManager.setMaxTotal(url.getParameter(Constants.CONNECTIONS_KEY, 20)); + connectionManager.setDefaultMaxPerRoute(url.getParameter(Constants.CONNECTIONS_KEY, 20)); + + connectionMonitor.addConnectionManager(connectionManager); // BasicHttpContext localContext = new BasicHttpContext(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager); + httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() { + public long getKeepAliveDuration(HttpResponse response, HttpContext context) { + HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); + while (it.hasNext()) { + HeaderElement he = it.nextElement(); + String param = he.getName(); + String value = he.getValue(); + if (value != null && param.equalsIgnoreCase("timeout")) { + return Long.parseLong(value) * 1000; + } + } + // TODO constant + return 30 * 1000; + } + }); + HttpParams params = httpClient.getParams(); // TODO currently no xml config for Constants.CONNECT_TIMEOUT_KEY so we directly reuse Constants.TIMEOUT_KEY for now HttpConnectionParams.setConnectionTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); HttpConnectionParams.setSoTimeout(params, url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + HttpConnectionParams.setTcpNoDelay(params, true); + HttpConnectionParams.setSoKeepalive(params, true); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient/*, localContext*/); ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); + clients.add(client); for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) { if (!StringUtils.isEmpty(clazz)) { @@ -125,6 +168,11 @@ protected int getErrorCode(Throwable e) { public void destroy() { super.destroy(); + + if (connectionMonitor != null) { + connectionMonitor.shutdown(); + } + for (Map.Entry entry : servers.entrySet()) { try { if (logger.isInfoEnabled()) { @@ -136,6 +184,18 @@ public void destroy() { } } servers.clear(); + + if (logger.isInfoEnabled()) { + logger.info("Closing rest clients"); + } + for (ResteasyClient client : clients) { + try { + client.close(); + } catch (Throwable t) { + logger.warn("Error closing rest client", t); + } + } + clients.clear(); } protected String getContextPath(URL url) { @@ -143,4 +203,38 @@ protected String getContextPath(URL url) { int pos = url.getPath().indexOf("/"); return pos > 0 ? url.getPath().substring(0, pos) : ""; } + + protected class ConnectionMonitor extends Thread { + private volatile boolean shutdown; + private final List connectionManagers = Collections.synchronizedList(new LinkedList()); + + public void addConnectionManager(ClientConnectionManager connectionManager) { + connectionManagers.add(connectionManager); + } + + public void run() { + try { + while (!shutdown) { + synchronized (this) { + wait(1000); + for (ClientConnectionManager connectionManager : connectionManagers) { + connectionManager.closeExpiredConnections(); + // TODO constant + connectionManager.closeIdleConnections(30, TimeUnit.SECONDS); + } + } + } + } catch (InterruptedException ex) { + shutdown(); + } + } + + public void shutdown() { + shutdown = true; + connectionManagers.clear(); + synchronized (this) { + notifyAll(); + } + } + } } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java index 54b26f71df79..0b7c9b38732c 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestServerFactory.java @@ -33,10 +33,10 @@ public void setHttpBinder(HttpBinder httpBinder) { public RestServer createServer(String name) { // TODO move names to Constants - if ("servlet".equalsIgnoreCase(name) || "jetty".equalsIgnoreCase(name)) { + if ("servlet".equalsIgnoreCase(name) || "jetty".equalsIgnoreCase(name) || "tomcat".equalsIgnoreCase(name)) { return new DubboHttpServer(httpBinder); - } else if ("tjws".equalsIgnoreCase(name)) { - return new TjwsServer(); +// } else if ("tjws".equalsIgnoreCase(name)) { +// return new TjwsServer(); } else if ("netty".equalsIgnoreCase(name)) { return new NettyServer(); } else if ("sunhttp".equalsIgnoreCase(name)) { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java index bfde8eb23b92..1de7403016be 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java @@ -29,6 +29,9 @@ public class RpcContextFilter implements ContainerRequestFilter { public void filter(ContainerRequestContext requestContext) throws IOException { + if (RpcContext.getContext().getRemoteAddress() != null) { + return; + } HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class); // this only works for servlet containers if (request != null) { diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/TjwsServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/TjwsServer.java index a8a765144d68..3a5e7c5a8a41 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/TjwsServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/TjwsServer.java @@ -16,7 +16,6 @@ package com.alibaba.dubbo.rpc.protocol.rest; import com.alibaba.dubbo.common.URL; -import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer; import org.jboss.resteasy.spi.ResteasyDeployment; /** @@ -24,20 +23,23 @@ */ public class TjwsServer extends BaseRestServer { - private final TJWSEmbeddedJaxrsServer server = new TJWSEmbeddedJaxrsServer(); +// private final TJWSEmbeddedJaxrsServer server = new TJWSEmbeddedJaxrsServer(); protected void doStart(URL url) { - server.setPort(url.getPort()); - // below config is useless due to a resteasy bug -// server.setKeepAlive(false); - server.start(); + throw new UnsupportedOperationException("TJWS server is now unsupported"); +// server.setPort(url.getPort()); +// // below config is useless due to a resteasy bug +//// server.setKeepAlive(false); +// server.start(); } protected ResteasyDeployment getDeployment() { - return server.getDeployment(); + throw new UnsupportedOperationException("TJWS server is now unsupported"); +// return server.getDeployment(); } public void stop() { - server.stop(); + throw new UnsupportedOperationException("TJWS server is now unsupported"); +// server.stop(); } } diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java index d20553d1163a..4b6eac4973e3 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java @@ -15,39 +15,54 @@ */ package com.alibaba.dubbo.rpc.protocol.rest; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.utils.StringUtils; +import io.undertow.Undertow; +import io.undertow.servlet.api.DeploymentInfo; +import org.jboss.resteasy.plugins.server.undertow.UndertowJaxrsServer; +import org.jboss.resteasy.spi.ResteasyDeployment; + /** - * TODO implement this after migrating to servlet 3.x api + * TODO this impl hasn't been well tested, and we can consider move undertow to a general remoting-http impl in the future * * @author lishen */ -public class UndertowServer /*implements RestServer*/ { - -// // NOTEUndertowJaxrsServer doesn't implement EmbeddedJaxrsServer -// private final UndertowJaxrsServer server = new UndertowJaxrsServer(); -// -// private final ResteasyDeployment deployment = new ResteasyDeployment(); -// -// public void start(String host, int port) { -// deployment.start(); -// DeploymentInfo deploymentInfo = server.undertowDeployment(deployment); -// deploymentInfo.setContextPath("/"); -// deploymentInfo.setDeploymentName("dubbo-rest"); -// deploymentInfo.setClassLoader(Thread.currentThread().getContextClassLoader()); -// server.start(Undertow.builder().addListener(port, host)); -// server.deploy(deploymentInfo); -//// server.start(); -// } -// -// public void deploy(Class resourceDef, Object resourceInstance) { -// deployment.getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef)); -// } -// -// public void undeploy(Class resourceDef) { -// -// } -// -// public void stop() { -// -// } +public class UndertowServer implements RestServer { + + // Note that UndertowJaxrsServer doesn't implement EmbeddedJaxrsServer + + private final ResteasyDeployment deployment = new ResteasyDeployment(); + + private final UndertowJaxrsServer server = new UndertowJaxrsServer(); + + public void start(URL url) { + deployment.start(); + DeploymentInfo deploymentInfo = server.undertowDeployment(deployment); + deploymentInfo.setContextPath("/"); + deploymentInfo.setDeploymentName("dubbo-rest"); + deploymentInfo.setClassLoader(Thread.currentThread().getContextClassLoader()); + server.deploy(deploymentInfo); + server.start(Undertow.builder().addHttpListener(url.getPort(), url.getHost())); + } + + public void deploy(Class resourceDef, Object resourceInstance, String contextPath) { + if (StringUtils.isEmpty(contextPath)) { + deployment.getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef)); + } else { + deployment.getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef), contextPath); + } + } + + public void undeploy(Class resourceDef) { + deployment.getRegistry().removeRegistrations(resourceDef); + } + + public void deploy(Class resourceDef, Object resourceInstance) { + deploy(resourceDef, resourceInstance, "/"); + } + public void stop() { + deployment.stop(); + server.stop(); + } } diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml index a4a7cee24299..1f0d25596062 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.0 + 2.8.1 dubbo-rpc-rmi jar diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml index 7ccecfec6f57..74383e6d8fbb 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ b/dubbo-rpc/dubbo-rpc-thrift/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.0 + 2.8.1 dubbo-rpc-thrift jar diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml index 4c0fba39f4ca..b2bbe1106f3e 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml +++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.0 + 2.8.1 dubbo-rpc-webservice jar diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 7a9fdce9bb39..47842b120b78 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-rpc pom diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml index 6c36b79684a9..4b836321576f 100644 --- a/dubbo-simple/dubbo-monitor-simple/pom.xml +++ b/dubbo-simple/dubbo-monitor-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.8.0 + 2.8.1 dubbo-monitor-simple jar @@ -104,7 +104,7 @@ javax.servlet - servlet-api + javax.servlet-api org.mortbay.jetty diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml index 72ad83501157..006a0f0a8949 100644 --- a/dubbo-simple/dubbo-registry-simple/pom.xml +++ b/dubbo-simple/dubbo-registry-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.8.0 + 2.8.1 dubbo-registry-simple jar diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml index 5e9f1b4ee566..aa02aef12a65 100644 --- a/dubbo-simple/pom.xml +++ b/dubbo-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-simple pom diff --git a/dubbo-test/dubbo-test-benchmark-api/pom.xml b/dubbo-test/dubbo-test-benchmark-api/pom.xml index 332a7cce7e6d..469d9815acc5 100644 --- a/dubbo-test/dubbo-test-benchmark-api/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-api/pom.xml @@ -4,7 +4,7 @@ com.alibaba dubbo-test - 2.8.0 + 2.8.1 dubbo-test-benchmark-api jar @@ -26,7 +26,7 @@ javax.servlet - servlet-api + javax.servlet-api \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark-client/pom.xml b/dubbo-test/dubbo-test-benchmark-client/pom.xml index ca7f1b842fee..c897513287ee 100644 --- a/dubbo-test/dubbo-test-benchmark-client/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-client/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.0 + 2.8.1 dubbo-test-benchmark-client jar @@ -110,7 +110,7 @@ javax.servlet - servlet-api + javax.servlet-api org.mortbay.jetty diff --git a/dubbo-test/dubbo-test-benchmark-server/pom.xml b/dubbo-test/dubbo-test-benchmark-server/pom.xml index 30eedf44fda9..be4b90c944da 100644 --- a/dubbo-test/dubbo-test-benchmark-server/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-server/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.0 + 2.8.1 dubbo-test-benchmark-server jar @@ -105,7 +105,7 @@ javax.servlet - servlet-api + javax.servlet-api org.mortbay.jetty diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml index b596f8b552e2..b2f0e8bcf9f5 100644 --- a/dubbo-test/dubbo-test-benchmark/pom.xml +++ b/dubbo-test/dubbo-test-benchmark/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.0 + 2.8.1 dubbo-test-benchmark jar diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml index fea3834bfc11..b0d5c3654e61 100644 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ b/dubbo-test/dubbo-test-compatibility/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.0 + 2.8.1 dubbo-test-compatibility jar diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index 97131c4448ff..100947be98dc 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.0 + 2.8.1 dubbo-test-examples jar diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml index be3430d192f3..5f87c82ffeac 100644 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ b/dubbo-test/dubbo-test-integration/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.0 + 2.8.1 dubbo-test-integration jar diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml index 9daa7682e074..5bee4af3bde9 100644 --- a/dubbo-test/pom.xml +++ b/dubbo-test/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo-test pom diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 8f997259b7cf..14dffbb533be 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 dubbo jar diff --git a/hessian-lite/pom.xml b/hessian-lite/pom.xml index 6c7e23f14304..01f71e0ad7e9 100644 --- a/hessian-lite/pom.xml +++ b/hessian-lite/pom.xml @@ -6,7 +6,7 @@ com.alibaba dubbo-parent - 2.8.0 + 2.8.1 hessian-lite jar diff --git a/pom.xml b/pom.xml index b7a25101c2e3..cd08452b7a85 100644 --- a/pom.xml +++ b/pom.xml @@ -20,7 +20,7 @@ 2.0 --> com.alibaba dubbo-parent - 2.8.0 + 2.8.1 pom ${project.artifactId} The parent project of dubbo @@ -103,7 +103,7 @@ 0.8.0 1.0.13 4.0.7 - 2.5 + 3.1.0 6.1.26 1.0.0.GA 4.2.0.Final @@ -128,8 +128,17 @@ ${file_encoding} - Copyright 1999-2012 Alibaba Group. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - oss + Copyright 1999-2012 Alibaba Group. Licensed under + the Apache License, Version 2.0 (the "License"); you + may not use this file except in compliance with the License. You + may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 Unless required + by applicable law or agreed to in writing, software distributed + under the License is distributed on an "AS IS" + BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + express or implied. See the License for the specific language + governing permissions and limitations under the License. + oss 2.3.2 @@ -255,7 +264,7 @@ javax.servlet - servlet-api + javax.servlet-api ${servlet_version} @@ -620,4 +629,16 @@ +8 + + + nexus-releases + Nexus Release Repository + http://10.255.209.180/nexus/content/repositories/releases/ + + + nexus-snapshots + Nexus Snapshot Repository + http://10.255.209.180/nexus/content/repositories/snapshots/ + + From 0c98d3c45a02d6d3a406b8a58834cc77c49d6be0 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 22 Oct 2014 09:39:16 +0800 Subject: [PATCH 111/200] change docs --- README.md | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 3904bf5e92c5..e96225ae3ee1 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,20 @@ Dubbox now means Dubbo eXtensions. If you know java, javax and dubbo, you know what dubbox is :) - -Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the popular [dubbo service framework](http://github.com/alibaba/dubbo). It鈥檚 now internally used by several projects of [dangdang.com](http://www.dangdang.com), which is one of the major e-commerce companies in China. -Contacts: shenli@dangdang.com, wangyuxuan@dangdang.com +Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the popular [dubbo service framework](http://github.com/alibaba/dubbo). It鈥檚 now internally used by several projects of [dangdang.com](http://www.dangdang.com), which is one of the major e-commerce companies in China. ### Dubbox褰撳墠鐨勪富瑕佸姛鑳斤細 -* **REST椋庢牸杩滅▼璋冪敤鏀寔 锛圚TTP + JSON/XML)**锛氬湪dubbo涓敮鎸佸熀浜嶩TTP + JSON/XML鐨勮繙绋嬭皟鐢紝浠ユ樉钁楃畝鍖栦紒涓氬唴閮ㄨ法璇█璋冪敤锛屽悓鏃舵樉钁楃畝鍖栧澶朞pen API銆佹棤绾緼PI鐢氳嚦娴忚鍣ˋJAX搴旂敤绛夌殑寮鍙戙 +* **鏀寔REST椋庢牸杩滅▼璋冪敤锛圚TTP + JSON/XML)**锛氬熀浜庨潪甯告垚鐔熺殑JBoss 锛籖estEasy锛斤紙http://resteasy.jboss.org/锛夋鏋讹紝鍦╠ubbo涓疄鐜颁簡REST椋庢牸锛圚TTP + JSON/XML锛夌殑杩滅▼璋冪敤锛屼互鏄捐憲绠鍖栦紒涓氬唴閮ㄧ殑璺ㄨ瑷浜や簰锛屽悓鏃舵樉钁楃畝鍖栦紒涓氬澶栫殑Open API銆佹棤绾緼PI鐢氳嚦AJAX鏈嶅姟绔瓑绛夌殑寮鍙戙備簨瀹炰笂锛岃繖涓猂EST璋冪敤涔熶娇寰桪ubbo鍙互瀵瑰綋浠婄壒鍒祦琛岀殑鈥滃井鏈嶅姟鈥濇灦鏋勬彁渚涘熀纭鎬ф敮鎸併 鍙﹀锛孯EST璋冪敤涔熻揪鍒颁簡姣旇緝楂樼殑鎬ц兘锛屽湪鍩哄噯娴嬭瘯涓嬶紝HTTP + JSON涓嶥ubbo 2.x榛樿鐨凴PC鍗忚锛堝嵆TCP + Hessian2浜岃繘鍒跺簭鍒楀寲锛変箣闂村彧鏈1.5鍊嶅乏鍙崇殑宸窛锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 -* **鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡紑婧愮殑kryo鍜宖st锛坒ast serialization锛夊簭鍒楀寲搴擄紝涓篸ubbo鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜嗚繙绋嬭皟鐢ㄦц兘銆 +* **鏀寔鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡綋浠婃瘮杈冪煡鍚嶇殑锛籏ryo锛斤紙https://github.com/EsotericSoftware/kryo锛夊拰锛籉ST锛斤紙https://github.com/RuedigerMoeller/fast-serialization锛夐珮鎬ц兘搴忓垪鍖栧簱锛屼负Dubbo 榛樿鐨凴PC鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜咲ubbo RPC鐨勬ц兘锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 -* **鍩轰簬宓屽叆寮廡omcat鐨凥TTP浣撶郴**锛氬熀浜庡祵鍏ュ紡tomcat瀹炵幇dubbo http浣撶郴锛堝嵆dubbo-remoting-http锛夛紝鐢ㄤ互閫愭鍙栦唬鏃х殑宓屽叆寮廽etty锛屽彲浠ユ樉钁楃殑鎻愰珮REST绛夎皟鐢ㄧ殑鎬ц兘锛屽苟灏唖ervlet API鐨勬敮鎸佷粠2.5鍗囩骇鍒3.1銆傦紙娉細闄や簡REST锛宒ubbo涓殑WebServices銆丠essian銆丠TTP Invoker绛夊崗璁兘鍩轰簬姝ttp浣撶郴锛夈 +* **鏀寔鍩轰簬宓屽叆寮廡omcat鐨凥TTP remoting浣撶郴**锛氬熀浜庡祵鍏ュ紡tomcat瀹炵幇dubbo鐨凥TTP remoting浣撶郴锛堝嵆dubbo-remoting-http锛夛紝鐢ㄤ互閫愭鍙栦唬Dubbo涓棫鐗堟湰鐨勫祵鍏ュ紡Jetty锛屽彲浠ユ樉钁楃殑鎻愰珮REST绛夌殑杩滅▼璋冪敤鎬ц兘锛屽苟灏哠ervlet API鐨勬敮鎸佷粠2.5鍗囩骇鍒3.1銆傦紙娉細闄や簡REST锛宒ubbo涓殑WebServices銆丠essian銆丠TTP Invoker绛夊崗璁兘鍩轰簬杩欎釜HTTP remoting浣撶郴锛夈 -* **Spring鐨勫崌绾**锛氬皢dubbo涓璼pring鐢2.x鍗囩骇鍒扮洰鍓嶆渶甯哥敤鐨3.x鐗堟湰锛屽噺灏戠増鏈啿绐佸甫鏉ョ殑楹荤儲 +* **鍗囩骇Spring**锛氬皢dubbo涓璖pring鐢2.x鍗囩骇鍒扮洰鍓嶆渶甯哥敤鐨3.x鐗堟湰锛屽噺灏戠増鏈啿绐佸甫鏉ョ殑楹荤儲 -* **ZooKeeper瀹㈡埛绔殑鍗囩骇**锛氬皢dubbo涓殑zookeeper瀹㈡埛绔崌绾у埌鏈鏂扮殑鐗堟湰锛屼互淇鑰佺増鏈腑鍖呭惈鐨刡ug銆 +* **鍗囩骇ZooKeeper瀹㈡埛绔**锛氬皢dubbo涓殑zookeeper瀹㈡埛绔崌绾у埌鏈鏂扮殑鐗堟湰锛屼互淇鑰佺増鏈腑鍖呭惈鐨刡ug銆 -* **Demo搴旂敤**锛氭殏鏃跺皢dubbo鐨刣emo搴旂敤璋冩暣骞舵敼鍐欎互涓昏婕旂ずREST鍔熻兘鍜屾柊鐨凧ava楂樻晥搴忓垪鍖栫瓑绛夈 +* **璋冩暣Demo搴旂敤**锛氭殏鏃跺皢dubbo鐨刣emo搴旂敤璋冩暣骞舵敼鍐欎互涓昏婕旂ずREST鍔熻兘鍜屾柊鐨凧ava楂樻晥搴忓垪鍖栫瓑绛夈 * **淇浜嗗湪JDK1.7涓奷ubbo鐨勯儴鍒哹ug**锛氫慨姝d簡姣斿dubbo鍗忚涓璲son搴忓垪鍖栫殑闂銆備絾鏄繕娌℃湁淇鎵鏈夊彂鐜扮殑bug銆 @@ -30,4 +28,11 @@ Contacts: shenli@dangdang.com, wangyuxuan@dangdang.com [Demo搴旂敤绠鍗曡繍琛屾寚鍗梋(http://dangdangdotcom.github.io/dubbox/demo.html) +### 鐗堟湰 +璇﹁锛歨ttps://github.com/dangdangdotcom/dubbox/releases + +* **dubbox-2.8.0**锛氳鐗堟湰宸茬粡鍦ㄧ敓浜х幆澧冧腑浣跨敤锛屼富瑕佹敮鎸丷EST椋庢牸杩滅▼璋冪敤銆佹敮鎸並ryo鍜孎ST搴忓垪鍖栥佸崌绾т簡Spring鍜孼ookeeper瀹㈡埛绔佽皟鏁翠簡demo搴旂敤绛夌瓑锛堢洰鍓嶄互涓婂叧浜嶳EST鐨勬枃妗e彧閽堝2.8.0锛 +* **dubbox-2.8.1**锛氫富瑕佹敮鎸佸熀浜庡祵鍏ュ紡tomcat鐨刪ttp-remoting锛屼紭鍖栦簡REST瀹㈡埛绔ц兘绛夌瓑 + +Contacts: shenli@dangdang.com, wangyuxuan@dangdang.com From 84772ef284f94fc0b30c6bad289001ca8101f98a Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 22 Oct 2014 11:37:23 +0800 Subject: [PATCH 112/200] fix docs --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e96225ae3ee1..1dee7ea5b377 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p ### Dubbox褰撳墠鐨勪富瑕佸姛鑳斤細 -* **鏀寔REST椋庢牸杩滅▼璋冪敤锛圚TTP + JSON/XML)**锛氬熀浜庨潪甯告垚鐔熺殑JBoss 锛籖estEasy锛斤紙http://resteasy.jboss.org/锛夋鏋讹紝鍦╠ubbo涓疄鐜颁簡REST椋庢牸锛圚TTP + JSON/XML锛夌殑杩滅▼璋冪敤锛屼互鏄捐憲绠鍖栦紒涓氬唴閮ㄧ殑璺ㄨ瑷浜や簰锛屽悓鏃舵樉钁楃畝鍖栦紒涓氬澶栫殑Open API銆佹棤绾緼PI鐢氳嚦AJAX鏈嶅姟绔瓑绛夌殑寮鍙戙備簨瀹炰笂锛岃繖涓猂EST璋冪敤涔熶娇寰桪ubbo鍙互瀵瑰綋浠婄壒鍒祦琛岀殑鈥滃井鏈嶅姟鈥濇灦鏋勬彁渚涘熀纭鎬ф敮鎸併 鍙﹀锛孯EST璋冪敤涔熻揪鍒颁簡姣旇緝楂樼殑鎬ц兘锛屽湪鍩哄噯娴嬭瘯涓嬶紝HTTP + JSON涓嶥ubbo 2.x榛樿鐨凴PC鍗忚锛堝嵆TCP + Hessian2浜岃繘鍒跺簭鍒楀寲锛変箣闂村彧鏈1.5鍊嶅乏鍙崇殑宸窛锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 +* **鏀寔REST椋庢牸杩滅▼璋冪敤锛圚TTP + JSON/XML)**锛氬熀浜庨潪甯告垚鐔熺殑JBoss 锛籖estEasy锛(http://resteasy.jboss.org/)妗嗘灦锛屽湪dubbo涓疄鐜颁簡REST椋庢牸锛圚TTP + JSON/XML锛夌殑杩滅▼璋冪敤锛屼互鏄捐憲绠鍖栦紒涓氬唴閮ㄧ殑璺ㄨ瑷浜や簰锛屽悓鏃舵樉钁楃畝鍖栦紒涓氬澶栫殑Open API銆佹棤绾緼PI鐢氳嚦AJAX鏈嶅姟绔瓑绛夌殑寮鍙戙備簨瀹炰笂锛岃繖涓猂EST璋冪敤涔熶娇寰桪ubbo鍙互瀵瑰綋浠婄壒鍒祦琛岀殑鈥滃井鏈嶅姟鈥濇灦鏋勬彁渚涘熀纭鎬ф敮鎸併 鍙﹀锛孯EST璋冪敤涔熻揪鍒颁簡姣旇緝楂樼殑鎬ц兘锛屽湪鍩哄噯娴嬭瘯涓嬶紝HTTP + JSON涓嶥ubbo 2.x榛樿鐨凴PC鍗忚锛堝嵆TCP + Hessian2浜岃繘鍒跺簭鍒楀寲锛変箣闂村彧鏈1.5鍊嶅乏鍙崇殑宸窛锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 -* **鏀寔鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡綋浠婃瘮杈冪煡鍚嶇殑锛籏ryo锛斤紙https://github.com/EsotericSoftware/kryo锛夊拰锛籉ST锛斤紙https://github.com/RuedigerMoeller/fast-serialization锛夐珮鎬ц兘搴忓垪鍖栧簱锛屼负Dubbo 榛樿鐨凴PC鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜咲ubbo RPC鐨勬ц兘锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 +* **鏀寔鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡綋浠婃瘮杈冪煡鍚嶇殑锛籏ryo锛(https://github.com/EsotericSoftware/kryo)鍜岋蓟FST锛(https://github.com/RuedigerMoeller/fast-serialization)楂樻ц兘搴忓垪鍖栧簱锛屼负Dubbo 榛樿鐨凴PC鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜咲ubbo RPC鐨勬ц兘锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 * **鏀寔鍩轰簬宓屽叆寮廡omcat鐨凥TTP remoting浣撶郴**锛氬熀浜庡祵鍏ュ紡tomcat瀹炵幇dubbo鐨凥TTP remoting浣撶郴锛堝嵆dubbo-remoting-http锛夛紝鐢ㄤ互閫愭鍙栦唬Dubbo涓棫鐗堟湰鐨勫祵鍏ュ紡Jetty锛屽彲浠ユ樉钁楃殑鎻愰珮REST绛夌殑杩滅▼璋冪敤鎬ц兘锛屽苟灏哠ervlet API鐨勬敮鎸佷粠2.5鍗囩骇鍒3.1銆傦紙娉細闄や簡REST锛宒ubbo涓殑WebServices銆丠essian銆丠TTP Invoker绛夊崗璁兘鍩轰簬杩欎釜HTTP remoting浣撶郴锛夈 @@ -35,4 +35,5 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p * **dubbox-2.8.0**锛氳鐗堟湰宸茬粡鍦ㄧ敓浜х幆澧冧腑浣跨敤锛屼富瑕佹敮鎸丷EST椋庢牸杩滅▼璋冪敤銆佹敮鎸並ryo鍜孎ST搴忓垪鍖栥佸崌绾т簡Spring鍜孼ookeeper瀹㈡埛绔佽皟鏁翠簡demo搴旂敤绛夌瓑锛堢洰鍓嶄互涓婂叧浜嶳EST鐨勬枃妗e彧閽堝2.8.0锛 * **dubbox-2.8.1**锛氫富瑕佹敮鎸佸熀浜庡祵鍏ュ紡tomcat鐨刪ttp-remoting锛屼紭鍖栦簡REST瀹㈡埛绔ц兘绛夌瓑 + Contacts: shenli@dangdang.com, wangyuxuan@dangdang.com From 2706196732a38bb7834f78f1c4c723a0fb7e42fc Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 22 Oct 2014 11:40:52 +0800 Subject: [PATCH 113/200] fix docs --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1dee7ea5b377..1018189b9774 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p ### Dubbox褰撳墠鐨勪富瑕佸姛鑳斤細 -* **鏀寔REST椋庢牸杩滅▼璋冪敤锛圚TTP + JSON/XML)**锛氬熀浜庨潪甯告垚鐔熺殑JBoss 锛籖estEasy锛(http://resteasy.jboss.org/)妗嗘灦锛屽湪dubbo涓疄鐜颁簡REST椋庢牸锛圚TTP + JSON/XML锛夌殑杩滅▼璋冪敤锛屼互鏄捐憲绠鍖栦紒涓氬唴閮ㄧ殑璺ㄨ瑷浜や簰锛屽悓鏃舵樉钁楃畝鍖栦紒涓氬澶栫殑Open API銆佹棤绾緼PI鐢氳嚦AJAX鏈嶅姟绔瓑绛夌殑寮鍙戙備簨瀹炰笂锛岃繖涓猂EST璋冪敤涔熶娇寰桪ubbo鍙互瀵瑰綋浠婄壒鍒祦琛岀殑鈥滃井鏈嶅姟鈥濇灦鏋勬彁渚涘熀纭鎬ф敮鎸併 鍙﹀锛孯EST璋冪敤涔熻揪鍒颁簡姣旇緝楂樼殑鎬ц兘锛屽湪鍩哄噯娴嬭瘯涓嬶紝HTTP + JSON涓嶥ubbo 2.x榛樿鐨凴PC鍗忚锛堝嵆TCP + Hessian2浜岃繘鍒跺簭鍒楀寲锛変箣闂村彧鏈1.5鍊嶅乏鍙崇殑宸窛锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 +* **鏀寔REST椋庢牸杩滅▼璋冪敤锛圚TTP + JSON/XML)**锛氬熀浜庨潪甯告垚鐔熺殑JBoss [RestEasy](http://resteasy.jboss.org/)妗嗘灦锛屽湪dubbo涓疄鐜颁簡REST椋庢牸锛圚TTP + JSON/XML锛夌殑杩滅▼璋冪敤锛屼互鏄捐憲绠鍖栦紒涓氬唴閮ㄧ殑璺ㄨ瑷浜や簰锛屽悓鏃舵樉钁楃畝鍖栦紒涓氬澶栫殑Open API銆佹棤绾緼PI鐢氳嚦AJAX鏈嶅姟绔瓑绛夌殑寮鍙戙備簨瀹炰笂锛岃繖涓猂EST璋冪敤涔熶娇寰桪ubbo鍙互瀵瑰綋浠婄壒鍒祦琛岀殑鈥滃井鏈嶅姟鈥濇灦鏋勬彁渚涘熀纭鎬ф敮鎸併 鍙﹀锛孯EST璋冪敤涔熻揪鍒颁簡姣旇緝楂樼殑鎬ц兘锛屽湪鍩哄噯娴嬭瘯涓嬶紝HTTP + JSON涓嶥ubbo 2.x榛樿鐨凴PC鍗忚锛堝嵆TCP + Hessian2浜岃繘鍒跺簭鍒楀寲锛変箣闂村彧鏈1.5鍊嶅乏鍙崇殑宸窛锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 -* **鏀寔鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡綋浠婃瘮杈冪煡鍚嶇殑锛籏ryo锛(https://github.com/EsotericSoftware/kryo)鍜岋蓟FST锛(https://github.com/RuedigerMoeller/fast-serialization)楂樻ц兘搴忓垪鍖栧簱锛屼负Dubbo 榛樿鐨凴PC鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜咲ubbo RPC鐨勬ц兘锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 +* **鏀寔鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡綋浠婃瘮杈冪煡鍚嶇殑[Kryo](https://github.com/EsotericSoftware/kryo)鍜孾FST](https://github.com/RuedigerMoeller/fast-serialization)楂樻ц兘搴忓垪鍖栧簱锛屼负Dubbo 榛樿鐨凴PC鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜咲ubbo RPC鐨勬ц兘锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 * **鏀寔鍩轰簬宓屽叆寮廡omcat鐨凥TTP remoting浣撶郴**锛氬熀浜庡祵鍏ュ紡tomcat瀹炵幇dubbo鐨凥TTP remoting浣撶郴锛堝嵆dubbo-remoting-http锛夛紝鐢ㄤ互閫愭鍙栦唬Dubbo涓棫鐗堟湰鐨勫祵鍏ュ紡Jetty锛屽彲浠ユ樉钁楃殑鎻愰珮REST绛夌殑杩滅▼璋冪敤鎬ц兘锛屽苟灏哠ervlet API鐨勬敮鎸佷粠2.5鍗囩骇鍒3.1銆傦紙娉細闄や簡REST锛宒ubbo涓殑WebServices銆丠essian銆丠TTP Invoker绛夊崗璁兘鍩轰簬杩欎釜HTTP remoting浣撶郴锛夈 From c881a54940a6c539325ae1cadeff7449ca9be453 Mon Sep 17 00:00:00 2001 From: denghua Date: Fri, 24 Oct 2014 11:07:08 +0800 Subject: [PATCH 114/200] =?UTF-8?q?=E7=BB=99surefire=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pom.xml b/pom.xml index cd08452b7a85..06b7fb26600d 100644 --- a/pom.xml +++ b/pom.xml @@ -151,6 +151,8 @@ 2.1.1 2.3.1 2.7 + + 2.17 @@ -402,6 +404,7 @@ org.apache.maven.plugins maven-surefire-plugin + ${maven-surefire-plugin_version} true once From c2e44e94192aa3ba679804f38dadacd2662cd345 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 29 Oct 2014 17:27:12 +0800 Subject: [PATCH 115/200] add exception mapping example for rest --- dubbo-demo/dubbo-demo-api/pom.xml | 7 +--- .../demo/extension/CustomExceptionMapper.java | 34 +++++++++++++++++++ .../META-INF/spring/dubbo-demo-provider.xml | 7 ++-- 3 files changed, 39 insertions(+), 9 deletions(-) create mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/CustomExceptionMapper.java diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index bcc64dfe62c1..791f88fcebc3 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -29,14 +29,9 @@ true - - com.alibaba - dubbo-common - ${project.parent.version} - com.alibaba - dubbo-rpc-rest + dubbo ${project.parent.version} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/CustomExceptionMapper.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/CustomExceptionMapper.java new file mode 100644 index 000000000000..82397901ab99 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/CustomExceptionMapper.java @@ -0,0 +1,34 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.extension; + +import com.alibaba.dubbo.rpc.RpcContext; + +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + +/** + * @author lishen + */ +public class CustomExceptionMapper implements ExceptionMapper { + + public Response toResponse(NotFoundException e) { + System.out.println("Exception mapper successfully got an exception: " + e + ":" + e.getMessage()); + System.out.println("Client IP is " + RpcContext.getContext().getRemoteAddressString()); + return Response.status(Response.Status.NOT_FOUND).entity("Oops! the requested resource is not found!").type("text/plain").build(); + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index d9ce8dc42a9a..732f0aa4f07f 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -45,12 +45,13 @@ - - + + com.alibaba.dubbo.demo.extension.DynamicTraceBinding, + com.alibaba.dubbo.demo.extension.CustomExceptionMapper"/> From 134d848953c6391dfd5bcc63ca0a9ef0b1c7ec4d Mon Sep 17 00:00:00 2001 From: Li Shen Date: Thu, 30 Oct 2014 10:28:11 +0800 Subject: [PATCH 116/200] change docs --- README.md | 4 ++-- .../main/resources/META-INF/spring/dubbo-demo-provider.xml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1018189b9774..66e26f34adce 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,8 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p 璇﹁锛歨ttps://github.com/dangdangdotcom/dubbox/releases -* **dubbox-2.8.0**锛氳鐗堟湰宸茬粡鍦ㄧ敓浜х幆澧冧腑浣跨敤锛屼富瑕佹敮鎸丷EST椋庢牸杩滅▼璋冪敤銆佹敮鎸並ryo鍜孎ST搴忓垪鍖栥佸崌绾т簡Spring鍜孼ookeeper瀹㈡埛绔佽皟鏁翠簡demo搴旂敤绛夌瓑锛堢洰鍓嶄互涓婂叧浜嶳EST鐨勬枃妗e彧閽堝2.8.0锛 -* **dubbox-2.8.1**锛氫富瑕佹敮鎸佸熀浜庡祵鍏ュ紡tomcat鐨刪ttp-remoting锛屼紭鍖栦簡REST瀹㈡埛绔ц兘绛夌瓑 +* **dubbox-2.8.0**锛氳鐗堟湰宸茬粡鍦ㄧ敓浜х幆澧冧腑浣跨敤锛屼富瑕佹敮鎸丷EST椋庢牸杩滅▼璋冪敤銆佹敮鎸並ryo鍜孎ST搴忓垪鍖栥佸崌绾т簡Spring鍜孼ookeeper瀹㈡埛绔佽皟鏁翠簡demo搴旂敤绛夌瓑 +* **dubbox-2.8.1**锛氫富瑕佹敮鎸佸熀浜庡祵鍏ュ紡tomcat鐨刪ttp-remoting锛屼紭鍖栦簡REST瀹㈡埛绔ц兘绛夌瓑锛堜互涓婂叧浜嶳EST鐨勬枃妗i拡瀵2.8.1锛 Contacts: shenli@dangdang.com, wangyuxuan@dangdang.com diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 732f0aa4f07f..a2dbd2da58ae 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -46,7 +46,7 @@ - Date: Thu, 6 Nov 2014 17:50:05 +0800 Subject: [PATCH 120/200] add http logging support for rest --- .../user/facade/AnotherUserRestService.java | 18 +-- .../AnnotationDrivenUserRestServiceImpl.java | 3 +- .../demo/user/facade/UserRestServiceImpl.java | 3 +- .../META-INF/spring/dubbo-demo-provider.xml | 3 +- .../protocol/rest/support/ContentType.java | 28 ++++ .../protocol/rest/support/LoggingFilter.java | 143 ++++++++++++++++++ 6 files changed, 179 insertions(+), 19 deletions(-) create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java index f60533a41ded..63a993823d89 100644 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java @@ -1,21 +1,7 @@ -/** - * Copyright 1999-2014 dangdang.com. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package com.alibaba.dubbo.demo.user.facade; import com.alibaba.dubbo.demo.user.User; +import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType; import javax.ws.rs.Consumes; import javax.ws.rs.GET; @@ -30,7 +16,7 @@ */ @Path("u") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) -@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) public interface AnotherUserRestService { @GET diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java index ffef936a02b6..2f67034873ad 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java @@ -18,6 +18,7 @@ import com.alibaba.dubbo.config.annotation.Service; import com.alibaba.dubbo.demo.user.User; import com.alibaba.dubbo.demo.user.UserService; +import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType; import org.springframework.beans.factory.annotation.Autowired; import javax.ws.rs.Consumes; @@ -34,7 +35,7 @@ @Service(protocol = "rest", group = "annotationConfig") @Path("customers") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) -@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) public class AnnotationDrivenUserRestServiceImpl implements UserRestService { // private static final Logger logger = LoggerFactory.getLogger(UserRestServiceImpl.class); diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java index 1387205f6f78..21e44a80c404 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java @@ -19,6 +19,7 @@ import com.alibaba.dubbo.demo.user.UserService; import com.alibaba.dubbo.demo.user.facade.RegistrationResult; import com.alibaba.dubbo.demo.user.facade.UserRestService; +import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType; import javax.ws.rs.Consumes; import javax.ws.rs.GET; @@ -33,7 +34,7 @@ */ @Path("users") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) -@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) public class UserRestServiceImpl implements UserRestService { // private static final Logger logger = LoggerFactory.getLogger(UserRestServiceImpl.class); diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index a2dbd2da58ae..c7d60bc941bc 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -51,7 +51,8 @@ com.alibaba.dubbo.demo.extension.TraceFilter, com.alibaba.dubbo.demo.extension.ClientTraceFilter, com.alibaba.dubbo.demo.extension.DynamicTraceBinding, - com.alibaba.dubbo.demo.extension.CustomExceptionMapper"/> + com.alibaba.dubbo.demo.extension.CustomExceptionMapper, + com.alibaba.dubbo.rpc.protocol.rest.support.LoggingFilter"/> diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java new file mode 100644 index 000000000000..d3887481347b --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/ContentType.java @@ -0,0 +1,28 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest.support; + +import javax.ws.rs.core.MediaType; + +/** + * @author lishen + */ +public class ContentType { + + public static final String APPLICATION_JSON_UTF_8 = MediaType.APPLICATION_JSON + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; + public static final String TEXT_XML_UTF_8 = MediaType.TEXT_XML + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; + public static final String TEXT_PLAIN_UTF_8 = MediaType.TEXT_PLAIN + "; " + MediaType.CHARSET_PARAMETER + "=UTF-8"; +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java new file mode 100644 index 000000000000..310d263f8ed0 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java @@ -0,0 +1,143 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest.support; + +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import org.apache.commons.io.IOUtils; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.ReaderInterceptor; +import javax.ws.rs.ext.ReaderInterceptorContext; +import javax.ws.rs.ext.WriterInterceptor; +import javax.ws.rs.ext.WriterInterceptorContext; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; + +/** + * This logging filter is not highly optimized for now + * + * @author lishen + */ +@Priority(Priorities.HEADER_DECORATOR) +public class LoggingFilter implements + ContainerRequestFilter, ClientRequestFilter, ContainerResponseFilter, + ClientResponseFilter, WriterInterceptor, ReaderInterceptor { + + private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class); + + public void filter(ClientRequestContext context) throws IOException { + logHttpHeaders(context.getStringHeaders()); + } + + public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { + logHttpHeaders(responseContext.getHeaders()); + } + + public void filter(ContainerRequestContext context) throws IOException { + logHttpHeaders(context.getHeaders()); + } + + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { + logHttpHeaders(responseContext.getStringHeaders()); + } + + public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException { + byte[] buffer = IOUtils.toByteArray(context.getInputStream()); + logger.info("The contents of request body is: \n" + new String(buffer, "UTF-8") + "\n"); + context.setInputStream(new ByteArrayInputStream(buffer)); + return context.proceed(); + } + + public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { + OutputStreamWrapper wrapper = new OutputStreamWrapper(context.getOutputStream()); + context.setOutputStream(wrapper); + context.proceed(); + logger.info("The contents of response body is: \n" + new String(wrapper.getBytes(), "UTF-8") + "\n"); + } + + protected void logHttpHeaders(MultivaluedMap headers) { + StringBuilder msg = new StringBuilder("The HTTP headers are: \n"); + for (Map.Entry> entry : headers.entrySet()) { + msg.append(entry.getKey()).append(": "); + for (int i = 0; i < entry.getValue().size(); i++) { + msg.append(entry.getValue().get(i)); + if (i < entry.getValue().size() - 1) { + msg.append(", "); + } + } + msg.append("\n"); + } + logger.info(msg.toString()); + } + + protected static class OutputStreamWrapper extends OutputStream { + + private final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + private final OutputStream output; + + private OutputStreamWrapper(OutputStream output) { + this.output = output; + } + + @Override + public void write(int i) throws IOException { + buffer.write(i); + output.write(i); + } + + @Override + public void write(byte[] b) throws IOException { + buffer.write(b); + output.write(b); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + buffer.write(b, off, len); + output.write(b, off, len); + } + + @Override + public void flush() throws IOException { + output.flush(); + } + + @Override + public void close() throws IOException { + output.close(); + } + + public byte[] getBytes() { + return buffer.toByteArray(); + } + } +} From 245a5f4fcca1040aa67373a0aa7091db0658c028 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 12 Nov 2014 11:09:00 +0800 Subject: [PATCH 121/200] change docs --- README.md | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 7eff76b3a77c..f9343056f971 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,11 @@ Dubbox now means Dubbo eXtensions. If you know java, javax and dubbo, you know w Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the popular [dubbo service framework](http://github.com/alibaba/dubbo). It鈥檚 now internally used by several projects of [dangdang.com](http://www.dangdang.com), which is one of the major e-commerce companies in China. -### Dubbox褰撳墠鐨勪富瑕佸姛鑳斤細 +**鑱旂郴鏂瑰紡**锛氭矆鐞嗭紙shenli@dangdang.com锛, 鐜嬪畤杞╋紙wangyuxuan@dangdang.com锛 + +**璁ㄨQQ缇**锛305896472 + +## Dubbox褰撳墠鐨勪富瑕佸姛鑳斤細 * **鏀寔REST椋庢牸杩滅▼璋冪敤锛圚TTP + JSON/XML)**锛氬熀浜庨潪甯告垚鐔熺殑JBoss [RestEasy](http://resteasy.jboss.org/)妗嗘灦锛屽湪dubbo涓疄鐜颁簡REST椋庢牸锛圚TTP + JSON/XML锛夌殑杩滅▼璋冪敤锛屼互鏄捐憲绠鍖栦紒涓氬唴閮ㄧ殑璺ㄨ瑷浜や簰锛屽悓鏃舵樉钁楃畝鍖栦紒涓氬澶栫殑Open API銆佹棤绾緼PI鐢氳嚦AJAX鏈嶅姟绔瓑绛夌殑寮鍙戙備簨瀹炰笂锛岃繖涓猂EST璋冪敤涔熶娇寰桪ubbo鍙互瀵瑰綋浠婄壒鍒祦琛岀殑鈥滃井鏈嶅姟鈥濇灦鏋勬彁渚涘熀纭鎬ф敮鎸併 鍙﹀锛孯EST璋冪敤涔熻揪鍒颁簡姣旇緝楂樼殑鎬ц兘锛屽湪鍩哄噯娴嬭瘯涓嬶紝HTTP + JSON涓嶥ubbo 2.x榛樿鐨凴PC鍗忚锛堝嵆TCP + Hessian2浜岃繘鍒跺簭鍒楀寲锛変箣闂村彧鏈1.5鍊嶅乏鍙崇殑宸窛锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 @@ -20,7 +24,7 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p **娉細dubbox鍜宒ubbo 2.x鏄吋瀹圭殑锛屾病鏈夋敼鍙榙ubbo鐨勪换浣曞凡鏈夌殑鍔熻兘鍜岄厤缃柟寮忥紙闄や簡鍗囩骇浜唖pring涔嬬被鐨勭増鏈級** -### Dubbox鏂囨。 +## Dubbox鏂囨。 [鍦―ubbo涓紑鍙慠EST椋庢牸鐨勮繙绋嬭皟鐢紙RESTful Remoting锛塢(http://dangdangdotcom.github.io/dubbox/rest.html) @@ -28,17 +32,36 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p [Demo搴旂敤绠鍗曡繍琛屾寚鍗梋(http://dangdangdotcom.github.io/dubbox/demo.html) -### 鐗堟湰 +## 鐗堟湰 璇﹁锛歨ttps://github.com/dangdangdotcom/dubbox/releases * **dubbox-2.8.0**锛氳鐗堟湰宸茬粡鍦ㄧ敓浜х幆澧冧腑浣跨敤锛屼富瑕佹敮鎸丷EST椋庢牸杩滅▼璋冪敤銆佹敮鎸並ryo鍜孎ST搴忓垪鍖栥佸崌绾т簡Spring鍜孼ookeeper瀹㈡埛绔佽皟鏁翠簡demo搴旂敤绛夌瓑 -* **dubbox-2.8.1**锛氫富瑕佹敮鎸佸熀浜庡祵鍏ュ紡tomcat鐨刪ttp-remoting锛屼紭鍖栦簡REST瀹㈡埛绔ц兘绛夌瓑锛堜互涓婂叧浜嶳EST鐨勬枃妗i拡瀵2.8.1锛 +* **dubbox-2.8.1**锛氫富瑕佹敮鎸佸熀浜庡祵鍏ュ紡tomcat鐨刪ttp-remoting锛屼紭鍖栦簡REST瀹㈡埛绔ц兘锛屽湪REST涓敮鎸侀檺鍒舵湇鍔$鎺ョ撼鐨勬渶澶TTP杩炴帴鏁扮瓑绛 +* **dubbox-2.8.2**锛 + * 鏀寔REST涓殑HTTP logging锛屽寘鎷琀TTP header鐨勫瓧娈靛拰HTTP body涓殑娑堟伅浣擄紝鏂逛究璋冭瘯銆佹棩蹇楃邯褰曠瓑绛 + * 鎻愪緵杈呭姪绫讳究浜嶳EST鐨勪腑鏂囧鐞 + * 鏀瑰彉浣跨敤锝@Reference锝 annotation閰嶇疆鏃剁殑寮傚父澶勭悊鏂瑰紡锛屽嵆褰撶敤annotion閰嶇疆鏃讹紝杩囧幓dubbo鍦ㄥ惎鍔ㄦ湡闂翠笉鎶涘嚭渚濊禆鏈嶅姟鎵句笉鍒扮殑寮傚父锛岃屾槸鍦ㄥ叿浣撹皟鐢ㄦ椂鎶涘嚭NPE锛岃繖涓庣敤XML閰嶇疆鏃剁殑琛屼负涓嶄竴鑷淬 + * 杈冨ぇ鐨勫厖瀹炰簡Dubbo REST鐨勬枃妗 +## FAQ锛堟殏瀛橈級 -**鑱旂郴鏂瑰紡**锛氭矆鐞嗭紙shenli@dangdang.com锛, 鐜嬪畤杞╋紙wangyuxuan@dangdang.com锛 +### Dubbo REST鐨勬湇鍔¤兘鍜孌ubbo娉ㄥ唽涓績銆佺洃鎺т腑蹇冮泦鎴愬悧锛 + +鍙互鐨勶紝鑰屼笖鏄嚜鍔ㄩ泦鎴愮殑锛屼篃灏辨槸浣犲湪dubbo涓紑鍙戠殑鎵鏈塕EST鏈嶅姟閮戒細鑷姩娉ㄥ唽鍒版湇鍔″唽涓績鍜岀洃鎺т腑蹇冿紝鍙互閫氳繃瀹冧滑鍋氱鐞嗐 + +浣嗘槸锛屽彧鏈夊綋REST鐨勬秷璐圭涔熸槸鍩轰簬dubbo鐨勬椂鍊欙紝娉ㄥ唽涓績涓殑璁稿鏈嶅姟娌荤悊鎿嶄綔鎵嶈兘瀹屽叏璧蜂綔鐢ㄣ傝屽鏋滄秷璐圭鏄潪dubbo鐨勶紝鑷劧涓嶅彈娉ㄥ唽涓績绠$悊锛屾墍浠ュ叾涓緢澶氭搷浣滄槸涓嶄細瀵规秷璐圭璧蜂綔鐢ㄧ殑銆 + +### Dubbo REST涓浣曞疄鐜拌礋杞藉潎琛″拰瀹归敊锛坒ailover锛夛紵 + +濡傛灉dubbo REST鐨勬秷璐圭涔熸槸dubbo鐨勶紝鍒橠ubbo REST鍜屽叾浠杁ubbo杩滅▼璋冪敤鍗忚鍩烘湰瀹屽叏涓鏍凤紝鐢眃ubbo妗嗘灦閫忔槑鐨勫湪娑堣垂绔仛load balance銆乫ailover绛夌瓑銆 + +濡傛灉dubbo REST鐨勬秷璐圭鏄潪dubbo鐨勶紝鐢氳嚦鏄潪java鐨勶紝鍒欐渶濂介厤缃湇鍔℃彁渚涚鐨勮蒋璐熻浇鍧囪 鏈哄埗锛岀洰鍓嶅彲鑰冭檻鐢↙VS銆丠AProxy銆 Nginx绛夌瓑瀵笻TTP璇锋眰鍋氳礋杞藉潎琛° -**QQ缇**锛305896472 +### JAX-RS涓噸杞界殑鏂规硶鑳藉鏄犲皠鍒板悓涓URL鍦板潃鍚楋紵 +http://stackoverflow.com/questions/17196766/can-resteasy-choose-method-based-on-query-params +### JAX-RS涓綔POST鐨勬柟娉曡兘澶熸帴鏀跺涓弬鏁板悧锛 +http://stackoverflow.com/questions/5553218/jax-rs-post-multiple-objects \ No newline at end of file From 0c30bb23864aa6415d9ce1019aa26b43a8b343b9 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 12 Nov 2014 12:30:19 +0800 Subject: [PATCH 122/200] change versions --- dubbo-admin/pom.xml | 2 +- dubbo-cluster/pom.xml | 2 +- dubbo-common/pom.xml | 2 +- dubbo-config/dubbo-config-api/pom.xml | 2 +- dubbo-config/dubbo-config-spring/pom.xml | 2 +- dubbo-config/pom.xml | 2 +- dubbo-container/dubbo-container-api/pom.xml | 2 +- dubbo-container/dubbo-container-jetty/pom.xml | 2 +- dubbo-container/dubbo-container-log4j/pom.xml | 2 +- dubbo-container/dubbo-container-logback/pom.xml | 2 +- dubbo-container/dubbo-container-spring/pom.xml | 2 +- dubbo-container/pom.xml | 2 +- dubbo-demo/dubbo-demo-api/pom.xml | 2 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 2 +- dubbo-demo/dubbo-demo-provider/pom.xml | 2 +- dubbo-demo/pom.xml | 2 +- dubbo-filter/dubbo-filter-cache/pom.xml | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 2 +- dubbo-filter/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +- dubbo-monitor/pom.xml | 2 +- dubbo-registry/dubbo-registry-api/pom.xml | 2 +- dubbo-registry/dubbo-registry-default/pom.xml | 2 +- dubbo-registry/dubbo-registry-multicast/pom.xml | 2 +- dubbo-registry/dubbo-registry-redis/pom.xml | 2 +- dubbo-registry/dubbo-registry-zookeeper/pom.xml | 2 +- dubbo-registry/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-p2p/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-zookeeper/pom.xml | 2 +- dubbo-remoting/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-default/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rest/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 2 +- dubbo-rpc/pom.xml | 2 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 2 +- dubbo-simple/dubbo-registry-simple/pom.xml | 2 +- dubbo-simple/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark-api/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark-client/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark-server/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark/pom.xml | 2 +- dubbo-test/dubbo-test-compatibility/pom.xml | 2 +- dubbo-test/dubbo-test-examples/pom.xml | 2 +- dubbo-test/dubbo-test-integration/pom.xml | 2 +- dubbo-test/pom.xml | 2 +- dubbo/pom.xml | 2 +- hessian-lite/pom.xml | 2 +- pom.xml | 14 +------------- 62 files changed, 62 insertions(+), 74 deletions(-) diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index aceee9864be4..2649a9f4c68d 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-admin war diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index 3edde87c4fdb..d9dfad2d30dc 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-cluster jar diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index 039b2a053a23..1c46724d8230 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-common jar diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 597f2341dc9a..07ae2702dc08 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.8.1 + 2.8.2 dubbo-config-api jar diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 3183a22cbf1d..3fc85bcb4a33 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.8.1 + 2.8.2 dubbo-config-spring jar diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index 6a31488a7921..7c36ce60ab63 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index c237c424cfec..7b156a1bbf54 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.1 + 2.8.2 dubbo-container-api jar diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index b550162c3bf2..c0def190054b 100644 --- a/dubbo-container/dubbo-container-jetty/pom.xml +++ b/dubbo-container/dubbo-container-jetty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.1 + 2.8.2 dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index 958983820aab..0e7b60aa0af2 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.1 + 2.8.2 dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index deea9f2a23a7..7551c504e098 100644 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ b/dubbo-container/dubbo-container-logback/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.1 + 2.8.2 dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index bf1f7d84b3a7..7f4caadbe1f0 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.1 + 2.8.2 dubbo-container-spring jar diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index 2b6dcfee279e..ad7f744fc0b5 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-container pom diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index 791f88fcebc3..9a67423b7f1c 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.1 + 2.8.2 dubbo-demo-api jar diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml index 446e83944485..da3966df760f 100644 --- a/dubbo-demo/dubbo-demo-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.1 + 2.8.2 dubbo-demo-consumer jar diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml index 74073b07e0c1..406d388cadba 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.1 + 2.8.2 dubbo-demo-provider war diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index 50a282bb1ce0..a86490c5f89a 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-demo pom diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 529269934995..05f3278ef179 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.8.1 + 2.8.2 dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index e1d82950a214..87102ace75cb 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.8.1 + 2.8.2 dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index d3c3e9651fa1..2fd68fdf5edb 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-filter pom diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index 55ee12cbda7d..f2b1de4f0d0b 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.8.1 + 2.8.2 dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index 83b2d02803aa..990b4de0b6d4 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.8.1 + 2.8.2 dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index c865c9af5482..1f0476f41abd 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 8851097487d7..94da9ccd05c4 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.1 + 2.8.2 dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index 7a39f9539d09..20bb33c2adcf 100644 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ b/dubbo-registry/dubbo-registry-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.1 + 2.8.2 dubbo-registry-default jar diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index 0708d4bd2305..4166a86f24f9 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.1 + 2.8.2 dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index e1ba73b1ce6f..ab2316dfe5f8 100644 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ b/dubbo-registry/dubbo-registry-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.1 + 2.8.2 dubbo-registry-redis jar diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index 2492aeb85a71..2c91b8e37c69 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.1 + 2.8.2 dubbo-registry-zookeeper jar diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index 85df9750224a..e2c6d5b9a842 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-registry pom diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index f5c8bc682a3a..45f213fdc2f1 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.1 + 2.8.2 dubbo-remoting-api jar diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml index 0cb92809f65a..2237885dfe83 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml +++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.1 + 2.8.2 dubbo-remoting-grizzly jar diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index 194a21336e3b..d0273a679663 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.1 + 2.8.2 dubbo-remoting-http jar diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml index 4594bb3c2985..687bb3d709c9 100644 --- a/dubbo-remoting/dubbo-remoting-mina/pom.xml +++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.1 + 2.8.2 dubbo-remoting-mina jar diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index 21c4facd2923..f920b18f20fe 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.1 + 2.8.2 dubbo-remoting-netty jar diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml index 0f7be3eca20b..7394b026387f 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml +++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.1 + 2.8.2 dubbo-remoting-p2p jar diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index 0f6cbc8b85bb..9868baa75e67 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.1 + 2.8.2 dubbo-remoting-zookeeper jar diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 8742605b9619..99bb82b069e2 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -18,7 +18,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-remoting pom diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index 439502aae176..74fc65130e66 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.1 + 2.8.2 dubbo-rpc-api jar diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index 2b1801751b77..33177c110a56 100644 --- a/dubbo-rpc/dubbo-rpc-default/pom.xml +++ b/dubbo-rpc/dubbo-rpc-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.1 + 2.8.2 dubbo-rpc-default jar diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index 8b79311a1883..400639440535 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.1 + 2.8.2 dubbo-rpc-hessian jar diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index 8dd468a54d11..569f7fb9c2fe 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.1 + 2.8.2 dubbo-rpc-http jar diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index c6180d7c5663..3f1f85ec6fe3 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml +++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.1 + 2.8.2 dubbo-rpc-injvm jar diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml index 24c2c47249ed..46d91e20b0b8 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml +++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.1 + 2.8.2 dubbo-rpc-memcached jar diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml index 134fb9d65019..dca41fd1d16f 100644 --- a/dubbo-rpc/dubbo-rpc-redis/pom.xml +++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.1 + 2.8.2 dubbo-rpc-redis jar diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml index 4a4c724c3b48..394844f8d3d2 100644 --- a/dubbo-rpc/dubbo-rpc-rest/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.1 + 2.8.2 dubbo-rpc-rest jar diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml index 1f0d25596062..c2f185f8e998 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.1 + 2.8.2 dubbo-rpc-rmi jar diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml index 74383e6d8fbb..d08a9926390f 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ b/dubbo-rpc/dubbo-rpc-thrift/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.1 + 2.8.2 dubbo-rpc-thrift jar diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml index b2bbe1106f3e..f8be327b3d74 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml +++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.1 + 2.8.2 dubbo-rpc-webservice jar diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 47842b120b78..675ff8701ad4 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-rpc pom diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml index 4b836321576f..e8aaa37de420 100644 --- a/dubbo-simple/dubbo-monitor-simple/pom.xml +++ b/dubbo-simple/dubbo-monitor-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.8.1 + 2.8.2 dubbo-monitor-simple jar diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml index 006a0f0a8949..8eb5f3c9d92e 100644 --- a/dubbo-simple/dubbo-registry-simple/pom.xml +++ b/dubbo-simple/dubbo-registry-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.8.1 + 2.8.2 dubbo-registry-simple jar diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml index aa02aef12a65..d64d5d276e8a 100644 --- a/dubbo-simple/pom.xml +++ b/dubbo-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-simple pom diff --git a/dubbo-test/dubbo-test-benchmark-api/pom.xml b/dubbo-test/dubbo-test-benchmark-api/pom.xml index 469d9815acc5..80a337860948 100644 --- a/dubbo-test/dubbo-test-benchmark-api/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-api/pom.xml @@ -4,7 +4,7 @@ com.alibaba dubbo-test - 2.8.1 + 2.8.2 dubbo-test-benchmark-api jar diff --git a/dubbo-test/dubbo-test-benchmark-client/pom.xml b/dubbo-test/dubbo-test-benchmark-client/pom.xml index c897513287ee..f1dd990ed287 100644 --- a/dubbo-test/dubbo-test-benchmark-client/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-client/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.1 + 2.8.2 dubbo-test-benchmark-client jar diff --git a/dubbo-test/dubbo-test-benchmark-server/pom.xml b/dubbo-test/dubbo-test-benchmark-server/pom.xml index be4b90c944da..f669e6e6be6c 100644 --- a/dubbo-test/dubbo-test-benchmark-server/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-server/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.1 + 2.8.2 dubbo-test-benchmark-server jar diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml index b2f0e8bcf9f5..4882dc29824f 100644 --- a/dubbo-test/dubbo-test-benchmark/pom.xml +++ b/dubbo-test/dubbo-test-benchmark/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.1 + 2.8.2 dubbo-test-benchmark jar diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml index b0d5c3654e61..162572190087 100644 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ b/dubbo-test/dubbo-test-compatibility/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.1 + 2.8.2 dubbo-test-compatibility jar diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index 100947be98dc..5343e1814aaf 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.1 + 2.8.2 dubbo-test-examples jar diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml index 5f87c82ffeac..cef01a44c905 100644 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ b/dubbo-test/dubbo-test-integration/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.1 + 2.8.2 dubbo-test-integration jar diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml index 5bee4af3bde9..c0d5e764bc60 100644 --- a/dubbo-test/pom.xml +++ b/dubbo-test/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo-test pom diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 14dffbb533be..c60a3887e45b 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 dubbo jar diff --git a/hessian-lite/pom.xml b/hessian-lite/pom.xml index 01f71e0ad7e9..938e71224009 100644 --- a/hessian-lite/pom.xml +++ b/hessian-lite/pom.xml @@ -6,7 +6,7 @@ com.alibaba dubbo-parent - 2.8.1 + 2.8.2 hessian-lite jar diff --git a/pom.xml b/pom.xml index 06b7fb26600d..b6762b016830 100644 --- a/pom.xml +++ b/pom.xml @@ -20,7 +20,7 @@ 2.0 --> com.alibaba dubbo-parent - 2.8.1 + 2.8.2 pom ${project.artifactId} The parent project of dubbo @@ -632,16 +632,4 @@ +8 - - - nexus-releases - Nexus Release Repository - http://10.255.209.180/nexus/content/repositories/releases/ - - - nexus-snapshots - Nexus Snapshot Repository - http://10.255.209.180/nexus/content/repositories/snapshots/ - - From 3380004afa6559965d9c63b9f1983218ad2bed23 Mon Sep 17 00:00:00 2001 From: Jinkai Ma Date: Fri, 14 Nov 2014 10:37:50 +0800 Subject: [PATCH 123/200] support for spring java config --- .../dubbo-container-javaconfig/pom.xml | 42 ++++++++++++ .../javaconfig/JavaConfigContainer.java | 64 +++++++++++++++++++ .../com.alibaba.dubbo.container.Container | 1 + .../javaconfig/JavaConfigContainerTest.java | 36 +++++++++++ .../spring/javaconfig/TestDubboConfig.java | 33 ++++++++++ .../src/test/resources/log4j.xml | 28 ++++++++ dubbo-container/pom.xml | 1 + 7 files changed, 205 insertions(+) create mode 100644 dubbo-container/dubbo-container-javaconfig/pom.xml create mode 100644 dubbo-container/dubbo-container-javaconfig/src/main/java/com/alibaba/dubbo/container/javaconfig/JavaConfigContainer.java create mode 100644 dubbo-container/dubbo-container-javaconfig/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.container.Container create mode 100644 dubbo-container/dubbo-container-javaconfig/src/test/java/com/alibaba/dubbo/container/javaconfig/JavaConfigContainerTest.java create mode 100644 dubbo-container/dubbo-container-javaconfig/src/test/java/dubbo/spring/javaconfig/TestDubboConfig.java create mode 100644 dubbo-container/dubbo-container-javaconfig/src/test/resources/log4j.xml diff --git a/dubbo-container/dubbo-container-javaconfig/pom.xml b/dubbo-container/dubbo-container-javaconfig/pom.xml new file mode 100644 index 000000000000..d0bfe6a0e0ae --- /dev/null +++ b/dubbo-container/dubbo-container-javaconfig/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + com.alibaba + dubbo-container + 2.8.2 + + dubbo-container-javaconfig + jar + ${project.artifactId} + The spring container by java config module of dubbo project + + true + + + + org.springframework + spring-context + + + com.alibaba + dubbo-container-api + ${project.parent.version} + + + \ No newline at end of file diff --git a/dubbo-container/dubbo-container-javaconfig/src/main/java/com/alibaba/dubbo/container/javaconfig/JavaConfigContainer.java b/dubbo-container/dubbo-container-javaconfig/src/main/java/com/alibaba/dubbo/container/javaconfig/JavaConfigContainer.java new file mode 100644 index 000000000000..15b30a4d91f4 --- /dev/null +++ b/dubbo-container/dubbo-container-javaconfig/src/main/java/com/alibaba/dubbo/container/javaconfig/JavaConfigContainer.java @@ -0,0 +1,64 @@ +/** + * Copyright 2006-2014 handu.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.container.javaconfig; + +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.common.utils.ConfigUtils; +import com.alibaba.dubbo.container.Container; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +/** + * JavaConfigContainer. (SPI, Singleton, ThreadSafe) + * + * @author Jinkai.Ma + */ +public class JavaConfigContainer implements Container { + + private static final Logger logger = LoggerFactory.getLogger(JavaConfigContainer.class); + + public static final String SPRING_JAVACONFIG = "dubbo.spring.javaconfig"; + + public static final String DEFAULT_SPRING_JAVACONFIG = "dubbo.spring.javaconfig"; + + static AnnotationConfigApplicationContext context; + + public static AnnotationConfigApplicationContext getContext() { + return context; + } + + public void start() { + String configPath = ConfigUtils.getProperty(SPRING_JAVACONFIG); + if (configPath == null || configPath.length() == 0) { + configPath = DEFAULT_SPRING_JAVACONFIG; + } + context = new AnnotationConfigApplicationContext(configPath); + context.start(); + } + + public void stop() { + try { + if (context != null) { + context.stop(); + context.close(); + context = null; + } + } catch (Throwable e) { + logger.error(e.getMessage(), e); + } + } + +} diff --git a/dubbo-container/dubbo-container-javaconfig/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.container.Container b/dubbo-container/dubbo-container-javaconfig/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.container.Container new file mode 100644 index 000000000000..c8d7f9f4f9dc --- /dev/null +++ b/dubbo-container/dubbo-container-javaconfig/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.container.Container @@ -0,0 +1 @@ +javaconfig=com.alibaba.dubbo.container.javaconfig.JavaConfigContainer \ No newline at end of file diff --git a/dubbo-container/dubbo-container-javaconfig/src/test/java/com/alibaba/dubbo/container/javaconfig/JavaConfigContainerTest.java b/dubbo-container/dubbo-container-javaconfig/src/test/java/com/alibaba/dubbo/container/javaconfig/JavaConfigContainerTest.java new file mode 100644 index 000000000000..cdf0d50dc7b7 --- /dev/null +++ b/dubbo-container/dubbo-container-javaconfig/src/test/java/com/alibaba/dubbo/container/javaconfig/JavaConfigContainerTest.java @@ -0,0 +1,36 @@ +/** + * Copyright 2006-2014 handu.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.container.javaconfig; + +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.container.Container; +import org.junit.Assert; +import org.junit.Test; + +/** + * @author Jinkai.Ma + */ +public class JavaConfigContainerTest { + + @Test + public void testContainer() { + JavaConfigContainer container = (JavaConfigContainer) ExtensionLoader.getExtensionLoader(Container.class).getExtension("javaconfig"); + container.start(); + Assert.assertEquals(JavaConfigContainer.class, container.context.getBean("container").getClass()); + container.stop(); + } + +} diff --git a/dubbo-container/dubbo-container-javaconfig/src/test/java/dubbo/spring/javaconfig/TestDubboConfig.java b/dubbo-container/dubbo-container-javaconfig/src/test/java/dubbo/spring/javaconfig/TestDubboConfig.java new file mode 100644 index 000000000000..0afc4c98ce35 --- /dev/null +++ b/dubbo-container/dubbo-container-javaconfig/src/test/java/dubbo/spring/javaconfig/TestDubboConfig.java @@ -0,0 +1,33 @@ +/** + * Copyright 2006-2014 handu.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package dubbo.spring.javaconfig; + +import com.alibaba.dubbo.container.javaconfig.JavaConfigContainer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author Jinkai.Ma + */ +@Configuration +public class TestDubboConfig { + + @Bean + public JavaConfigContainer container() { + return new JavaConfigContainer(); + } + +} diff --git a/dubbo-container/dubbo-container-javaconfig/src/test/resources/log4j.xml b/dubbo-container/dubbo-container-javaconfig/src/test/resources/log4j.xml new file mode 100644 index 000000000000..210b4678882c --- /dev/null +++ b/dubbo-container/dubbo-container-javaconfig/src/test/resources/log4j.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index ad7f744fc0b5..3cbeace8bfc5 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -31,6 +31,7 @@ dubbo-container-api dubbo-container-spring + dubbo-container-javaconfig dubbo-container-jetty dubbo-container-log4j dubbo-container-logback From acf52afaa2d5cd4d32c688323101e99ec1c9bc83 Mon Sep 17 00:00:00 2001 From: Jinkai Ma Date: Fri, 14 Nov 2014 10:39:19 +0800 Subject: [PATCH 124/200] add dependency to dubbo/pom.xml to support spring java config --- dubbo/pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/dubbo/pom.xml b/dubbo/pom.xml index c60a3887e45b..7d8afba6ed30 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -236,6 +236,11 @@ dubbo-container-spring ${project.parent.version} + + com.alibaba + dubbo-container-javaconfig + ${project.parent.version} + com.alibaba dubbo-container-jetty From d1259a4d8738ec740db56e1c7e5a0026be52a4d9 Mon Sep 17 00:00:00 2001 From: Jinkai Ma Date: Fri, 14 Nov 2014 10:41:15 +0800 Subject: [PATCH 125/200] consumer demo without spring xml config and dubbo annotation config --- .../demo/consumer/DemoJavaConfigAction.java | 87 +++++++++++++++++++ .../javaconfig/DubboDemoActionConfig.java | 33 +++++++ .../javaconfig/DubboDemoConsumerConfig.java | 56 ++++++++++++ .../demo/consumer/DemoJavaConfigConsumer.java | 27 ++++++ 4 files changed, 203 insertions(+) create mode 100644 dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigAction.java create mode 100644 dubbo-demo/dubbo-demo-consumer/src/main/java/dubbo/spring/javaconfig/DubboDemoActionConfig.java create mode 100644 dubbo-demo/dubbo-demo-consumer/src/main/java/dubbo/spring/javaconfig/DubboDemoConsumerConfig.java create mode 100644 dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigConsumer.java diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigAction.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigAction.java new file mode 100644 index 000000000000..19b71c220255 --- /dev/null +++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigAction.java @@ -0,0 +1,87 @@ +/* + * Copyright 2006-2014 handu.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.consumer; + +import com.alibaba.dubbo.config.annotation.Reference; +import com.alibaba.dubbo.demo.bid.*; +import com.alibaba.dubbo.demo.user.User; +import com.alibaba.dubbo.demo.user.facade.AnotherUserRestService; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Jinkai.Ma + */ +@Component +public class DemoJavaConfigAction { + + @Reference + private BidService bidService; + + @Reference + private AnotherUserRestService anotherUserRestService; + + @PostConstruct + public void start() throws Exception { + BidRequest request = new BidRequest(); + + Impression imp = new Impression(); + imp.setBidFloor(1.1); + imp.setId("abc"); + List imps = new ArrayList(1); + imps.add(imp); + request.setImpressions(imps); + + Geo geo = new Geo(); + geo.setCity("beijing"); + geo.setCountry("china"); + geo.setLat(100.1f); + geo.setLon(100.1f); + + Device device = new Device(); + device.setMake("apple"); + device.setOs("ios"); + device.setVersion("7.0"); + device.setLang("zh_CN"); + device.setModel("iphone"); + device.setGeo(geo); + request.setDevice(device); + +// long start = System.currentTimeMillis(); + +// for (int i = 0; i < 10000; i ++) { +// System.out.println(bidService.bid(request).getId()); + System.out.println("SUCESS: got bid response id: " + bidService.bid(request).getId()); +// } + +// System.out.println(">>>>> Total time consumed:" + (System.currentTimeMillis() - start)); + + try { + bidService.throwNPE(); + System.out.println("ERROR: no exception found"); + } catch (NullPointerException e) { + System.out.println("SUCCESS: caught exception " + e.getClass()); + } + + User user = new User(1L, "dang"); + System.out.println("SUCESS: registered user with id " + anotherUserRestService.registerUser(user).getId()); + + System.out.println("SUCESS: got user " + anotherUserRestService.getUser(1L)); + } +} diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/java/dubbo/spring/javaconfig/DubboDemoActionConfig.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/dubbo/spring/javaconfig/DubboDemoActionConfig.java new file mode 100644 index 000000000000..ea27c4039236 --- /dev/null +++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/dubbo/spring/javaconfig/DubboDemoActionConfig.java @@ -0,0 +1,33 @@ +/* + * Copyright 2006-2014 handu.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package dubbo.spring.javaconfig; + +import com.alibaba.dubbo.demo.consumer.DemoJavaConfigAction; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author Jinkai.Ma + */ +@Configuration +public class DubboDemoActionConfig { + + @Bean + public DemoJavaConfigAction demoAnnotationAction() { + return new DemoJavaConfigAction(); + } + +} diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/java/dubbo/spring/javaconfig/DubboDemoConsumerConfig.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/dubbo/spring/javaconfig/DubboDemoConsumerConfig.java new file mode 100644 index 000000000000..2052150a92fb --- /dev/null +++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/dubbo/spring/javaconfig/DubboDemoConsumerConfig.java @@ -0,0 +1,56 @@ +/* + * Copyright 2006-2014 handu.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package dubbo.spring.javaconfig; + +import com.alibaba.dubbo.config.ApplicationConfig; +import com.alibaba.dubbo.config.RegistryConfig; +import com.alibaba.dubbo.config.spring.AnnotationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author Jinkai.Ma + */ +@Configuration +public class DubboDemoConsumerConfig { + + public static final String APPLICATION_NAME = "consumer-of-helloworld-app"; + + public static final String REGISTRY_ADDRESS = "zookeeper://127.0.0.1:2181"; + + public static final String ANNOTATION_PACKAGE = "com.alibaba.dubbo.demo.consumer"; + + @Bean + public ApplicationConfig applicationConfig() { + ApplicationConfig applicationConfig = new ApplicationConfig(); + applicationConfig.setName(APPLICATION_NAME); + return applicationConfig; + } + + @Bean + public RegistryConfig registryConfig() { + RegistryConfig registryConfig = new RegistryConfig(); + registryConfig.setAddress(REGISTRY_ADDRESS); + return registryConfig; + } + + @Bean + public AnnotationBean annotationBean() { + AnnotationBean annotationBean = new AnnotationBean(); + annotationBean.setPackage(ANNOTATION_PACKAGE); + return annotationBean; + } +} diff --git a/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigConsumer.java b/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigConsumer.java new file mode 100644 index 000000000000..afbe0704394b --- /dev/null +++ b/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigConsumer.java @@ -0,0 +1,27 @@ +/* + * Copyright 2006-2014 handu.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demo.consumer; + +/** + * @author Jinkai.Ma + */ +public class DemoJavaConfigConsumer { + public static void main(String[] args) { + // add `javaconfig` to args + String[] customArgs = new String[]{"javaconfig"}; + com.alibaba.dubbo.container.Main.main(customArgs); + } +} From 5267039f6c83a4120726e44573e27d0c54a30133 Mon Sep 17 00:00:00 2001 From: Jinkai Ma Date: Mon, 17 Nov 2014 17:01:33 +0800 Subject: [PATCH 126/200] =?UTF-8?q?=E5=8F=82=E7=85=A7dubbo/readme.txt?= =?UTF-8?q?=EF=BC=8C=E6=96=B0=E5=A2=9E=E6=A8=A1=E5=9D=97=E9=9C=80=E8=A6=81?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=88=B0POM=E7=9A=84maven-shade-plugin?= =?UTF-8?q?=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dubbo/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 7d8afba6ed30..ec6d45ff953f 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -351,6 +351,7 @@ com.alibaba:dubbo-config-spring com.alibaba:dubbo-container-api com.alibaba:dubbo-container-spring + com.alibaba:dubbo-container-javaconfig com.alibaba:dubbo-container-jetty com.alibaba:dubbo-container-log4j com.alibaba:dubbo-container-logback From ae1a968df53b68b717a3364e4cc3cda3bf768ee4 Mon Sep 17 00:00:00 2001 From: "Dylan.Ding" Date: Tue, 18 Nov 2014 21:09:45 +0800 Subject: [PATCH 127/200] =?UTF-8?q?=E5=A2=9E=E5=8A=A0jackson=E5=BA=8F?= =?UTF-8?q?=E5=88=97=E5=8C=96=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dubbo-common/pom.xml | 4 + .../alibaba/dubbo/common/json/Jackson.java | 52 +++++ .../json/JacksonObjectMapperProvider.java | 12 ++ .../support/json/JacksonObjectInput.java | 166 ++++++++++++++++ .../support/json/JacksonObjectOutput.java | 99 ++++++++++ .../support/json/JacksonSerialization.java | 50 +++++ ...ibaba.dubbo.common.serialize.Serialization | 3 +- .../dubbo/common/json/JacksonTest.java | 177 ++++++++++++++++++ dubbo-test/dubbo-test-examples/pom.xml | 14 ++ .../examples/jackson/JacksonConsumer.java | 43 +++++ .../examples/jackson/JacksonProvider.java | 34 ++++ .../examples/jackson/api/JacksonBean.java | 110 +++++++++++ .../jackson/api/JacksonInnerBean.java | 33 ++++ .../examples/jackson/api/JacksonService.java | 26 +++ .../jackson/impl/JacksonServiceImpl.java | 38 ++++ .../examples/jackson/jackson-consumer.xml | 29 +++ .../examples/jackson/jackson-provider.xml | 33 ++++ .../CustomJacksonObjectMapperProvider.java | 15 ++ ...bo.common.json.JacksonObjectMapperProvider | 1 + pom.xml | 15 +- 20 files changed, 951 insertions(+), 3 deletions(-) create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/json/Jackson.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/json/JacksonObjectMapperProvider.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectInput.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectOutput.java create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonSerialization.java create mode 100644 dubbo-common/src/test/java/com/alibaba/dubbo/common/json/JacksonTest.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonConsumer.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonProvider.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonBean.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonInnerBean.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonService.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/impl/JacksonServiceImpl.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jackson-consumer.xml create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jackson-provider.xml create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jacksonprovider/CustomJacksonObjectMapperProvider.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index 1c46724d8230..cac18d5113d8 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -81,5 +81,9 @@ fst 1.55 + + com.fasterxml.jackson.core + jackson-databind + \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/Jackson.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/Jackson.java new file mode 100644 index 000000000000..88b3e0cf29d3 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/Jackson.java @@ -0,0 +1,52 @@ +package com.alibaba.dubbo.common.json; + +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.TimeZone; + +/** + * Created by dylan on 11/12/14. + */ +public class Jackson { + private static Logger logger = LoggerFactory.getLogger(Jackson.class); + private static ObjectMapper objectMapper; + + private static JacksonObjectMapperProvider getJacksonProvider() { + return ExtensionLoader.getExtensionLoader(JacksonObjectMapperProvider.class).getDefaultExtension(); + } + + /** + * 鑾峰彇object mapper + * @return + */ + public static ObjectMapper getObjectMapper(){ + ObjectMapper objectMapper = null; + if(objectMapper == null){ + JacksonObjectMapperProvider jacksonObjectMapperProvider = getJacksonProvider(); + if(jacksonObjectMapperProvider != null){ + objectMapper = jacksonObjectMapperProvider.getObjectMapper(); + } + } + if(objectMapper == null){ + logger.warn("load objectMapper failed, use default config."); + objectMapper = buildDefaultObjectMapper(); + } + return objectMapper; + } + private static synchronized ObjectMapper buildDefaultObjectMapper(){ + if(objectMapper == null){ + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); +// objectMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); + objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.setTimeZone(TimeZone.getDefault()); + return objectMapper; + } + return null; + } +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/JacksonObjectMapperProvider.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/JacksonObjectMapperProvider.java new file mode 100644 index 000000000000..756e8f6d462d --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/JacksonObjectMapperProvider.java @@ -0,0 +1,12 @@ +package com.alibaba.dubbo.common.json; + +import com.alibaba.dubbo.common.extension.SPI; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Created by dylan on 11/12/14. + */ +@SPI("default") +public interface JacksonObjectMapperProvider { + public ObjectMapper getObjectMapper(); +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectInput.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectInput.java new file mode 100644 index 000000000000..a00b770a793d --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectInput.java @@ -0,0 +1,166 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.json; + +import com.alibaba.dubbo.common.json.Jackson; +import com.alibaba.dubbo.common.serialize.ObjectInput; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.util.Map; + +/** + * JsonObjectInput + * + * @author dylan + */ +public class JacksonObjectInput implements ObjectInput { + private static Logger logger = LoggerFactory.getLogger(JacksonObjectInput.class); + + private final ObjectMapper objectMapper; + // private final BufferedReader reader; + private final Map data; + private static final String KEY_PREFIX = "$"; + private int index = 0; + + public JacksonObjectInput(InputStream inputstream) throws IOException { +// this.reader = new BufferedReader(new InputStreamReader(inputstream)); +// String line = null; +// try { +// while ((line = reader.readLine()) != null) { +// System.out.println(line); +// } +// }catch(Exception e){ +// e.printStackTrace(); +// } + this.objectMapper = Jackson.getObjectMapper(); + try { + data = objectMapper.readValue(inputstream, Map.class); + } catch (IOException e) { + logger.error("parse inputstream error.", e); + throw e; + } + } + + public boolean readBool() throws IOException { + try { + return readObject(Boolean.class); + } catch (ClassNotFoundException e) { + throw new IOException(e.getMessage()); + } + } + + public byte readByte() throws IOException { + try { + return readObject(Byte.class); + } catch (ClassNotFoundException e) { + throw new IOException(e.getMessage()); + } + } + + public short readShort() throws IOException { + try { + return readObject(Short.class); + } catch (ClassNotFoundException e) { + throw new IOException(e.getMessage()); + } + } + + public int readInt() throws IOException { + try { + return readObject(Integer.class); + } catch (ClassNotFoundException e) { + throw new IOException(e.getMessage()); + } + } + + public long readLong() throws IOException { + try { + return readObject(Long.class); + } catch (ClassNotFoundException e) { + throw new IOException(e.getMessage()); + } + } + + public float readFloat() throws IOException { + try { + return readObject(Float.class); + } catch (ClassNotFoundException e) { + throw new IOException(e.getMessage()); + } + } + + public double readDouble() throws IOException { + try { + return readObject(Double.class); + } catch (ClassNotFoundException e) { + throw new IOException(e.getMessage()); + } + } + + public String readUTF() throws IOException { + try { + return readObject(String.class); + } catch (ClassNotFoundException e) { + throw new IOException(e.getMessage()); + } + } + + public byte[] readBytes() throws IOException { + return readUTF().getBytes(); + } + + public Object readObject() throws IOException, ClassNotFoundException { +// try { +// String json = readLine(); +// if (json.startsWith("{")) { +// return JSON.parse(json, Map.class); +// } else { +// json = "{\"value\":" + json + "}"; +// +// @SuppressWarnings("unchecked") +// Map map = objectMapper.readValue(json, Map.class); +// return map.get("value"); +// } +// } catch (ParseException e) { +// throw new IOException(e.getMessage()); +// } + try { + return readObject(Map.class); + } catch (ClassNotFoundException e) { + throw new IOException(e.getMessage()); + } + } + + @SuppressWarnings("unchecked") + public T readObject(Class cls) throws IOException, ClassNotFoundException { +// Object value = readObject(); + String json = this.data.get(KEY_PREFIX + (++index)); + logger.debug("index:{}, value:{}", index, json); + return objectMapper.readValue(json, cls); + } + + @SuppressWarnings("unchecked") + public T readObject(Class cls, Type type) throws IOException, ClassNotFoundException { +// Object value = readObject(); + return readObject(cls); + } + +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectOutput.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectOutput.java new file mode 100644 index 000000000000..778296cf734c --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectOutput.java @@ -0,0 +1,99 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.json; + +import com.alibaba.dubbo.common.json.Jackson; +import com.alibaba.dubbo.common.serialize.ObjectOutput; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.*; +import java.util.HashMap; +import java.util.Map; + +/** + * jackson object output + * @author dylan + */ +public class JacksonObjectOutput implements ObjectOutput { + + private final ObjectMapper objectMapper; + private final Map data; + private final static String KEY_PREFIX="$"; + private int index = 0; + + private final PrintWriter writer; + + public JacksonObjectOutput(OutputStream out) { + this(new OutputStreamWriter(out)); + } + + public JacksonObjectOutput(Writer writer) { + this.objectMapper = Jackson.getObjectMapper(); + this.writer = new PrintWriter(writer); + this.data = new HashMap(); + } + + public void writeBool(boolean v) throws IOException { + writeObject(v); + } + + public void writeByte(byte v) throws IOException { + writeObject(v); + } + + public void writeShort(short v) throws IOException { + writeObject(v); + } + + public void writeInt(int v) throws IOException { + writeObject(v); + } + + public void writeLong(long v) throws IOException { + writeObject(v); + } + + public void writeFloat(float v) throws IOException { + writeObject(v); + } + + public void writeDouble(double v) throws IOException { + writeObject(v); + } + + public void writeUTF(String v) throws IOException { + writeObject(v); + } + + public void writeBytes(byte[] b) throws IOException { + writeObject(new String(b)); + } + + public void writeBytes(byte[] b, int off, int len) throws IOException { + writeObject(new String(b, off, len)); + } + + public void writeObject(Object obj) throws IOException { + data.put(KEY_PREFIX + (++index), objectMapper.writeValueAsString(obj)); + } + + public void flushBuffer() throws IOException { + objectMapper.writeValue(writer, data); + writer.println(); + writer.flush(); + } + +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonSerialization.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonSerialization.java new file mode 100644 index 000000000000..2729cef5c3db --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonSerialization.java @@ -0,0 +1,50 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.common.serialize.support.json; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.serialize.ObjectInput; +import com.alibaba.dubbo.common.serialize.ObjectOutput; +import com.alibaba.dubbo.common.serialize.Serialization; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +/** + * JsonSerialization + * + * @author dylan + */ +public class JacksonSerialization implements Serialization { + + public byte getContentTypeId() { + return 20; + } + + public String getContentType() { + return "text/json"; + } + + public ObjectOutput serialize(URL url, OutputStream output) throws IOException { + return new JacksonObjectOutput(output); + } + + public ObjectInput deserialize(URL url, InputStream input) throws IOException { + return new JacksonObjectInput(input); + } + +} \ No newline at end of file diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization b/dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization index c47c91c40bae..2362c9acb886 100644 --- a/dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization +++ b/dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization @@ -6,4 +6,5 @@ json=com.alibaba.dubbo.common.serialize.support.json.JsonSerialization fastjson=com.alibaba.dubbo.common.serialize.support.json.FastJsonSerialization nativejava=com.alibaba.dubbo.common.serialize.support.nativejava.NativeJavaSerialization kryo=com.alibaba.dubbo.common.serialize.support.kryo.KryoSerialization -fst=com.alibaba.dubbo.common.serialize.support.fst.FstSerialization \ No newline at end of file +fst=com.alibaba.dubbo.common.serialize.support.fst.FstSerialization +jackson=com.alibaba.dubbo.common.serialize.support.json.JacksonSerialization \ No newline at end of file diff --git a/dubbo-common/src/test/java/com/alibaba/dubbo/common/json/JacksonTest.java b/dubbo-common/src/test/java/com/alibaba/dubbo/common/json/JacksonTest.java new file mode 100644 index 000000000000..558e9735bfdc --- /dev/null +++ b/dubbo-common/src/test/java/com/alibaba/dubbo/common/json/JacksonTest.java @@ -0,0 +1,177 @@ +package com.alibaba.dubbo.common.json; + +import com.alibaba.dubbo.common.serialize.support.json.FastJsonObjectOutput; +import com.alibaba.dubbo.common.serialize.support.json.JacksonObjectInput; +import com.alibaba.dubbo.common.serialize.support.json.JacksonObjectOutput; +import com.alibaba.dubbo.common.utils.CollectionUtils; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import java.io.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by dylan on 11/13/14. + */ +public class JacksonTest { + @Test + public void testWrite() throws Exception{ + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + JacksonObjectOutput output = new JacksonObjectOutput(bos); +// PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out)); + output.writeUTF("2.0.0"); + output.writeBool(true); + output.writeByte((byte) 2); + output.writeBytes(new String("abc").getBytes()); + output.writeDouble(2.0d); + output.writeFloat(3.05f); + output.writeInt(32); + output.writeLong(64L); + output.writeShort((short) 16); + output.writeBytes(new String("afdsafdsafsa").getBytes(), 6, 4); + output.writeObject(new String[]{"abc", "def", "gfk"}); + output.writeObject(new int[]{4,5,8}); + output.writeObject(new JacksonBean()); + output.flushBuffer(); + + JacksonObjectInput input = new JacksonObjectInput(new ByteArrayInputStream(bos.toByteArray())); + System.out.println(input.readUTF()); + System.out.println(input.readBool()); + System.out.println(input.readByte()); + System.out.println(new String(input.readBytes())); + System.out.println(input.readDouble()); + System.out.println(input.readFloat()); + System.out.println(input.readInt()); + System.out.println(input.readLong()); + System.out.println(input.readShort()); + System.out.println(Arrays.toString(input.readBytes())); + System.out.println(Arrays.toString(input.readObject(String[].class))); + System.out.println(Arrays.toString(input.readObject(int[].class))); + JacksonBean jacksonBean = input.readObject(JacksonBean.class); + System.out.println(jacksonBean); + + } + public static class JacksonBean { + private boolean bValue = true; + private String sValue = "string"; + private int iValue = 20; + private double dValue = 20.5; + private float fValue = 2.18f; + private long lValue = 3; + private Double dValue2 = null; + private List innerBeanList = new ArrayList(); + + public JacksonBean(){ + innerBeanList.add(new InnerBean()); + innerBeanList.add(new InnerBean()); + } + @Override + public String toString() { + return "JacksonBean{" + + "bValue=" + bValue + + ", sValue='" + sValue + '\'' + + ", iValue=" + iValue + + ", dValue=" + dValue + + ", fValue=" + fValue + + ", lValue=" + lValue + + ", dValue2=" + dValue2 + + ", innerBeanList=" + innerBeanList + + '}'; + } + + public boolean isbValue() { + return bValue; + } + + public void setbValue(boolean bValue) { + this.bValue = bValue; + } + + public String getsValue() { + return sValue; + } + + public void setsValue(String sValue) { + this.sValue = sValue; + } + + public int getiValue() { + return iValue; + } + + public void setiValue(int iValue) { + this.iValue = iValue; + } + + public double getdValue() { + return dValue; + } + + public void setdValue(double dValue) { + this.dValue = dValue; + } + + public float getfValue() { + return fValue; + } + + public void setfValue(float fValue) { + this.fValue = fValue; + } + + public long getlValue() { + return lValue; + } + + public void setlValue(long lValue) { + this.lValue = lValue; + } + + public Double getdValue2() { + return dValue2; + } + + public void setdValue2(Double dValue2) { + this.dValue2 = dValue2; + } + + public List getInnerBeanList() { + return innerBeanList; + } + + public void setInnerBeanList(List innerBeanList) { + this.innerBeanList = innerBeanList; + } + } + + public static class InnerBean { + private String siValue = "innerStr"; + private int iiValue = 18; + + public String getSiValue() { + return siValue; + } + + public void setSiValue(String siValue) { + this.siValue = siValue; + } + + public int getIiValue() { + return iiValue; + } + + public void setIiValue(int iiValue) { + this.iiValue = iiValue; + } + + @Override + public String toString() { + return "InnerBean{" + + "siValue='" + siValue + '\'' + + ", iiValue=" + iiValue + + '}'; + } + } +} diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index 5343e1814aaf..6819bd2c5cec 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -137,6 +137,20 @@ org.hibernate hibernate-validator + + com.alibaba + fastjson + + + joda-time + joda-time + 2.4 + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + 2.4.0 + diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonConsumer.java new file mode 100644 index 000000000000..9679263d5686 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonConsumer.java @@ -0,0 +1,43 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.examples.jackson; + +import com.alibaba.dubbo.examples.jackson.api.JacksonBean; +import com.alibaba.dubbo.examples.jackson.api.JacksonInnerBean; +import com.alibaba.dubbo.examples.jackson.api.JacksonService; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +/** + * JacksonConsumer + * + * @author dylan + */ +public class JacksonConsumer { + + public static void main(String[] args) throws Exception { + String config = JacksonConsumer.class.getPackage().getName().replace('.', '/') + "/jackson-consumer.xml"; + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); + context.start(); + JacksonService jacksonService = (JacksonService) context.getBean("jacksonService"); + String hello = jacksonService.sayHello("world"); + System.out.println(hello); + + JacksonBean jacksonBean = jacksonService.testJacksonBean(new JacksonBean(), new JacksonInnerBean()); + System.out.println(jacksonBean); + System.in.read(); + } + +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonProvider.java new file mode 100644 index 000000000000..dfa097fce184 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonProvider.java @@ -0,0 +1,34 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.examples.jackson; + +import org.springframework.context.support.ClassPathXmlApplicationContext; + +/** + * JacksonProvider + * + * @author dylan + */ +public class JacksonProvider { + + public static void main(String[] args) throws Exception { + String config = JacksonProvider.class.getPackage().getName().replace('.', '/') + "/jackson-provider.xml"; + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); + context.start(); + System.in.read(); + } + +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonBean.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonBean.java new file mode 100644 index 000000000000..f42ec8121056 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonBean.java @@ -0,0 +1,110 @@ +package com.alibaba.dubbo.examples.jackson.api; + +import org.joda.time.DateTime; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +/** + * Created by dylan on 11/15/14. + */ +public class JacksonBean { + + private boolean bValue = true; + private String sValue = "string"; + private int iValue = 20; + private double dValue = 20.5; + private float fValue = 2.18f; + private long lValue = 3; + private Double dValue2 = null; + private Date date = Calendar.getInstance().getTime(); + private DateTime dateTime = DateTime.now(); + private List innerBeanList = new ArrayList(); + + public JacksonBean(){ + innerBeanList.add(new JacksonInnerBean()); + innerBeanList.add(new JacksonInnerBean()); + } + + @Override + public String toString() { + return "JacksonBean{" + + "bValue=" + bValue + + ", sValue='" + sValue + '\'' + + ", iValue=" + iValue + + ", dValue=" + dValue + + ", fValue=" + fValue + + ", lValue=" + lValue + + ", dValue2=" + dValue2 + + ", date=" + date + + ", dateTime=" + dateTime + + ", innerBeanList=" + innerBeanList + + '}'; + } + + public boolean isbValue() { + return bValue; + } + + public void setbValue(boolean bValue) { + this.bValue = bValue; + } + + public String getsValue() { + return sValue; + } + + public void setsValue(String sValue) { + this.sValue = sValue; + } + + public int getiValue() { + return iValue; + } + + public void setiValue(int iValue) { + this.iValue = iValue; + } + + public double getdValue() { + return dValue; + } + + public void setdValue(double dValue) { + this.dValue = dValue; + } + + public float getfValue() { + return fValue; + } + + public void setfValue(float fValue) { + this.fValue = fValue; + } + + public long getlValue() { + return lValue; + } + + public void setlValue(long lValue) { + this.lValue = lValue; + } + + public Double getdValue2() { + return dValue2; + } + + public void setdValue2(Double dValue2) { + this.dValue2 = dValue2; + } + + public List getInnerBeanList() { + return innerBeanList; + } + + public void setInnerBeanList(List innerBeanList) { + this.innerBeanList = innerBeanList; + } +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonInnerBean.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonInnerBean.java new file mode 100644 index 000000000000..1a44907c8d0f --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonInnerBean.java @@ -0,0 +1,33 @@ +package com.alibaba.dubbo.examples.jackson.api; + +/** + * Created by dylan on 11/15/14. + */ +public class JacksonInnerBean { + private String siValue = "innerStr"; + private int iiValue = 18; + + public String getSiValue() { + return siValue; + } + + public void setSiValue(String siValue) { + this.siValue = siValue; + } + + public int getIiValue() { + return iiValue; + } + + public void setIiValue(int iiValue) { + this.iiValue = iiValue; + } + + @Override + public String toString() { + return "InnerBean{" + + "siValue='" + siValue + '\'' + + ", iiValue=" + iiValue + + '}'; + } +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonService.java new file mode 100644 index 000000000000..1386c4759a71 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonService.java @@ -0,0 +1,26 @@ +/** + * Project: dubbo-examples + * + * File Created at 2012-2-17 + * $Id$ + * + * Copyright 1999-2100 Alibaba.com Corporation Limited. + * All rights reserved. + * + * This software is the confidential and proprietary information of + * Alibaba Company. ("Confidential Information"). You shall not + * disclose such Confidential Information and shall use it only in + * accordance with the terms of the license agreement you entered into + * with Alibaba.com. + */ +package com.alibaba.dubbo.examples.jackson.api; + +/** + * @author william.liangf + */ +public interface JacksonService { + + String sayHello(String name); + + public JacksonBean testJacksonBean(JacksonBean jacksonBean, JacksonInnerBean jacksonInnerBean); +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/impl/JacksonServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/impl/JacksonServiceImpl.java new file mode 100644 index 000000000000..ebfb0bfa0217 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/impl/JacksonServiceImpl.java @@ -0,0 +1,38 @@ +/** + * Project: dubbo-examples + * + * File Created at 2012-2-17 + * $Id$ + * + * Copyright 1999-2100 Alibaba.com Corporation Limited. + * All rights reserved. + * + * This software is the confidential and proprietary information of + * Alibaba Company. ("Confidential Information"). You shall not + * disclose such Confidential Information and shall use it only in + * accordance with the terms of the license agreement you entered into + * with Alibaba.com. + */ +package com.alibaba.dubbo.examples.jackson.impl; + +import com.alibaba.dubbo.examples.jackson.api.JacksonBean; +import com.alibaba.dubbo.examples.jackson.api.JacksonInnerBean; +import com.alibaba.dubbo.examples.jackson.api.JacksonService; + +/** + * @author william.liangf + */ +public class JacksonServiceImpl implements JacksonService { + + public String sayHello(String name) { + return "hello, " + name; + } + + @Override + public JacksonBean testJacksonBean(JacksonBean jacksonBean, JacksonInnerBean jacksonInnerBean) { + System.out.println(jacksonBean); + System.out.println(jacksonInnerBean); + jacksonBean.getInnerBeanList().add(jacksonInnerBean); + return jacksonBean; + } +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jackson-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jackson-consumer.xml new file mode 100644 index 000000000000..f4a05eb5ac39 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jackson-consumer.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jackson-provider.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jackson-provider.xml new file mode 100644 index 000000000000..93a9d2a6212b --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jackson-provider.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jacksonprovider/CustomJacksonObjectMapperProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jacksonprovider/CustomJacksonObjectMapperProvider.java new file mode 100644 index 000000000000..b6f1c2de4d22 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jacksonprovider/CustomJacksonObjectMapperProvider.java @@ -0,0 +1,15 @@ +package com.alibaba.dubbo.examples.jackson.jacksonprovider; + +import com.alibaba.dubbo.common.json.JacksonObjectMapperProvider; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Created by dylan on 11/15/14. + */ +public class CustomJacksonObjectMapperProvider implements JacksonObjectMapperProvider { + @Override + public ObjectMapper getObjectMapper() { + System.out.println("get object mapper from CustomJacksonObjectMapperProvider"); + return new ObjectMapper(); + } +} diff --git a/dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider b/dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider new file mode 100644 index 000000000000..b14abca92d2a --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider @@ -0,0 +1 @@ +default=com.alibaba.dubbo.examples.jackson.jacksonprovider.CustomJacksonObjectMapperProvider \ No newline at end of file diff --git a/pom.xml b/pom.xml index b6762b016830..37d8ad72dd57 100644 --- a/pom.xml +++ b/pom.xml @@ -16,7 +16,7 @@ 4.0.0 - com.alibaba dubbo-parent @@ -112,6 +112,7 @@ 3.0 2.2 3.0.8 + 2.3.3 1.6.2 1.1 @@ -304,6 +305,16 @@ citrus-webx-all ${webx_version} + + com.fasterxml.jackson.core + jackson-core + ${jackson_version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson_version} + org.slf4j @@ -513,7 +524,7 @@ ${file_encoding} - org.eclipse.m2e From 3276f0a37044fb4761c3825bcd1fb25fb4e1d889 Mon Sep 17 00:00:00 2001 From: "Dylan.Ding" Date: Sat, 15 Nov 2014 16:13:27 +0800 Subject: [PATCH 128/200] add default jackson ObjectMapper provider --- .../DefaultJacksonObjectMapperProvider.java | 22 ++++++++++++++ .../alibaba/dubbo/common/json/Jackson.java | 29 +++++++++---------- .../json/JacksonObjectMapperProvider.java | 2 +- ...bo.common.json.JacksonObjectMapperProvider | 1 + ...bo.common.json.JacksonObjectMapperProvider | 0 5 files changed, 37 insertions(+), 17 deletions(-) create mode 100644 dubbo-common/src/main/java/com/alibaba/dubbo/common/json/DefaultJacksonObjectMapperProvider.java create mode 100644 dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider rename dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/{internal => }/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider (100%) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/DefaultJacksonObjectMapperProvider.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/DefaultJacksonObjectMapperProvider.java new file mode 100644 index 000000000000..5b7bb5197056 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/DefaultJacksonObjectMapperProvider.java @@ -0,0 +1,22 @@ +package com.alibaba.dubbo.common.json; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +import java.util.TimeZone; + +/** + * @author dylan + */ +public class DefaultJacksonObjectMapperProvider implements JacksonObjectMapperProvider { + @Override + public ObjectMapper getObjectMapper() { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); +// objectMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); + objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.setTimeZone(TimeZone.getDefault()); + return objectMapper; + } +} diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/Jackson.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/Jackson.java index 88b3e0cf29d3..6bcd8d35cd0d 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/Jackson.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/Jackson.java @@ -10,7 +10,7 @@ import java.util.TimeZone; /** - * Created by dylan on 11/12/14. + * @author dylan */ public class Jackson { private static Logger logger = LoggerFactory.getLogger(Jackson.class); @@ -22,31 +22,28 @@ private static JacksonObjectMapperProvider getJacksonProvider() { /** * 鑾峰彇object mapper + * * @return */ - public static ObjectMapper getObjectMapper(){ - ObjectMapper objectMapper = null; - if(objectMapper == null){ + public static ObjectMapper getObjectMapper() { + if (objectMapper == null) { JacksonObjectMapperProvider jacksonObjectMapperProvider = getJacksonProvider(); - if(jacksonObjectMapperProvider != null){ + if (jacksonObjectMapperProvider != null) { objectMapper = jacksonObjectMapperProvider.getObjectMapper(); } } - if(objectMapper == null){ + if (objectMapper == null) { logger.warn("load objectMapper failed, use default config."); - objectMapper = buildDefaultObjectMapper(); + buildDefaultObjectMapper(); } return objectMapper; } - private static synchronized ObjectMapper buildDefaultObjectMapper(){ - if(objectMapper == null){ - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); + + private static synchronized void buildDefaultObjectMapper() { + objectMapper = new ObjectMapper(); + objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); // objectMapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE); - objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - objectMapper.setTimeZone(TimeZone.getDefault()); - return objectMapper; - } - return null; + objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + objectMapper.setTimeZone(TimeZone.getDefault()); } } diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/JacksonObjectMapperProvider.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/JacksonObjectMapperProvider.java index 756e8f6d462d..70524bb77c62 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/JacksonObjectMapperProvider.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/json/JacksonObjectMapperProvider.java @@ -6,7 +6,7 @@ /** * Created by dylan on 11/12/14. */ -@SPI("default") +@SPI("jackson") public interface JacksonObjectMapperProvider { public ObjectMapper getObjectMapper(); } diff --git a/dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider b/dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider new file mode 100644 index 000000000000..73e8cf261f55 --- /dev/null +++ b/dubbo-common/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider @@ -0,0 +1 @@ +jackson=com.alibaba.dubbo.common.json.DefaultJacksonObjectMapperProvider \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider b/dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider similarity index 100% rename from dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider rename to dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider From 1b33f1909723c4760c9fd4fd5ce3ce57b2e97d84 Mon Sep 17 00:00:00 2001 From: "Dylan.Ding" Date: Sat, 15 Nov 2014 15:51:56 +0800 Subject: [PATCH 129/200] proxy bean support with annotation scan --- .../dubbo/config/spring/AnnotationBean.java | 31 ++++++++++++---- dubbo-test/dubbo-test-examples/pom.xml | 10 ++++++ .../examples/aop/AopAnnotationConsumer.java | 36 +++++++++++++++++++ .../examples/aop/AopAnnotationProvider.java | 32 +++++++++++++++++ .../aop/action/AopAnnotationAction.java | 35 ++++++++++++++++++ .../examples/aop/annotation-consumer.xml | 29 +++++++++++++++ .../examples/aop/annotation-provider.xml | 33 +++++++++++++++++ .../alibaba/dubbo/examples/aop/aop-aspect.xml | 30 ++++++++++++++++ .../aop/api/AopAnnotationService.java | 25 +++++++++++++ .../examples/aop/aspect/AnnotationAspect.java | 11 ++++++ .../aop/impl/AopAnnotationServiceImpl.java | 32 +++++++++++++++++ 11 files changed, 297 insertions(+), 7 deletions(-) create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/AopAnnotationConsumer.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/AopAnnotationProvider.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/action/AopAnnotationAction.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/annotation-consumer.xml create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/annotation-provider.xml create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/aop-aspect.xml create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/api/AopAnnotationService.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/aspect/AnnotationAspect.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/impl/AopAnnotationServiceImpl.java diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java index bdc6098baf4f..e79538a42e5e 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java @@ -24,6 +24,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import org.springframework.aop.support.AopUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.DisposableBean; @@ -135,15 +136,19 @@ public Object postProcessAfterInitialization(Object bean, String beanName) if (! isMatchPackage(bean)) { return bean; } - Service service = bean.getClass().getAnnotation(Service.class); + Class clazz = bean.getClass(); + if(isProxyBean(bean)){ + clazz = AopUtils.getTargetClass(bean); + } + Service service = clazz.getAnnotation(Service.class); if (service != null) { ServiceBean serviceConfig = new ServiceBean(service); if (void.class.equals(service.interfaceClass()) && "".equals(service.interfaceName())) { - if (bean.getClass().getInterfaces().length > 0) { - serviceConfig.setInterface(bean.getClass().getInterfaces()[0]); + if (clazz.getInterfaces().length > 0) { + serviceConfig.setInterface(clazz.getInterfaces()[0]); } else { - throw new IllegalStateException("Failed to export remote service class " + bean.getClass().getName() + ", cause: The @Service undefined interfaceClass or interfaceName, and the service class unimplemented any interfaces."); + throw new IllegalStateException("Failed to export remote service class " + clazz.getName() + ", cause: The @Service undefined interfaceClass or interfaceName, and the service class unimplemented any interfaces."); } } if (applicationContext != null) { @@ -203,7 +208,11 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) if (! isMatchPackage(bean)) { return bean; } - Method[] methods = bean.getClass().getMethods(); + Class clazz = bean.getClass(); + if(isProxyBean(bean)){ + clazz = AopUtils.getTargetClass(bean); + } + Method[] methods = clazz.getMethods(); for (Method method : methods) { String name = method.getName(); if (name.length() > 3 && name.startsWith("set") @@ -225,7 +234,7 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) } } } - Field[] fields = bean.getClass().getDeclaredFields(); + Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { try { if (! field.isAccessible()) { @@ -311,7 +320,11 @@ private boolean isMatchPackage(Object bean) { if (annotationPackages == null || annotationPackages.length == 0) { return true; } - String beanClassName = bean.getClass().getName(); + Class clazz = bean.getClass(); + if(isProxyBean(bean)){ + clazz = AopUtils.getTargetClass(bean); + } + String beanClassName = clazz.getName(); for (String pkg : annotationPackages) { if (beanClassName.startsWith(pkg)) { return true; @@ -320,4 +333,8 @@ private boolean isMatchPackage(Object bean) { return false; } + private boolean isProxyBean(Object bean) { + return AopUtils.isAopProxy(bean) || AopUtils.isCglibProxy(bean) || AopUtils.isJdkDynamicProxy(bean); + } + } diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index 6819bd2c5cec..06d2f7a2e5c7 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -151,6 +151,16 @@ jackson-datatype-joda 2.4.0 + + org.springframework + spring-aop + + + + org.aspectj + aspectjweaver + 1.7.4 + diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/AopAnnotationConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/AopAnnotationConsumer.java new file mode 100644 index 000000000000..be5a4d04f3cb --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/AopAnnotationConsumer.java @@ -0,0 +1,36 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.examples.aop; + +import com.alibaba.dubbo.examples.aop.action.AopAnnotationAction; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +/** + * @author dylan + */ +public class AopAnnotationConsumer { + + public static void main(String[] args) throws Exception { + String config = AopAnnotationConsumer.class.getPackage().getName().replace('.', '/') + "/annotation-consumer.xml"; + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); + context.start(); + final AopAnnotationAction annotationAction = (AopAnnotationAction)context.getBean("aopAnnotationAction"); + String hello = annotationAction.doSayHello("world"); + System.out.println("result :" + hello); + System.in.read(); + } + +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/AopAnnotationProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/AopAnnotationProvider.java new file mode 100644 index 000000000000..9a9542a34ae2 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/AopAnnotationProvider.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.examples.aop; + +import org.springframework.context.support.ClassPathXmlApplicationContext; + +/** + * @author dylan + */ +public class AopAnnotationProvider { + + public static void main(String[] args) throws Exception { + String config = AopAnnotationProvider.class.getPackage().getName().replace('.', '/') + "/annotation-provider.xml"; + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); + context.start(); + System.in.read(); + } + +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/action/AopAnnotationAction.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/action/AopAnnotationAction.java new file mode 100644 index 000000000000..52a4ed20b072 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/action/AopAnnotationAction.java @@ -0,0 +1,35 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.examples.aop.action; + +import com.alibaba.dubbo.config.annotation.Reference; +import com.alibaba.dubbo.examples.aop.api.AopAnnotationService; +import org.springframework.stereotype.Component; + +/** + * @author dylan + */ +@Component("aopAnnotationAction") +public class AopAnnotationAction { + + @Reference + private AopAnnotationService annotationService; + + public String doSayHello(String name) { + return annotationService.sayHello(name); + } + +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/annotation-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/annotation-consumer.xml new file mode 100644 index 000000000000..6eb4da393615 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/annotation-consumer.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/annotation-provider.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/annotation-provider.xml new file mode 100644 index 000000000000..9dfaf32445df --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/annotation-provider.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/aop-aspect.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/aop-aspect.xml new file mode 100644 index 000000000000..8061f37f73b3 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/aop-aspect.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/api/AopAnnotationService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/api/AopAnnotationService.java new file mode 100644 index 000000000000..60e6cefc3033 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/api/AopAnnotationService.java @@ -0,0 +1,25 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.examples.aop.api; + +/** + * @author dylan + */ +public interface AopAnnotationService { + + String sayHello(String name); + +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/aspect/AnnotationAspect.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/aspect/AnnotationAspect.java new file mode 100644 index 000000000000..5fb0743599d7 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/aspect/AnnotationAspect.java @@ -0,0 +1,11 @@ +package com.alibaba.dubbo.examples.aop.aspect; + +/** + * @author dylan + */ +public class AnnotationAspect { + + public void before(){ + System.out.println("aspect before------------"); + } +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/impl/AopAnnotationServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/impl/AopAnnotationServiceImpl.java new file mode 100644 index 000000000000..71440f6ee3e3 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/impl/AopAnnotationServiceImpl.java @@ -0,0 +1,32 @@ +/* + * Copyright 1999-2012 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.examples.aop.impl; + +import com.alibaba.dubbo.config.annotation.Service; +import com.alibaba.dubbo.examples.aop.api.AopAnnotationService; + +/** + * @author dylan + */ +@Service +public class AopAnnotationServiceImpl implements AopAnnotationService { + + public String sayHello(String name) { + System.out.println("aop provider received: " + name); + return "aop annotation: hello, " + name; + } + +} \ No newline at end of file From b76bcbe2713dc84eb29ab75ec233caef5d8a55c3 Mon Sep 17 00:00:00 2001 From: "Dylan.Ding" Date: Tue, 18 Nov 2014 21:18:11 +0800 Subject: [PATCH 130/200] bugfix: no value set for reference method --- .../java/com/alibaba/dubbo/config/spring/AnnotationBean.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java index e79538a42e5e..58730bff10c9 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java @@ -224,7 +224,7 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) if (reference != null) { Object value = refer(reference, method.getParameterTypes()[0]); if (value != null) { - method.invoke(bean, new Object[] { }); + method.invoke(bean, new Object[] { value }); } } } catch (Exception e) { From 13302ced3cab0b1e7a5bd3e3c5167f0546c3660b Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 19 Nov 2014 11:41:35 +0800 Subject: [PATCH 131/200] update docs --- README.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f9343056f971..b902d57d553f 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,17 @@ Dubbox now means Dubbo eXtensions. If you know java, javax and dubbo, you know what dubbox is :) -Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the popular [dubbo service framework](http://github.com/alibaba/dubbo). It鈥檚 now internally used by several projects of [dangdang.com](http://www.dangdang.com), which is one of the major e-commerce companies in China. +Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the popular [dubbo service framework](http://github.com/alibaba/dubbo). It's been used by several projects of [dangdang.com](http://www.dangdang.com), which is one of the major e-commerce companies in China. -**鑱旂郴鏂瑰紡**锛氭矆鐞嗭紙shenli@dangdang.com锛, 鐜嬪畤杞╋紙wangyuxuan@dangdang.com锛 +## 涓昏璐$尞鑰 + +* 娌堢悊 褰撳綋缃 shenli@dangdang.com +* 鐜嬪畤杞 褰撳綋缃 wangyuxuan@dangdang.com +* 椹噾鍑 闊╅兘琛h垗 majk@vip.qq.com +* Dylan 鐙珛寮鍙戣 dinguangx@163.com **璁ㄨQQ缇**锛305896472 -## Dubbox褰撳墠鐨勪富瑕佸姛鑳斤細 +## Dubbox褰撳墠鐨勪富瑕佸姛鑳 * **鏀寔REST椋庢牸杩滅▼璋冪敤锛圚TTP + JSON/XML)**锛氬熀浜庨潪甯告垚鐔熺殑JBoss [RestEasy](http://resteasy.jboss.org/)妗嗘灦锛屽湪dubbo涓疄鐜颁簡REST椋庢牸锛圚TTP + JSON/XML锛夌殑杩滅▼璋冪敤锛屼互鏄捐憲绠鍖栦紒涓氬唴閮ㄧ殑璺ㄨ瑷浜や簰锛屽悓鏃舵樉钁楃畝鍖栦紒涓氬澶栫殑Open API銆佹棤绾緼PI鐢氳嚦AJAX鏈嶅姟绔瓑绛夌殑寮鍙戙備簨瀹炰笂锛岃繖涓猂EST璋冪敤涔熶娇寰桪ubbo鍙互瀵瑰綋浠婄壒鍒祦琛岀殑鈥滃井鏈嶅姟鈥濇灦鏋勬彁渚涘熀纭鎬ф敮鎸併 鍙﹀锛孯EST璋冪敤涔熻揪鍒颁簡姣旇緝楂樼殑鎬ц兘锛屽湪鍩哄噯娴嬭瘯涓嬶紝HTTP + JSON涓嶥ubbo 2.x榛樿鐨凴PC鍗忚锛堝嵆TCP + Hessian2浜岃繘鍒跺簭鍒楀寲锛変箣闂村彧鏈1.5鍊嶅乏鍙崇殑宸窛锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 @@ -41,7 +46,7 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p * **dubbox-2.8.2**锛 * 鏀寔REST涓殑HTTP logging锛屽寘鎷琀TTP header鐨勫瓧娈靛拰HTTP body涓殑娑堟伅浣擄紝鏂逛究璋冭瘯銆佹棩蹇楃邯褰曠瓑绛 * 鎻愪緵杈呭姪绫讳究浜嶳EST鐨勪腑鏂囧鐞 - * 鏀瑰彉浣跨敤锝@Reference锝 annotation閰嶇疆鏃剁殑寮傚父澶勭悊鏂瑰紡锛屽嵆褰撶敤annotion閰嶇疆鏃讹紝杩囧幓dubbo鍦ㄥ惎鍔ㄦ湡闂翠笉鎶涘嚭渚濊禆鏈嶅姟鎵句笉鍒扮殑寮傚父锛岃屾槸鍦ㄥ叿浣撹皟鐢ㄦ椂鎶涘嚭NPE锛岃繖涓庣敤XML閰嶇疆鏃剁殑琛屼负涓嶄竴鑷淬 + * 鏀瑰彉浣跨敤`@Reference` annotation閰嶇疆鏃剁殑寮傚父澶勭悊鏂瑰紡锛屽嵆褰撶敤annotation閰嶇疆鏃讹紝杩囧幓dubbo鍦ㄥ惎鍔ㄦ湡闂翠笉鎶涘嚭渚濊禆鏈嶅姟鎵句笉鍒扮殑寮傚父锛岃屾槸鍦ㄥ叿浣撹皟鐢ㄦ椂鎶涘嚭NPE锛岃繖涓庣敤XML閰嶇疆鏃剁殑琛屼负涓嶄竴鑷淬 * 杈冨ぇ鐨勫厖瀹炰簡Dubbo REST鐨勬枃妗 ## FAQ锛堟殏瀛橈級 From ac03e2253fd8e097b4ee9aa3c1450ca548ac2aa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E5=AE=87=E8=BD=A9?= Date: Wed, 19 Nov 2014 15:38:49 +0800 Subject: [PATCH 132/200] =?UTF-8?q?=E7=BD=91=E7=BB=9C=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- version.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 version.txt diff --git a/version.txt b/version.txt new file mode 100644 index 000000000000..e69de29bb2d1 From 731d27c9202a7ad2448e58109f37ae155ceda12d Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 19 Nov 2014 16:59:23 +0800 Subject: [PATCH 133/200] network test --- version | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 version diff --git a/version b/version new file mode 100644 index 000000000000..e69de29bb2d1 From 57c751afea5a68f393730492afedadd5418e8b14 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 19 Nov 2014 17:51:15 +0800 Subject: [PATCH 134/200] remove test files --- version | 0 version.txt | 0 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 version delete mode 100644 version.txt diff --git a/version b/version deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/version.txt b/version.txt deleted file mode 100644 index e69de29bb2d1..000000000000 From 52ace4f192f884acdfe6e459159846dfee1756ed Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 19 Nov 2014 17:57:32 +0800 Subject: [PATCH 135/200] fix bug in annotation config --- .../java/com/alibaba/dubbo/config/spring/AnnotationBean.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java index 58730bff10c9..04afefe348c8 100644 --- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java +++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java @@ -181,7 +181,8 @@ public Object postProcessAfterInitialization(Object bean, String beanName) } if (service.protocol() != null && service.protocol().length > 0) { List protocolConfigs = new ArrayList(); - for (String protocolId : service.registry()) { + // modified by lishen; fix dubbo's bug + for (String protocolId : service.protocol()) { if (protocolId != null && protocolId.length() > 0) { protocolConfigs.add((ProtocolConfig)applicationContext.getBean(protocolId, ProtocolConfig.class)); } From 424e3d9ef7323c95ff185af5955a8ed24ffc243a Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 19 Nov 2014 18:02:32 +0800 Subject: [PATCH 136/200] update docs --- README.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f9343056f971..b902d57d553f 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,17 @@ Dubbox now means Dubbo eXtensions. If you know java, javax and dubbo, you know what dubbox is :) -Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the popular [dubbo service framework](http://github.com/alibaba/dubbo). It鈥檚 now internally used by several projects of [dangdang.com](http://www.dangdang.com), which is one of the major e-commerce companies in China. +Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the popular [dubbo service framework](http://github.com/alibaba/dubbo). It's been used by several projects of [dangdang.com](http://www.dangdang.com), which is one of the major e-commerce companies in China. -**鑱旂郴鏂瑰紡**锛氭矆鐞嗭紙shenli@dangdang.com锛, 鐜嬪畤杞╋紙wangyuxuan@dangdang.com锛 +## 涓昏璐$尞鑰 + +* 娌堢悊 褰撳綋缃 shenli@dangdang.com +* 鐜嬪畤杞 褰撳綋缃 wangyuxuan@dangdang.com +* 椹噾鍑 闊╅兘琛h垗 majk@vip.qq.com +* Dylan 鐙珛寮鍙戣 dinguangx@163.com **璁ㄨQQ缇**锛305896472 -## Dubbox褰撳墠鐨勪富瑕佸姛鑳斤細 +## Dubbox褰撳墠鐨勪富瑕佸姛鑳 * **鏀寔REST椋庢牸杩滅▼璋冪敤锛圚TTP + JSON/XML)**锛氬熀浜庨潪甯告垚鐔熺殑JBoss [RestEasy](http://resteasy.jboss.org/)妗嗘灦锛屽湪dubbo涓疄鐜颁簡REST椋庢牸锛圚TTP + JSON/XML锛夌殑杩滅▼璋冪敤锛屼互鏄捐憲绠鍖栦紒涓氬唴閮ㄧ殑璺ㄨ瑷浜や簰锛屽悓鏃舵樉钁楃畝鍖栦紒涓氬澶栫殑Open API銆佹棤绾緼PI鐢氳嚦AJAX鏈嶅姟绔瓑绛夌殑寮鍙戙備簨瀹炰笂锛岃繖涓猂EST璋冪敤涔熶娇寰桪ubbo鍙互瀵瑰綋浠婄壒鍒祦琛岀殑鈥滃井鏈嶅姟鈥濇灦鏋勬彁渚涘熀纭鎬ф敮鎸併 鍙﹀锛孯EST璋冪敤涔熻揪鍒颁簡姣旇緝楂樼殑鎬ц兘锛屽湪鍩哄噯娴嬭瘯涓嬶紝HTTP + JSON涓嶥ubbo 2.x榛樿鐨凴PC鍗忚锛堝嵆TCP + Hessian2浜岃繘鍒跺簭鍒楀寲锛変箣闂村彧鏈1.5鍊嶅乏鍙崇殑宸窛锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 @@ -41,7 +46,7 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p * **dubbox-2.8.2**锛 * 鏀寔REST涓殑HTTP logging锛屽寘鎷琀TTP header鐨勫瓧娈靛拰HTTP body涓殑娑堟伅浣擄紝鏂逛究璋冭瘯銆佹棩蹇楃邯褰曠瓑绛 * 鎻愪緵杈呭姪绫讳究浜嶳EST鐨勪腑鏂囧鐞 - * 鏀瑰彉浣跨敤锝@Reference锝 annotation閰嶇疆鏃剁殑寮傚父澶勭悊鏂瑰紡锛屽嵆褰撶敤annotion閰嶇疆鏃讹紝杩囧幓dubbo鍦ㄥ惎鍔ㄦ湡闂翠笉鎶涘嚭渚濊禆鏈嶅姟鎵句笉鍒扮殑寮傚父锛岃屾槸鍦ㄥ叿浣撹皟鐢ㄦ椂鎶涘嚭NPE锛岃繖涓庣敤XML閰嶇疆鏃剁殑琛屼负涓嶄竴鑷淬 + * 鏀瑰彉浣跨敤`@Reference` annotation閰嶇疆鏃剁殑寮傚父澶勭悊鏂瑰紡锛屽嵆褰撶敤annotation閰嶇疆鏃讹紝杩囧幓dubbo鍦ㄥ惎鍔ㄦ湡闂翠笉鎶涘嚭渚濊禆鏈嶅姟鎵句笉鍒扮殑寮傚父锛岃屾槸鍦ㄥ叿浣撹皟鐢ㄦ椂鎶涘嚭NPE锛岃繖涓庣敤XML閰嶇疆鏃剁殑琛屼负涓嶄竴鑷淬 * 杈冨ぇ鐨勫厖瀹炰簡Dubbo REST鐨勬枃妗 ## FAQ锛堟殏瀛橈級 From bf2b98c460d4b60fd9f563709e927b5d5f706d7e Mon Sep 17 00:00:00 2001 From: Li Shen Date: Thu, 20 Nov 2014 10:25:19 +0800 Subject: [PATCH 137/200] add validation support for rest --- dubbo-demo/dubbo-demo-api/pom.xml | 4 ++ .../com/alibaba/dubbo/demo/DemoService.java | 22 ------ .../com/alibaba/dubbo/demo/user/User.java | 14 +++- .../user/facade/AnotherUserRestService.java | 3 +- .../demo/user/facade/UserRestService.java | 6 +- .../dubbo/demo/consumer/DemoAction.java | 2 +- .../demo/consumer/DemoJavaConfigAction.java | 2 +- .../dubbo/demo/consumer/RestClient.java | 2 +- .../dubbo/demo/user/UserServiceImpl.java | 2 +- .../AnnotationDrivenUserRestServiceImpl.java | 2 +- .../META-INF/spring/dubbo-demo-provider.xml | 4 +- dubbo-rpc/dubbo-rpc-rest/pom.xml | 7 +- .../rpc/protocol/rest/BaseRestServer.java | 2 + .../rest/RestConstraintViolation.java | 68 +++++++++++++++++++ .../rpc/protocol/rest/RpcExceptionMapper.java | 52 ++++++++++++++ .../rpc/protocol/rest/ViolationReport.java | 50 ++++++++++++++ 16 files changed, 206 insertions(+), 36 deletions(-) delete mode 100644 dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/DemoService.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestConstraintViolation.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcExceptionMapper.java create mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/ViolationReport.java diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index 9a67423b7f1c..dad7caf5f7fa 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -38,5 +38,9 @@ javax.servlet javax.servlet-api + + javax.validation + validation-api + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/DemoService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/DemoService.java deleted file mode 100644 index 7dda95f2d799..000000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/DemoService.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.dubbo.demo; - -public interface DemoService { - - String sayHello(String name); - -} \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/User.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/User.java index e4b43ebf29d7..eb5a3b86f3ca 100644 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/User.java +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/User.java @@ -17,6 +17,11 @@ import org.codehaus.jackson.annotate.JsonProperty; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; @@ -25,11 +30,17 @@ * @author lishen */ @XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) public class User implements Serializable { + @NotNull + @Min(1L) private Long id; -// @JsonProperty("username") + @JsonProperty("username") + @XmlElement(name = "username") + @NotNull + @Size(min = 6, max = 50) private String name; public User() { @@ -48,7 +59,6 @@ public void setId(Long id) { this.id = id; } -// @XmlElement(name = "username") public String getName() { return name; } diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java index 63a993823d89..91ab166133ed 100644 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java @@ -3,6 +3,7 @@ import com.alibaba.dubbo.demo.user.User; import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType; +import javax.validation.constraints.Min; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; @@ -21,7 +22,7 @@ public interface AnotherUserRestService { @GET @Path("{id : \\d+}") - User getUser(@PathParam("id") Long id); + User getUser(@PathParam("id") @Min(1L) Long id); @POST @Path("register") diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestService.java index a349e17a398f..87f28fcd9822 100644 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestService.java +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestService.java @@ -17,6 +17,8 @@ import com.alibaba.dubbo.demo.user.User; +import javax.validation.constraints.Min; + /** * This interface acts as some kind of service broker for the original UserService @@ -30,9 +32,9 @@ public interface UserRestService { /** - * the request object is just used to test jax-rs injection + * the request object is just used to test jax-rs injection. */ - User getUser(Long id/*, HttpServletRequest request*/); + User getUser(@Min(value=1L, message="User ID must be greater than 1") Long id/*, HttpServletRequest request*/); RegistrationResult registerUser(User user); } diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java index f71b5761c39b..a65bd214e78b 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java +++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java @@ -77,7 +77,7 @@ public void start() throws Exception { System.out.println("SUCCESS: caught exception " + e.getClass()); } - User user = new User(1L, "dang"); + User user = new User(1L, "larrypage"); System.out.println("SUCESS: registered user with id " + anotherUserRestService.registerUser(user).getId()); System.out.println("SUCESS: got user " + anotherUserRestService.getUser(1L)); diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigAction.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigAction.java index 19b71c220255..636aba174260 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigAction.java +++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigAction.java @@ -79,7 +79,7 @@ public void start() throws Exception { System.out.println("SUCCESS: caught exception " + e.getClass()); } - User user = new User(1L, "dang"); + User user = new User(1L, "larrypage"); System.out.println("SUCESS: registered user with id " + anotherUserRestService.registerUser(user).getId()); System.out.println("SUCESS: got user " + anotherUserRestService.getUser(1L)); diff --git a/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/RestClient.java b/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/RestClient.java index 578423ead714..b8fd5fddba81 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/RestClient.java +++ b/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/RestClient.java @@ -70,7 +70,7 @@ public static void main(String[] args) { private static void registerUser(String url, MediaType mediaType) { System.out.println("Registering user via " + url); - User user = new User(1L, "dang"); + User user = new User(1L, "larrypage"); Client client = ClientBuilder.newClient(); WebTarget target = client.target(url); Response response = target.request().post(Entity.entity(user, mediaType)); diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/UserServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/UserServiceImpl.java index ef3ba3483170..e722a01573f2 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/UserServiceImpl.java +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/UserServiceImpl.java @@ -25,7 +25,7 @@ public class UserServiceImpl implements UserService { private final AtomicLong idGen = new AtomicLong(); public User getUser(Long id) { - return new User(id, "dang" + id); + return new User(id, "username" + id); } diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java index 2f67034873ad..e7dd278dacd3 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java @@ -32,7 +32,7 @@ /** * @author lishen */ -@Service(protocol = "rest", group = "annotationConfig") +@Service(protocol = {"rest", "dubbo"}, group = "annotationConfig", validation = "true") @Path("customers") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) @Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index c7d60bc941bc..0576b782ff24 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -66,8 +66,8 @@ - - + + diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml index 394844f8d3d2..b2fd1b5037f4 100644 --- a/dubbo-rpc/dubbo-rpc-rest/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml @@ -141,6 +141,9 @@ resteasy-jaxb-provider 3.0.7.Final - - + + javax.validation + validation-api + + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/BaseRestServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/BaseRestServer.java index dca66e2421c7..a788043e669d 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/BaseRestServer.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/BaseRestServer.java @@ -30,6 +30,8 @@ public void start(URL url) { getDeployment().getMediaTypeMappings().put("xml", "text/xml"); // server.getDeployment().getMediaTypeMappings().put("xml", "application/xml"); getDeployment().getProviderClasses().add(RpcContextFilter.class.getName()); + // TODO users can override this mapper, but we just rely on the current priority strategy of resteasy + getDeployment().getProviderClasses().add(RpcExceptionMapper.class.getName()); loadProviders(url.getParameter(Constants.EXTENSION_KEY, "")); diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestConstraintViolation.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestConstraintViolation.java new file mode 100644 index 000000000000..8c73243efce3 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestConstraintViolation.java @@ -0,0 +1,68 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * @author lishen + */ +@XmlRootElement(name = "constraintViolation") +@XmlAccessorType(XmlAccessType.FIELD) +public class RestConstraintViolation implements Serializable { + + private static final long serialVersionUID = -23497234978L; + + private String path; + private String message; + private String value; + + public RestConstraintViolation(String path, String message, String value) { + this.path = path; + this.message = message; + this.value = value; + } + + public RestConstraintViolation() { + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcExceptionMapper.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcExceptionMapper.java new file mode 100644 index 000000000000..e654cec6cd15 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcExceptionMapper.java @@ -0,0 +1,52 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType; + +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + +/** + * @author lishen + */ +public class RpcExceptionMapper implements ExceptionMapper { + + public Response toResponse(RpcException e) { + // TODO do more sophisticated exception handling and output + if (e.getCause() instanceof ConstraintViolationException) { + return handleConstraintViolationException((ConstraintViolationException) e.getCause()); + } + // we may want to avoid exposing the dubbo exception details to certain clients + // TODO for now just do plain text output + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Internal server error: " + e.getMessage()).type("text/plain").build(); + } + + protected Response handleConstraintViolationException(ConstraintViolationException cve) { + ViolationReport report = new ViolationReport(); + for (ConstraintViolation cv : cve.getConstraintViolations()) { + report.addConstraintViolation(new RestConstraintViolation( + cv.getPropertyPath().toString(), + cv.getMessage(), + cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString())); + } + // TODO for now just do xml output + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.TEXT_XML_UTF_8).build(); + } +} diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/ViolationReport.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/ViolationReport.java new file mode 100644 index 000000000000..4fa6e5dd086b --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/ViolationReport.java @@ -0,0 +1,50 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.rpc.protocol.rest; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; +import java.util.LinkedList; +import java.util.List; + +/** + * @author lishen + */ +@XmlRootElement(name="violationReport") +@XmlAccessorType(XmlAccessType.FIELD) +public class ViolationReport implements Serializable { + + private static final long serialVersionUID = -130498234L; + + private List constraintViolations; + + public List getConstraintViolations() { + return constraintViolations; + } + + public void setConstraintViolations(List constraintViolations) { + this.constraintViolations = constraintViolations; + } + + public void addConstraintViolation(RestConstraintViolation constraintViolation) { + if (constraintViolations == null) { + constraintViolations = new LinkedList(); + } + constraintViolations.add(constraintViolation); + } +} From 600ed7526dd609bd348d07aa699cb28a6118233e Mon Sep 17 00:00:00 2001 From: Li Shen Date: Thu, 20 Nov 2014 14:13:41 +0800 Subject: [PATCH 138/200] update docs --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b902d57d553f..911889d35ea2 100644 --- a/README.md +++ b/README.md @@ -4,9 +4,9 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p ## 涓昏璐$尞鑰 -* 娌堢悊 褰撳綋缃 shenli@dangdang.com -* 鐜嬪畤杞 褰撳綋缃 wangyuxuan@dangdang.com -* 椹噾鍑 闊╅兘琛h垗 majk@vip.qq.com +* 娌堢悊 [褰撳綋缃慮(http://www.dangdang.com/) shenli@dangdang.com +* 鐜嬪畤杞 [褰撳綋缃慮(http://www.dangdang.com/) wangyuxuan@dangdang.com +* 椹噾鍑 [闊╅兘琛h垗](http://www.handu.com/) majinkai@handu.com * Dylan 鐙珛寮鍙戣 dinguangx@163.com **璁ㄨQQ缇**锛305896472 From cd34f41abbfb92b193d70ded26d35a5b3906f20a Mon Sep 17 00:00:00 2001 From: Li Shen Date: Fri, 21 Nov 2014 10:41:37 +0800 Subject: [PATCH 139/200] add request/response support in RpcContext --- .../demo/user/facade/UserRestServiceImpl.java | 9 +++++ .../com/alibaba/dubbo/rpc/RpcContext.java | 33 ++++++++++++++++++- .../rpc/protocol/rest/RpcContextFilter.java | 10 +++--- 3 files changed, 47 insertions(+), 5 deletions(-) diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java index 21e44a80c404..5c37c4921775 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java @@ -19,8 +19,11 @@ import com.alibaba.dubbo.demo.user.UserService; import com.alibaba.dubbo.demo.user.facade.RegistrationResult; import com.alibaba.dubbo.demo.user.facade.UserRestService; +import com.alibaba.dubbo.rpc.RpcContext; import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; @@ -51,6 +54,12 @@ public User getUser(@PathParam("id") Long id/*, @Context HttpServletRequest requ // test context injection // System.out.println("Client address from @Context injection: " + (request != null ? request.getRemoteAddr() : "")); // System.out.println("Client address from RpcContext: " + RpcContext.getContext().getRemoteAddressString()); + if (RpcContext.getContext().getRequest() != null && RpcContext.getContext().getRequest() instanceof HttpServletRequest) { + System.out.println("Client IP address from RpcContext: " + ((HttpServletRequest) RpcContext.getContext().getRequest()).getRemoteAddr()); + } + if (RpcContext.getContext().getResponse() != null && RpcContext.getContext().getResponse() instanceof HttpServletResponse) { + System.out.println("Response object from RpcContext: " + RpcContext.getContext().getResponse()); + } return userService.getUser(id); } diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java index 25a34f4b6204..7a4107dadf0b 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java @@ -89,7 +89,12 @@ public static void removeContext() { private final Map attachments = new HashMap(); private final Map values = new HashMap(); - + + // now we don't use the 'values' map to hold these objects + // we want these objects to be as generic as possible + private Object request; + private Object response; + @Deprecated private List> invokers; @@ -102,6 +107,32 @@ public static void removeContext() { protected RpcContext() { } + /** + * Get the request object of the underlying RPC protocol, e.g. HttServletRequest + * + * @return null if the underlying protocol doesn't provide support for getting request + */ + public Object getRequest() { + return request; + } + + public void setRequest(Object request) { + this.request = request; + } + + /** + * Get the response object of the underlying RPC protocol, e.g. HttServletResponse + * + * @return null if the underlying protocol doesn't provide support for getting response + */ + public Object getResponse() { + return response; + } + + public void setResponse(Object response) { + this.response = response; + } + /** * is provider side. * diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java index 1de7403016be..a9667c432d85 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java @@ -19,6 +19,7 @@ import org.jboss.resteasy.spi.ResteasyProviderFactory; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import java.io.IOException; @@ -29,13 +30,14 @@ public class RpcContextFilter implements ContainerRequestFilter { public void filter(ContainerRequestContext requestContext) throws IOException { - if (RpcContext.getContext().getRemoteAddress() != null) { - return; - } HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class); + RpcContext.getContext().setRequest(request); + // this only works for servlet containers - if (request != null) { + if (request != null && RpcContext.getContext().getRemoteAddress() == null) { RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); } + + RpcContext.getContext().setResponse(ResteasyProviderFactory.getContextData(HttpServletResponse.class)); } } From 345b228c666ac89e5f70730eac815704b470033c Mon Sep 17 00:00:00 2001 From: Li Shen Date: Fri, 21 Nov 2014 14:30:23 +0800 Subject: [PATCH 140/200] remove old files --- .../resources/Acme/Resource/mime.properties | 104 ------------------ 1 file changed, 104 deletions(-) delete mode 100644 dubbo-rpc/dubbo-rpc-rest/src/main/resources/Acme/Resource/mime.properties diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/Acme/Resource/mime.properties b/dubbo-rpc/dubbo-rpc-rest/src/main/resources/Acme/Resource/mime.properties deleted file mode 100644 index f3afc3999bff..000000000000 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/resources/Acme/Resource/mime.properties +++ /dev/null @@ -1,104 +0,0 @@ -# $Id: mime.properties,v 1.1 2009/12/10 04:30:50 dmitriy Exp $ -HTML=text/html -HTM=text/html -TXT=text/plain -XML=text/xml -CSS=text/css -SGML=text/x-sgml -SGM=text/x-sgml -GIF=image/gif -JPG=image/jpeg -JPEG=image/jpeg -JPE=image/jpeg -PNG=image/png -BMP=image/bmp -TIF=image/tiff -TIFF=image/tiff -RGB=image/x-rgb -XPM=image/x-xpixmap -XBM=image/x-xbitmap -SVG=image/svg-xml -SVGZ=image/svg-xml -# Audio -AU=audio/basic -SND=audio/basic -MID=audio/mid -MIDI=audio/mid -RMI=audio/mid -KAR=audio/mid -MPGA=audio/mpeg -MP2=audio/mpeg -MP3=audio/mpeg -WAV=audio/wav -AIFF=audio/aiff -AIFC=audio/aiff -AIF=audio/x-aiff -RA=audio/x-realaudio -RPM=audio/x-pn-realaudio-plugin -RAM=audio/x-pn-realaudio -SD2=audio/x-sd2 -# Applications -BIN=application/octet-stream -DMS=application/octet-stream -LHA=application/octet-stream -LZH=application/octet-stream -EXE=application/octet-stream -DLL=application/octet-stream -CLASS=application/octet-stream -HQX=application/mac-binhex40 -PS=application/postscript -AI=application/postscript -EPS=application/postscript -PDF=application/pdf -RTF=application/rtf -DOC=application/msword -DOCX=application/msword -PPT=application/powerpoint -PPTX=application/powerpoint -FIF=application/fractals -P7C=application/pkcs7-mime -# Application/x -JS=application/x-javascript -Z=application/x-compress -GZ=application/x-gzip -TAR=application/x-tar -TGZ=application/x-compressed -ZIP=application/x-zip-compressed -DIR=application/x-director -DCR=application/x-director -DXR=application/x-director -DVI=application/x-dvi -TEX=application/x-tex -LATEX=application/x-latex -TCL=application/x-tcl -CER=application/x-x509-ca-cert -CRT=application/x-x509-ca-cert -DER=application/x-x509-ca-cert -ISO=application/x-iso9660-image -# Video -MPG=video/mpeg -MPE=video/mpeg -MPEG=video/mpeg -QT=video/quicktime -MOV=video/quicktime -AVI=video/x-msvideo -MOVIE=video/x-sgi-movie -# Chemical -PDB=chemical/x-pdb -XYZ=chemical/x-pdb -# X- -ICE=x-conference/x-cooltalk -JNLP=application/x-java-jnlp-file -WRL=x-world/x-vrml -VRML=x-world/x-vrml -WML=text/vnd.wap.wml -WMLC=application/vnd.wap.wmlc -WMLS=text/vnd.wap.wmlscript -WMLSC=application/vnd.wap.wmlscriptc -WBMP=image/vnd.wap.wbmp -FLAC=audio/flac -OGG=audio/ogg -OGA=audio/ogg -SPX=audio/ogg -OGV=video/ogg -OGX=application/ogg \ No newline at end of file From 604a840221c690c5af29b3a8b049da667730a900 Mon Sep 17 00:00:00 2001 From: Jinkai Ma Date: Fri, 21 Nov 2014 17:29:33 +0800 Subject: [PATCH 141/200] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dadmin=E6=B2=A1?= =?UTF-8?q?=E6=9C=89consumer=E6=97=B6=E5=87=BA=E7=8E=B0=E7=A9=BA=E6=8C=87?= =?UTF-8?q?=E9=92=88=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dubbo/governance/service/impl/ConsumerServiceImpl.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConsumerServiceImpl.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConsumerServiceImpl.java index bd236c293293..106d3c0a1655 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConsumerServiceImpl.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/service/impl/ConsumerServiceImpl.java @@ -76,6 +76,8 @@ public List findAddresses() { public List findAddressesByApplication(String application) { List ret = new ArrayList(); ConcurrentMap> consumerUrls = getRegistryCache().get(Constants.CONSUMERS_CATEGORY); + if(consumerUrls == null) return ret; + for(Map.Entry> e1 : consumerUrls.entrySet()) { Map value = e1.getValue(); for(Map.Entry e2 : value.entrySet()) { From 32fc31953982252cbe524b9284d543dd0ffc3d87 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Tue, 25 Nov 2014 15:01:33 +0800 Subject: [PATCH 142/200] update versions --- README.md | 19 +++++++++++--- dubbo-admin/pom.xml | 2 +- dubbo-cluster/pom.xml | 2 +- dubbo-common/pom.xml | 2 +- dubbo-config/dubbo-config-api/pom.xml | 2 +- dubbo-config/dubbo-config-spring/pom.xml | 2 +- dubbo-config/pom.xml | 2 +- dubbo-container/dubbo-container-api/pom.xml | 2 +- .../dubbo-container-javaconfig/pom.xml | 2 +- dubbo-container/dubbo-container-jetty/pom.xml | 2 +- dubbo-container/dubbo-container-log4j/pom.xml | 2 +- .../dubbo-container-logback/pom.xml | 2 +- .../dubbo-container-spring/pom.xml | 2 +- dubbo-container/pom.xml | 2 +- dubbo-demo/dubbo-demo-api/pom.xml | 2 +- dubbo-demo/dubbo-demo-consumer/pom.xml | 2 +- dubbo-demo/dubbo-demo-provider/pom.xml | 2 +- .../demo/user/facade/UserRestServiceImpl.java | 8 +++--- dubbo-demo/pom.xml | 2 +- dubbo-filter/dubbo-filter-cache/pom.xml | 2 +- dubbo-filter/dubbo-filter-validation/pom.xml | 2 +- dubbo-filter/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-api/pom.xml | 2 +- dubbo-monitor/dubbo-monitor-default/pom.xml | 2 +- dubbo-monitor/pom.xml | 2 +- dubbo-registry/dubbo-registry-api/pom.xml | 2 +- dubbo-registry/dubbo-registry-default/pom.xml | 2 +- .../dubbo-registry-multicast/pom.xml | 2 +- dubbo-registry/dubbo-registry-redis/pom.xml | 2 +- .../dubbo-registry-zookeeper/pom.xml | 2 +- dubbo-registry/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-api/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-http/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-mina/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-netty/pom.xml | 2 +- dubbo-remoting/dubbo-remoting-p2p/pom.xml | 2 +- .../dubbo-remoting-zookeeper/pom.xml | 2 +- dubbo-remoting/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-api/pom.xml | 2 +- .../com/alibaba/dubbo/rpc/RpcContext.java | 25 +++++++++++++++++-- dubbo-rpc/dubbo-rpc-default/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-hessian/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-http/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-injvm/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-memcached/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-redis/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rest/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-rmi/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-thrift/pom.xml | 2 +- dubbo-rpc/dubbo-rpc-webservice/pom.xml | 2 +- dubbo-rpc/pom.xml | 2 +- dubbo-simple/dubbo-monitor-simple/pom.xml | 2 +- dubbo-simple/dubbo-registry-simple/pom.xml | 2 +- dubbo-simple/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark-api/pom.xml | 2 +- .../dubbo-test-benchmark-client/pom.xml | 2 +- .../dubbo-test-benchmark-server/pom.xml | 2 +- dubbo-test/dubbo-test-benchmark/pom.xml | 2 +- dubbo-test/dubbo-test-compatibility/pom.xml | 2 +- dubbo-test/dubbo-test-examples/pom.xml | 2 +- dubbo-test/dubbo-test-integration/pom.xml | 2 +- dubbo-test/pom.xml | 2 +- dubbo/pom.xml | 2 +- hessian-lite/pom.xml | 2 +- pom.xml | 14 ++++++++++- 66 files changed, 118 insertions(+), 72 deletions(-) diff --git a/README.md b/README.md index 911889d35ea2..744abdb84a3e 100644 --- a/README.md +++ b/README.md @@ -17,15 +17,19 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p * **鏀寔鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡綋浠婃瘮杈冪煡鍚嶇殑[Kryo](https://github.com/EsotericSoftware/kryo)鍜孾FST](https://github.com/RuedigerMoeller/fast-serialization)楂樻ц兘搴忓垪鍖栧簱锛屼负Dubbo 榛樿鐨凴PC鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜咲ubbo RPC鐨勬ц兘锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 +* **鏀寔鍩轰簬Jackson鐨凧SON搴忓垪鍖**锛 + * **鏀寔鍩轰簬宓屽叆寮廡omcat鐨凥TTP remoting浣撶郴**锛氬熀浜庡祵鍏ュ紡tomcat瀹炵幇dubbo鐨凥TTP remoting浣撶郴锛堝嵆dubbo-remoting-http锛夛紝鐢ㄤ互閫愭鍙栦唬Dubbo涓棫鐗堟湰鐨勫祵鍏ュ紡Jetty锛屽彲浠ユ樉钁楃殑鎻愰珮REST绛夌殑杩滅▼璋冪敤鎬ц兘锛屽苟灏哠ervlet API鐨勬敮鎸佷粠2.5鍗囩骇鍒3.1銆傦紙娉細闄や簡REST锛宒ubbo涓殑WebServices銆丠essian銆丠TTP Invoker绛夊崗璁兘鍩轰簬杩欎釜HTTP remoting浣撶郴锛夈 -* **鍗囩骇Spring**锛氬皢dubbo涓璖pring鐢2.x鍗囩骇鍒扮洰鍓嶆渶甯哥敤鐨3.x鐗堟湰锛屽噺灏戠増鏈啿绐佸甫鏉ョ殑楹荤儲 +* **鍗囩骇Spring**锛氬皢dubbo涓璖pring鐢2.x鍗囩骇鍒扮洰鍓嶆渶甯哥敤鐨3.x鐗堟湰锛屽噺灏戠増鏈啿绐佸甫鏉ョ殑楹荤儲銆 * **鍗囩骇ZooKeeper瀹㈡埛绔**锛氬皢dubbo涓殑zookeeper瀹㈡埛绔崌绾у埌鏈鏂扮殑鐗堟湰锛屼互淇鑰佺増鏈腑鍖呭惈鐨刡ug銆 -* **璋冩暣Demo搴旂敤**锛氭殏鏃跺皢dubbo鐨刣emo搴旂敤璋冩暣骞舵敼鍐欎互涓昏婕旂ずREST鍔熻兘鍜屾柊鐨凧ava楂樻晥搴忓垪鍖栫瓑绛夈 +* **鏀寔鍩轰簬Java浠g爜鐨凷pring閰嶇疆**锛 + +* **璋冩暣Demo搴旂敤**锛氭殏鏃跺皢dubbo鐨刣emo搴旂敤璋冩暣骞舵敼鍐欎互涓昏婕旂ずREST鍔熻兘銆丏ubbo鍗忚鐨勬柊搴忓垪鍖栨柟寮忋佸熀浜嶫ava浠g爜鐨凷pring閰嶇疆绛夌瓑銆 -* **淇浜嗗湪JDK1.7涓奷ubbo鐨勯儴鍒哹ug**锛氫慨姝d簡姣斿dubbo鍗忚涓璲son搴忓垪鍖栫殑闂銆備絾鏄繕娌℃湁淇鎵鏈夊彂鐜扮殑bug銆 +* **淇浜哾ubbo鐨刡ug** 鍖呮嫭閰嶇疆銆佸簭鍒楀寲銆佺鐞嗙晫闈㈢瓑绛夌殑bug銆 **娉細dubbox鍜宒ubbo 2.x鏄吋瀹圭殑锛屾病鏈夋敼鍙榙ubbo鐨勪换浣曞凡鏈夌殑鍔熻兘鍜岄厤缃柟寮忥紙闄や簡鍗囩骇浜唖pring涔嬬被鐨勭増鏈級** @@ -48,6 +52,15 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p * 鎻愪緵杈呭姪绫讳究浜嶳EST鐨勪腑鏂囧鐞 * 鏀瑰彉浣跨敤`@Reference` annotation閰嶇疆鏃剁殑寮傚父澶勭悊鏂瑰紡锛屽嵆褰撶敤annotation閰嶇疆鏃讹紝杩囧幓dubbo鍦ㄥ惎鍔ㄦ湡闂翠笉鎶涘嚭渚濊禆鏈嶅姟鎵句笉鍒扮殑寮傚父锛岃屾槸鍦ㄥ叿浣撹皟鐢ㄦ椂鎶涘嚭NPE锛岃繖涓庣敤XML閰嶇疆鏃剁殑琛屼负涓嶄竴鑷淬 * 杈冨ぇ鐨勫厖瀹炰簡Dubbo REST鐨勬枃妗 +* **dubbox-2.8.3**锛 + * 鍦≧EST涓敮鎸乨ubbo缁熶竴鐨勬柟寮忕敤bean validation annotation浣滃弬鏁版牎楠岋紙娌堢悊锛 + * 鍦≧pcContext涓婃敮鎸佽幏鍙栧簳灞傚崗璁殑Request/Response锛堟矆鐞嗭級 + * 鏀寔閲囩敤Spring鐨凧ava Config鏂瑰紡閰嶇疆dubbo锛堥┈閲戝嚡锛 + * 鍦―ubbo鍗忚涓敮鎸佸熀浜嶫ackson鐨刯son搴忓垪鍖栵紙Dylan锛 + * 鍦⊿pring AOP浠g悊杩囩殑瀵硅薄涓婃敮鎸乨ubbo annotation閰嶇疆锛圖ylan锛 + * 淇Dubbo绠$悊鐣岄潰涓病鏈塩onsumer鏃跺嚭鐜扮┖鎸囬拡寮傚父锛堥┈閲戝嚡锛 + * 淇@Reference annotation涓璸rotocol璁剧疆涓嶈捣浣滅敤鐨刡ug锛堟矆鐞嗭級 + * 淇@Reference annotation鏀惧湪setter鏂规硶涓婂嵆浼氬嚭閿欑殑bug锛圖ylan锛 ## FAQ锛堟殏瀛橈級 diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index 2649a9f4c68d..40738e793673 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-admin war diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index d9dfad2d30dc..b3f6818440b5 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-cluster jar diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index cac18d5113d8..0fd4705f3535 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-common jar diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 07ae2702dc08..95180e8bb5ad 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.8.2 + 2.8.3 dubbo-config-api jar diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 3fc85bcb4a33..c4d2a8771e41 100644 --- a/dubbo-config/dubbo-config-spring/pom.xml +++ b/dubbo-config/dubbo-config-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-config - 2.8.2 + 2.8.3 dubbo-config-spring jar diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index 7c36ce60ab63..f2bbcbf5d69e 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index 7b156a1bbf54..17587930fb68 100644 --- a/dubbo-container/dubbo-container-api/pom.xml +++ b/dubbo-container/dubbo-container-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.2 + 2.8.3 dubbo-container-api jar diff --git a/dubbo-container/dubbo-container-javaconfig/pom.xml b/dubbo-container/dubbo-container-javaconfig/pom.xml index d0bfe6a0e0ae..bdc600557fe9 100644 --- a/dubbo-container/dubbo-container-javaconfig/pom.xml +++ b/dubbo-container/dubbo-container-javaconfig/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.2 + 2.8.3 dubbo-container-javaconfig jar diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index c0def190054b..e130f94de31e 100644 --- a/dubbo-container/dubbo-container-jetty/pom.xml +++ b/dubbo-container/dubbo-container-jetty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.2 + 2.8.3 dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index 0e7b60aa0af2..42b1d97a41cf 100644 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ b/dubbo-container/dubbo-container-log4j/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.2 + 2.8.3 dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index 7551c504e098..b74d2fe49ac1 100644 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ b/dubbo-container/dubbo-container-logback/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.2 + 2.8.3 dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index 7f4caadbe1f0..f6dfd0bcf2df 100644 --- a/dubbo-container/dubbo-container-spring/pom.xml +++ b/dubbo-container/dubbo-container-spring/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-container - 2.8.2 + 2.8.3 dubbo-container-spring jar diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index 3cbeace8bfc5..0a11e727390b 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-container pom diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index dad7caf5f7fa..0b3df71b6365 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.2 + 2.8.3 dubbo-demo-api jar diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml index da3966df760f..237843945fe8 100644 --- a/dubbo-demo/dubbo-demo-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-consumer/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.2 + 2.8.3 dubbo-demo-consumer jar diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml index 406d388cadba..f71f03f06228 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-demo - 2.8.2 + 2.8.3 dubbo-demo-provider war diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java index 5c37c4921775..659a82035108 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java @@ -54,11 +54,11 @@ public User getUser(@PathParam("id") Long id/*, @Context HttpServletRequest requ // test context injection // System.out.println("Client address from @Context injection: " + (request != null ? request.getRemoteAddr() : "")); // System.out.println("Client address from RpcContext: " + RpcContext.getContext().getRemoteAddressString()); - if (RpcContext.getContext().getRequest() != null && RpcContext.getContext().getRequest() instanceof HttpServletRequest) { - System.out.println("Client IP address from RpcContext: " + ((HttpServletRequest) RpcContext.getContext().getRequest()).getRemoteAddr()); + if (RpcContext.getContext().getRequest(HttpServletRequest.class) != null) { + System.out.println("Client IP address from RpcContext: " + RpcContext.getContext().getRequest(HttpServletRequest.class).getRemoteAddr()); } - if (RpcContext.getContext().getResponse() != null && RpcContext.getContext().getResponse() instanceof HttpServletResponse) { - System.out.println("Response object from RpcContext: " + RpcContext.getContext().getResponse()); + if (RpcContext.getContext().getResponse(HttpServletResponse.class) != null) { + System.out.println("Response object from RpcContext: " + RpcContext.getContext().getResponse(HttpServletResponse.class)); } return userService.getUser(id); } diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml index a86490c5f89a..05e9a671b044 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-demo pom diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 05f3278ef179..9e5ee4e974a1 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.8.2 + 2.8.3 dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index 87102ace75cb..99555f86d10a 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-filter - 2.8.2 + 2.8.3 dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index 2fd68fdf5edb..b5cb71737550 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-filter pom diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index f2b1de4f0d0b..2aa23613698c 100644 --- a/dubbo-monitor/dubbo-monitor-api/pom.xml +++ b/dubbo-monitor/dubbo-monitor-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.8.2 + 2.8.3 dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index 990b4de0b6d4..fe93f4ae359b 100644 --- a/dubbo-monitor/dubbo-monitor-default/pom.xml +++ b/dubbo-monitor/dubbo-monitor-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-monitor - 2.8.2 + 2.8.3 dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index 1f0476f41abd..9181394e4f46 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 94da9ccd05c4..e8ddb66de429 100644 --- a/dubbo-registry/dubbo-registry-api/pom.xml +++ b/dubbo-registry/dubbo-registry-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.2 + 2.8.3 dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index 20bb33c2adcf..558672125188 100644 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ b/dubbo-registry/dubbo-registry-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.2 + 2.8.3 dubbo-registry-default jar diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index 4166a86f24f9..9eb3763e7a07 100644 --- a/dubbo-registry/dubbo-registry-multicast/pom.xml +++ b/dubbo-registry/dubbo-registry-multicast/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.2 + 2.8.3 dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index ab2316dfe5f8..fcd0ed3c35c4 100644 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ b/dubbo-registry/dubbo-registry-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.2 + 2.8.3 dubbo-registry-redis jar diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index 2c91b8e37c69..d843b00c89ac 100644 --- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml +++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-registry - 2.8.2 + 2.8.3 dubbo-registry-zookeeper jar diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index e2c6d5b9a842..b0b74ea2bc5f 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-registry pom diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index 45f213fdc2f1..6b4474d92a52 100644 --- a/dubbo-remoting/dubbo-remoting-api/pom.xml +++ b/dubbo-remoting/dubbo-remoting-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.2 + 2.8.3 dubbo-remoting-api jar diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml index 2237885dfe83..744f47c4764d 100644 --- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml +++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.2 + 2.8.3 dubbo-remoting-grizzly jar diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index d0273a679663..7fb25c527de2 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.2 + 2.8.3 dubbo-remoting-http jar diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml index 687bb3d709c9..b0a1198630d4 100644 --- a/dubbo-remoting/dubbo-remoting-mina/pom.xml +++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.2 + 2.8.3 dubbo-remoting-mina jar diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index f920b18f20fe..adad78b783b2 100644 --- a/dubbo-remoting/dubbo-remoting-netty/pom.xml +++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.2 + 2.8.3 dubbo-remoting-netty jar diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml index 7394b026387f..604ca605101e 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml +++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.2 + 2.8.3 dubbo-remoting-p2p jar diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index 9868baa75e67..d85e71039806 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-remoting - 2.8.2 + 2.8.3 dubbo-remoting-zookeeper jar diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 99bb82b069e2..a8751dcfe9e5 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -18,7 +18,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-remoting pom diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index 74fc65130e66..49bd1f6e023d 100644 --- a/dubbo-rpc/dubbo-rpc-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-api/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.2 + 2.8.3 dubbo-rpc-api jar diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java index 7a4107dadf0b..e0d6cd752366 100644 --- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/RpcContext.java @@ -108,7 +108,7 @@ protected RpcContext() { } /** - * Get the request object of the underlying RPC protocol, e.g. HttServletRequest + * Get the request object of the underlying RPC protocol, e.g. HttpServletRequest * * @return null if the underlying protocol doesn't provide support for getting request */ @@ -116,12 +116,23 @@ public Object getRequest() { return request; } + /** + * Get the request object of the underlying RPC protocol, e.g. HttpServletRequest + * + * @return null if the underlying protocol doesn't provide support for getting request or the request is not of the specified type + */ + @SuppressWarnings("unchecked") + public T getRequest(Class clazz) { + return (request != null && clazz.isAssignableFrom(request.getClass())) ? (T) request : null; + } + + public void setRequest(Object request) { this.request = request; } /** - * Get the response object of the underlying RPC protocol, e.g. HttServletResponse + * Get the response object of the underlying RPC protocol, e.g. HttpServletResponse * * @return null if the underlying protocol doesn't provide support for getting response */ @@ -129,6 +140,16 @@ public Object getResponse() { return response; } + /** + * Get the response object of the underlying RPC protocol, e.g. HttpServletResponse + * + * @return null if the underlying protocol doesn't provide support for getting response or the response is not of the specified type + */ + @SuppressWarnings("unchecked") + public T getResponse(Class clazz) { + return (response != null && clazz.isAssignableFrom(response.getClass())) ? (T) response : null; + } + public void setResponse(Object response) { this.response = response; } diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index 33177c110a56..7c2a16d35716 100644 --- a/dubbo-rpc/dubbo-rpc-default/pom.xml +++ b/dubbo-rpc/dubbo-rpc-default/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.2 + 2.8.3 dubbo-rpc-default jar diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index 400639440535..4010b9b3c1bb 100644 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.2 + 2.8.3 dubbo-rpc-hessian jar diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index 569f7fb9c2fe..c74dba205558 100644 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ b/dubbo-rpc/dubbo-rpc-http/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.2 + 2.8.3 dubbo-rpc-http jar diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index 3f1f85ec6fe3..03bd369d8533 100644 --- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml +++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.2 + 2.8.3 dubbo-rpc-injvm jar diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml index 46d91e20b0b8..d99c29f63e67 100644 --- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml +++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.2 + 2.8.3 dubbo-rpc-memcached jar diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml index dca41fd1d16f..f3fe7af03232 100644 --- a/dubbo-rpc/dubbo-rpc-redis/pom.xml +++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.2 + 2.8.3 dubbo-rpc-redis jar diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml index b2fd1b5037f4..de1328ddb1cc 100644 --- a/dubbo-rpc/dubbo-rpc-rest/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.2 + 2.8.3 dubbo-rpc-rest jar diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml index c2f185f8e998..fd60d58701cf 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml +++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.2 + 2.8.3 dubbo-rpc-rmi jar diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml index d08a9926390f..c02426ee2d3f 100644 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ b/dubbo-rpc/dubbo-rpc-thrift/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.2 + 2.8.3 dubbo-rpc-thrift jar diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml index f8be327b3d74..dfe06dd391eb 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml +++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-rpc - 2.8.2 + 2.8.3 dubbo-rpc-webservice jar diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 675ff8701ad4..25b076c2239c 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-rpc pom diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml index e8aaa37de420..eebb21d03acb 100644 --- a/dubbo-simple/dubbo-monitor-simple/pom.xml +++ b/dubbo-simple/dubbo-monitor-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.8.2 + 2.8.3 dubbo-monitor-simple jar diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml index 8eb5f3c9d92e..9a66eb905355 100644 --- a/dubbo-simple/dubbo-registry-simple/pom.xml +++ b/dubbo-simple/dubbo-registry-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-simple - 2.8.2 + 2.8.3 dubbo-registry-simple jar diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml index d64d5d276e8a..f66c7f497d54 100644 --- a/dubbo-simple/pom.xml +++ b/dubbo-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-simple pom diff --git a/dubbo-test/dubbo-test-benchmark-api/pom.xml b/dubbo-test/dubbo-test-benchmark-api/pom.xml index 80a337860948..03287eadbbad 100644 --- a/dubbo-test/dubbo-test-benchmark-api/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-api/pom.xml @@ -4,7 +4,7 @@ com.alibaba dubbo-test - 2.8.2 + 2.8.3 dubbo-test-benchmark-api jar diff --git a/dubbo-test/dubbo-test-benchmark-client/pom.xml b/dubbo-test/dubbo-test-benchmark-client/pom.xml index f1dd990ed287..f467b9b5510a 100644 --- a/dubbo-test/dubbo-test-benchmark-client/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-client/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.2 + 2.8.3 dubbo-test-benchmark-client jar diff --git a/dubbo-test/dubbo-test-benchmark-server/pom.xml b/dubbo-test/dubbo-test-benchmark-server/pom.xml index f669e6e6be6c..9caea44212a9 100644 --- a/dubbo-test/dubbo-test-benchmark-server/pom.xml +++ b/dubbo-test/dubbo-test-benchmark-server/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.2 + 2.8.3 dubbo-test-benchmark-server jar diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml index 4882dc29824f..b9338265cfb5 100644 --- a/dubbo-test/dubbo-test-benchmark/pom.xml +++ b/dubbo-test/dubbo-test-benchmark/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.2 + 2.8.3 dubbo-test-benchmark jar diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml index 162572190087..cd005173b762 100644 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ b/dubbo-test/dubbo-test-compatibility/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.2 + 2.8.3 dubbo-test-compatibility jar diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml index 06d2f7a2e5c7..801876019e36 100644 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ b/dubbo-test/dubbo-test-examples/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.2 + 2.8.3 dubbo-test-examples jar diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml index cef01a44c905..5a5065a08b2a 100644 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ b/dubbo-test/dubbo-test-integration/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-test - 2.8.2 + 2.8.3 dubbo-test-integration jar diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml index c0d5e764bc60..c3f79938f685 100644 --- a/dubbo-test/pom.xml +++ b/dubbo-test/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo-test pom diff --git a/dubbo/pom.xml b/dubbo/pom.xml index ec6d45ff953f..130815d23ed9 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 dubbo jar diff --git a/hessian-lite/pom.xml b/hessian-lite/pom.xml index 938e71224009..535e8de68adf 100644 --- a/hessian-lite/pom.xml +++ b/hessian-lite/pom.xml @@ -6,7 +6,7 @@ com.alibaba dubbo-parent - 2.8.2 + 2.8.3 hessian-lite jar diff --git a/pom.xml b/pom.xml index 37d8ad72dd57..b3698915396b 100644 --- a/pom.xml +++ b/pom.xml @@ -20,7 +20,7 @@ 2.0 --> com.alibaba dubbo-parent - 2.8.2 + 2.8.3 pom ${project.artifactId} The parent project of dubbo @@ -643,4 +643,16 @@ +8 + + + nexus-releases + Nexus Release Repository + http://10.255.209.180/nexus/content/repositories/releases/ + + + nexus-snapshots + Nexus Snapshot Repository + http://10.255.209.180/nexus/content/repositories/snapshots/ + + From 55ff6a3e3f8c586e072d6bec405d3a69864f3173 Mon Sep 17 00:00:00 2001 From: "Dylan.Ding" Date: Tue, 25 Nov 2014 21:02:59 +0800 Subject: [PATCH 143/200] =?UTF-8?q?=E5=AE=8C=E5=96=84jackson=E5=BA=8F?= =?UTF-8?q?=E5=88=97=E5=8C=96=EF=BC=8C=E6=94=B9=E8=BF=9B=E5=AF=B9=E7=BB=A7?= =?UTF-8?q?=E6=89=BFbean=E7=9A=84=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../support/json/JacksonObjectInput.java | 14 +++++- .../support/json/JacksonObjectOutput.java | 47 ++++++++++++++----- .../examples/jackson/JacksonConsumer.java | 30 ++++++++++-- .../jackson/api/AbstractInheritBean.java | 33 +++++++++++++ .../dubbo/examples/jackson/api/Inherit.java | 7 +++ .../examples/jackson/api/InheritBean.java | 35 ++++++++++++++ .../examples/jackson/api/InheritBean2.java | 25 ++++++++++ .../examples/jackson/api/JacksonService.java | 8 ++++ .../jackson/impl/JacksonServiceImpl.java | 36 ++++++++++++-- 9 files changed, 214 insertions(+), 21 deletions(-) create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/AbstractInheritBean.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/Inherit.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/InheritBean.java create mode 100644 dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/InheritBean2.java diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectInput.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectInput.java index a00b770a793d..f8a3c19ceec8 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectInput.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectInput.java @@ -17,6 +17,7 @@ import com.alibaba.dubbo.common.json.Jackson; import com.alibaba.dubbo.common.serialize.ObjectInput; +import com.alibaba.dubbo.common.utils.ReflectUtils; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -143,7 +144,7 @@ public Object readObject() throws IOException, ClassNotFoundException { // throw new IOException(e.getMessage()); // } try { - return readObject(Map.class); + return readObject(Object.class); } catch (ClassNotFoundException e) { throw new IOException(e.getMessage()); } @@ -152,7 +153,18 @@ public Object readObject() throws IOException, ClassNotFoundException { @SuppressWarnings("unchecked") public T readObject(Class cls) throws IOException, ClassNotFoundException { // Object value = readObject(); + //read data value String json = this.data.get(KEY_PREFIX + (++index)); + //read data type + String dataType = this.data.get(KEY_PREFIX + index + "t"); + if (dataType != null) { + Class clazz = ReflectUtils.desc2class(dataType); + if (cls.isAssignableFrom(clazz)) { + cls = clazz; + } else { + throw new IllegalArgumentException("Class \"" + clazz + "\" is not inherited from \"" + cls + "\""); + } + } logger.debug("index:{}, value:{}", index, json); return objectMapper.readValue(json, cls); } diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectOutput.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectOutput.java index 778296cf734c..b070c818c424 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectOutput.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JacksonObjectOutput.java @@ -17,21 +17,24 @@ import com.alibaba.dubbo.common.json.Jackson; import com.alibaba.dubbo.common.serialize.ObjectOutput; +import com.alibaba.dubbo.common.utils.ReflectUtils; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.*; +import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * jackson object output + * * @author dylan */ public class JacksonObjectOutput implements ObjectOutput { private final ObjectMapper objectMapper; - private final Map data; - private final static String KEY_PREFIX="$"; + private final Map data; + private final static String KEY_PREFIX = "$"; private int index = 0; private final PrintWriter writer; @@ -47,46 +50,66 @@ public JacksonObjectOutput(Writer writer) { } public void writeBool(boolean v) throws IOException { - writeObject(v); + writeObject0(v); } public void writeByte(byte v) throws IOException { - writeObject(v); + writeObject0(v); } public void writeShort(short v) throws IOException { - writeObject(v); + writeObject0(v); } public void writeInt(int v) throws IOException { - writeObject(v); + writeObject0(v); } public void writeLong(long v) throws IOException { - writeObject(v); + writeObject0(v); } public void writeFloat(float v) throws IOException { - writeObject(v); + writeObject0(v); } public void writeDouble(double v) throws IOException { - writeObject(v); + writeObject0(v); } public void writeUTF(String v) throws IOException { - writeObject(v); + writeObject0(v); } public void writeBytes(byte[] b) throws IOException { - writeObject(new String(b)); + writeObject0(new String(b)); } public void writeBytes(byte[] b, int off, int len) throws IOException { - writeObject(new String(b, off, len)); + writeObject0(new String(b, off, len)); } public void writeObject(Object obj) throws IOException { +// int i = ++index; + if (obj == null) { + writeObject0(obj); + return; + } + //write data value + writeObject0(obj); + //write data type + Class c = obj.getClass(); + String desc = ReflectUtils.getDesc(c); + data.put(KEY_PREFIX + (index) + "t", desc); +// if (obj instanceof Collection) { +// //闆嗗悎绫诲瀷 +// } else if (obj instanceof Map) { +// // +// } else { +// } + } + + private void writeObject0(Object obj) throws IOException { data.put(KEY_PREFIX + (++index), objectMapper.writeValueAsString(obj)); } diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonConsumer.java index 9679263d5686..e13847d690d7 100644 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonConsumer.java +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonConsumer.java @@ -15,11 +15,13 @@ */ package com.alibaba.dubbo.examples.jackson; -import com.alibaba.dubbo.examples.jackson.api.JacksonBean; -import com.alibaba.dubbo.examples.jackson.api.JacksonInnerBean; -import com.alibaba.dubbo.examples.jackson.api.JacksonService; +import com.alibaba.dubbo.examples.jackson.api.*; +import com.google.common.collect.Lists; import org.springframework.context.support.ClassPathXmlApplicationContext; +import java.util.Arrays; +import java.util.List; + /** * JacksonConsumer * @@ -32,11 +34,33 @@ public static void main(String[] args) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); context.start(); JacksonService jacksonService = (JacksonService) context.getBean("jacksonService"); + System.out.println("TEST: sayHello"); String hello = jacksonService.sayHello("world"); System.out.println(hello); + System.out.println("TEST: testJacksonBean"); JacksonBean jacksonBean = jacksonService.testJacksonBean(new JacksonBean(), new JacksonInnerBean()); System.out.println(jacksonBean); + + System.out.println("TEST: testInheritBean"); + Inherit inherit = jacksonService.testInheritBean(new InheritBean(), new JacksonBean()); + System.out.println(inherit); + + System.out.println("TEST: testArray"); + int[] intArray = jacksonService.testArray(new int[]{1,2}); + System.out.println(Arrays.toString(intArray)); + + System.out.println("TEST: testBeanArray"); + JacksonBean[] beanArray = jacksonService.testBeanArray(new JacksonBean[]{new JacksonBean(), new JacksonBean()}); + System.out.println(Arrays.toString(beanArray)); + + System.out.println("TEST: testException"); + try { + jacksonService.testException(); + } catch(Exception e){ + System.out.println("exception : " + e.getClass() + " : " + e.getMessage()); + } + System.in.read(); } diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/AbstractInheritBean.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/AbstractInheritBean.java new file mode 100644 index 000000000000..70ee7e17eb4e --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/AbstractInheritBean.java @@ -0,0 +1,33 @@ +package com.alibaba.dubbo.examples.jackson.api; + +/** + * Created by dylan on 14-11-22. + */ +public abstract class AbstractInheritBean implements Inherit{ + private String username = "Dylan"; + private int age = 10; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "AbstractInheritBean{" + + "username='" + username + '\'' + + ", age=" + age + + '}'; + } +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/Inherit.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/Inherit.java new file mode 100644 index 000000000000..e57b13bba989 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/Inherit.java @@ -0,0 +1,7 @@ +package com.alibaba.dubbo.examples.jackson.api; + +/** + * Created by dylan on 14-11-22. + */ +public interface Inherit { +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/InheritBean.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/InheritBean.java new file mode 100644 index 000000000000..6bccb8e909c4 --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/InheritBean.java @@ -0,0 +1,35 @@ +package com.alibaba.dubbo.examples.jackson.api; + +import java.util.Date; + +/** + * Created by dylan on 14-11-22. + */ +public class InheritBean extends AbstractInheritBean { + private String address = "ShangHai"; + private Date birthDate = new Date(); + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public Date getBirthDate() { + return birthDate; + } + + public void setBirthDate(Date birthDate) { + this.birthDate = birthDate; + } + + @Override + public String toString() { + return "InheritBean{" + + "address='" + address + '\'' + + ", birthDate=" + birthDate + + "} " + super.toString(); + } +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/InheritBean2.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/InheritBean2.java new file mode 100644 index 000000000000..4bd51b074c5f --- /dev/null +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/InheritBean2.java @@ -0,0 +1,25 @@ +package com.alibaba.dubbo.examples.jackson.api; + +import org.joda.time.DateTime; + +/** + * Created by dylan on 14-11-22. + */ +public class InheritBean2 extends AbstractInheritBean { + private String zipCode = "200000"; + + public String getZipCode() { + return zipCode; + } + + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } + + @Override + public String toString() { + return "InheritBean2{" + + "zipCode='" + zipCode + '\'' + + "} " + super.toString(); + } +} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonService.java index 1386c4759a71..836eb8e3b7ff 100644 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonService.java +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonService.java @@ -23,4 +23,12 @@ public interface JacksonService { String sayHello(String name); public JacksonBean testJacksonBean(JacksonBean jacksonBean, JacksonInnerBean jacksonInnerBean); + + public Inherit testInheritBean(Inherit inherit, JacksonBean jacksonBean); + + public int[] testArray(int[] array); + + public JacksonBean[] testBeanArray(JacksonBean[] jacksonBeans); + + public void testException(); } diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/impl/JacksonServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/impl/JacksonServiceImpl.java index ebfb0bfa0217..f13528bc8ba3 100644 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/impl/JacksonServiceImpl.java +++ b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/impl/JacksonServiceImpl.java @@ -1,9 +1,9 @@ /** * Project: dubbo-examples - * + * * File Created at 2012-2-17 * $Id$ - * + * * Copyright 1999-2100 Alibaba.com Corporation Limited. * All rights reserved. * @@ -15,9 +15,7 @@ */ package com.alibaba.dubbo.examples.jackson.impl; -import com.alibaba.dubbo.examples.jackson.api.JacksonBean; -import com.alibaba.dubbo.examples.jackson.api.JacksonInnerBean; -import com.alibaba.dubbo.examples.jackson.api.JacksonService; +import com.alibaba.dubbo.examples.jackson.api.*; /** * @author william.liangf @@ -35,4 +33,32 @@ public JacksonBean testJacksonBean(JacksonBean jacksonBean, JacksonInnerBean jac jacksonBean.getInnerBeanList().add(jacksonInnerBean); return jacksonBean; } + + @Override + public Inherit testInheritBean(Inherit inherit, JacksonBean jacksonBean) { + System.out.println(inherit); + System.out.println(jacksonBean); + return new InheritBean2(); + } + + @Override + public int[] testArray(int[] array) { + return new int[]{3, 4}; + } + + @Override + public JacksonBean[] testBeanArray(JacksonBean[] jacksonBeans) { + System.out.println("testBeanArray"); + for (JacksonBean in : jacksonBeans) { + System.out.println(in); + } + return new JacksonBean[]{ + new JacksonBean(), new JacksonBean() + }; + } + + @Override + public void testException() { + throw new RuntimeException("exception from provider"); + } } From 5013a5325d7a43d48f55761b157eff912a6ee73d Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 26 Nov 2014 09:33:04 +0800 Subject: [PATCH 144/200] update docs --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 744abdb84a3e..ac86dfe8843f 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p * **鏀寔鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡綋浠婃瘮杈冪煡鍚嶇殑[Kryo](https://github.com/EsotericSoftware/kryo)鍜孾FST](https://github.com/RuedigerMoeller/fast-serialization)楂樻ц兘搴忓垪鍖栧簱锛屼负Dubbo 榛樿鐨凴PC鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜咲ubbo RPC鐨勬ц兘锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 -* **鏀寔鍩轰簬Jackson鐨凧SON搴忓垪鍖**锛 +* **鏀寔鍩轰簬Jackson鐨凧SON搴忓垪鍖**锛歍ODO * **鏀寔鍩轰簬宓屽叆寮廡omcat鐨凥TTP remoting浣撶郴**锛氬熀浜庡祵鍏ュ紡tomcat瀹炵幇dubbo鐨凥TTP remoting浣撶郴锛堝嵆dubbo-remoting-http锛夛紝鐢ㄤ互閫愭鍙栦唬Dubbo涓棫鐗堟湰鐨勫祵鍏ュ紡Jetty锛屽彲浠ユ樉钁楃殑鎻愰珮REST绛夌殑杩滅▼璋冪敤鎬ц兘锛屽苟灏哠ervlet API鐨勬敮鎸佷粠2.5鍗囩骇鍒3.1銆傦紙娉細闄や簡REST锛宒ubbo涓殑WebServices銆丠essian銆丠TTP Invoker绛夊崗璁兘鍩轰簬杩欎釜HTTP remoting浣撶郴锛夈 @@ -25,7 +25,7 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p * **鍗囩骇ZooKeeper瀹㈡埛绔**锛氬皢dubbo涓殑zookeeper瀹㈡埛绔崌绾у埌鏈鏂扮殑鐗堟湰锛屼互淇鑰佺増鏈腑鍖呭惈鐨刡ug銆 -* **鏀寔鍩轰簬Java浠g爜鐨凷pring閰嶇疆**锛 +* **鏀寔鍩轰簬Java浠g爜鐨凷pring閰嶇疆**锛歍ODO * **璋冩暣Demo搴旂敤**锛氭殏鏃跺皢dubbo鐨刣emo搴旂敤璋冩暣骞舵敼鍐欎互涓昏婕旂ずREST鍔熻兘銆丏ubbo鍗忚鐨勬柊搴忓垪鍖栨柟寮忋佸熀浜嶫ava浠g爜鐨凷pring閰嶇疆绛夌瓑銆 @@ -39,6 +39,8 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p [鍦―ubbo涓娇鐢ㄩ珮鏁堢殑Java搴忓垪鍖栵紙Kryo鍜孎ST锛塢(http://dangdangdotcom.github.io/dubbox/serialization.html) +[浣跨敤JavaConfig鏂瑰紡閰嶇疆dubbox](http://dangdangdotcom.github.io/dubbox/java-config.html) + [Demo搴旂敤绠鍗曡繍琛屾寚鍗梋(http://dangdangdotcom.github.io/dubbox/demo.html) ## 鐗堟湰 From e9daead1a1195228fc544f57541b060b9131805a Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 26 Nov 2014 09:58:21 +0800 Subject: [PATCH 145/200] update docs --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ac86dfe8843f..3eb7fb3e7bc8 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p * **鏀寔REST椋庢牸杩滅▼璋冪敤锛圚TTP + JSON/XML)**锛氬熀浜庨潪甯告垚鐔熺殑JBoss [RestEasy](http://resteasy.jboss.org/)妗嗘灦锛屽湪dubbo涓疄鐜颁簡REST椋庢牸锛圚TTP + JSON/XML锛夌殑杩滅▼璋冪敤锛屼互鏄捐憲绠鍖栦紒涓氬唴閮ㄧ殑璺ㄨ瑷浜や簰锛屽悓鏃舵樉钁楃畝鍖栦紒涓氬澶栫殑Open API銆佹棤绾緼PI鐢氳嚦AJAX鏈嶅姟绔瓑绛夌殑寮鍙戙備簨瀹炰笂锛岃繖涓猂EST璋冪敤涔熶娇寰桪ubbo鍙互瀵瑰綋浠婄壒鍒祦琛岀殑鈥滃井鏈嶅姟鈥濇灦鏋勬彁渚涘熀纭鎬ф敮鎸併 鍙﹀锛孯EST璋冪敤涔熻揪鍒颁簡姣旇緝楂樼殑鎬ц兘锛屽湪鍩哄噯娴嬭瘯涓嬶紝HTTP + JSON涓嶥ubbo 2.x榛樿鐨凴PC鍗忚锛堝嵆TCP + Hessian2浜岃繘鍒跺簭鍒楀寲锛変箣闂村彧鏈1.5鍊嶅乏鍙崇殑宸窛锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 -* **鏀寔鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡綋浠婃瘮杈冪煡鍚嶇殑[Kryo](https://github.com/EsotericSoftware/kryo)鍜孾FST](https://github.com/RuedigerMoeller/fast-serialization)楂樻ц兘搴忓垪鍖栧簱锛屼负Dubbo 榛樿鐨凴PC鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜咲ubbo RPC鐨勬ц兘锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 +* **鏀寔鍩轰簬Kryo鍜孎ST鐨凧ava楂樻晥搴忓垪鍖栧疄鐜**锛氬熀浜庡綋浠婃瘮杈冪煡鍚嶇殑[Kryo](https://github.com/EsotericSoftware/kryo)鍜孾FST](https://github.com/RuedigerMoeller/fast-serialization)楂樻ц兘搴忓垪鍖栧簱锛屼负Dubbo榛樿鐨凴PC鍗忚娣诲姞鏂扮殑搴忓垪鍖栧疄鐜帮紝骞朵紭鍖栬皟鏁翠簡鍏跺簭鍒楀寲浣撶郴锛屾瘮杈冩樉钁楃殑鎻愰珮浜咲ubbo RPC鐨勬ц兘锛岃瑙佹枃妗d腑鐨勫熀鍑嗘祴璇曟姤鍛娿 -* **鏀寔鍩轰簬Jackson鐨凧SON搴忓垪鍖**锛歍ODO +* **鏀寔鍩轰簬Jackson鐨凧SON搴忓垪鍖**锛氬熀浜庝笟鐣屽簲鐢ㄦ渶骞挎硾鐨刐Jackson](http://jackson.codehaus.org/)搴忓垪鍖栧簱锛屼负Dubbo榛樿鐨凴PC鍗忚娣诲姞鏂扮殑JSON搴忓垪鍖栧疄鐜般 * **鏀寔鍩轰簬宓屽叆寮廡omcat鐨凥TTP remoting浣撶郴**锛氬熀浜庡祵鍏ュ紡tomcat瀹炵幇dubbo鐨凥TTP remoting浣撶郴锛堝嵆dubbo-remoting-http锛夛紝鐢ㄤ互閫愭鍙栦唬Dubbo涓棫鐗堟湰鐨勫祵鍏ュ紡Jetty锛屽彲浠ユ樉钁楃殑鎻愰珮REST绛夌殑杩滅▼璋冪敤鎬ц兘锛屽苟灏哠ervlet API鐨勬敮鎸佷粠2.5鍗囩骇鍒3.1銆傦紙娉細闄や簡REST锛宒ubbo涓殑WebServices銆丠essian銆丠TTP Invoker绛夊崗璁兘鍩轰簬杩欎釜HTTP remoting浣撶郴锛夈 @@ -25,7 +25,7 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p * **鍗囩骇ZooKeeper瀹㈡埛绔**锛氬皢dubbo涓殑zookeeper瀹㈡埛绔崌绾у埌鏈鏂扮殑鐗堟湰锛屼互淇鑰佺増鏈腑鍖呭惈鐨刡ug銆 -* **鏀寔鍩轰簬Java浠g爜鐨凷pring閰嶇疆**锛歍ODO +* **鏀寔瀹屽叏鍩轰簬Java浠g爜鐨凞ubbo閰嶇疆**锛氬熀浜嶴pring鐨凧ava Config锛屽疄鐜板畬鍏ㄦ棤XML鐨勭函Java浠g爜鏂瑰紡鏉ラ厤缃甦ubbo * **璋冩暣Demo搴旂敤**锛氭殏鏃跺皢dubbo鐨刣emo搴旂敤璋冩暣骞舵敼鍐欎互涓昏婕旂ずREST鍔熻兘銆丏ubbo鍗忚鐨勬柊搴忓垪鍖栨柟寮忋佸熀浜嶫ava浠g爜鐨凷pring閰嶇疆绛夌瓑銆 From fde7b4db031f4a5b8d566d8dcb5a0e17eeb7200e Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 26 Nov 2014 10:14:37 +0800 Subject: [PATCH 146/200] update docs --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3eb7fb3e7bc8..9c836e65ea75 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,8 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p [浣跨敤JavaConfig鏂瑰紡閰嶇疆dubbox](http://dangdangdotcom.github.io/dubbox/java-config.html) +[Dubbo Jackson搴忓垪鍖栦娇鐢ㄨ鏄嶿(http://dangdangdotcom.github.io/dubbox/jackson.html) + [Demo搴旂敤绠鍗曡繍琛屾寚鍗梋(http://dangdangdotcom.github.io/dubbox/demo.html) ## 鐗堟湰 From a6f773bc1b09ba442245b1293d5439cc21f03b60 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 26 Nov 2014 14:11:51 +0800 Subject: [PATCH 147/200] change rest logging --- .../rpc/protocol/rest/support/LoggingFilter.java | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java index 310d263f8ed0..92b1b4405313 100644 --- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java +++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/support/LoggingFilter.java @@ -47,10 +47,8 @@ * * @author lishen */ -@Priority(Priorities.HEADER_DECORATOR) -public class LoggingFilter implements - ContainerRequestFilter, ClientRequestFilter, ContainerResponseFilter, - ClientResponseFilter, WriterInterceptor, ReaderInterceptor { +@Priority(Integer.MIN_VALUE) +public class LoggingFilter implements ContainerRequestFilter, ClientRequestFilter, ContainerResponseFilter, ClientResponseFilter, WriterInterceptor, ReaderInterceptor { private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class); @@ -59,11 +57,11 @@ public void filter(ClientRequestContext context) throws IOException { } public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException { - logHttpHeaders(responseContext.getHeaders()); + logHttpHeaders(responseContext.getHeaders()); } public void filter(ContainerRequestContext context) throws IOException { - logHttpHeaders(context.getHeaders()); + logHttpHeaders(context.getHeaders()); } public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { @@ -110,7 +108,7 @@ private OutputStreamWrapper(OutputStream output) { @Override public void write(int i) throws IOException { - buffer.write(i); + buffer.write(i); output.write(i); } From bbe673e5ec2cd4d3a6476251ee4b9949ba79b8f0 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 26 Nov 2014 14:14:37 +0800 Subject: [PATCH 148/200] change rest logging --- pom.xml | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/pom.xml b/pom.xml index b3698915396b..41a954131769 100644 --- a/pom.xml +++ b/pom.xml @@ -643,16 +643,4 @@ +8 - - - nexus-releases - Nexus Release Repository - http://10.255.209.180/nexus/content/repositories/releases/ - - - nexus-snapshots - Nexus Snapshot Repository - http://10.255.209.180/nexus/content/repositories/snapshots/ - - From 3013a193e51b5d6837c9dee4cc45a003c612170d Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 26 Nov 2014 14:55:06 +0800 Subject: [PATCH 149/200] change demo config --- .../src/main/resources/META-INF/spring/dubbo-demo-consumer.xml | 2 +- .../src/main/resources/META-INF/spring/dubbo-demo-provider.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index 49ff527e1fe5..e7888cddc0e7 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -5,7 +5,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> - + diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index 0576b782ff24..fa1c601bf89b 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -20,7 +20,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> - + From 7635e794994c97908a7a5e29ecb955938a6ee4fd Mon Sep 17 00:00:00 2001 From: Li Shen Date: Wed, 26 Nov 2014 17:05:24 +0800 Subject: [PATCH 150/200] set basedir for tomcat http server --- .../dubbo/remoting/http/tomcat/TomcatHttpServer.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java index 01bb1b80bea4..686d562ae68a 100755 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java +++ b/dubbo-remoting/dubbo-remoting-http/src/main/java/com/alibaba/dubbo/remoting/http/tomcat/TomcatHttpServer.java @@ -47,7 +47,9 @@ public TomcatHttpServer(URL url, final HttpHandler handler) { this.url = url; DispatcherServlet.addHttpHandler(url.getPort(), handler); + String baseDir = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath(); tomcat = new Tomcat(); + tomcat.setBaseDir(baseDir); tomcat.setPort(url.getPort()); tomcat.getConnector().setProperty( "maxThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS))); @@ -63,9 +65,7 @@ public TomcatHttpServer(URL url, final HttpHandler handler) { tomcat.getConnector().setProperty("maxKeepAliveRequests", "-1"); tomcat.getConnector().setProtocol("org.apache.coyote.http11.Http11NioProtocol"); - - File baseDir = new File(System.getProperty("java.io.tmpdir")); - Context context = tomcat.addContext("/", baseDir.getAbsolutePath()); + Context context = tomcat.addContext("/", baseDir); Tomcat.addServlet(context, "dispatcher", new DispatcherServlet()); context.addServletMapping("/*", "dispatcher"); ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext()); From 7107e283c518d7856b9588a2e462e6255c52a553 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Tue, 2 Dec 2014 11:14:36 +0800 Subject: [PATCH 151/200] update docs --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c836e65ea75..9de3d30a5c11 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p 璇﹁锛歨ttps://github.com/dangdangdotcom/dubbox/releases -* **dubbox-2.8.0**锛氳鐗堟湰宸茬粡鍦ㄧ敓浜х幆澧冧腑浣跨敤锛屼富瑕佹敮鎸丷EST椋庢牸杩滅▼璋冪敤銆佹敮鎸並ryo鍜孎ST搴忓垪鍖栥佸崌绾т簡Spring鍜孼ookeeper瀹㈡埛绔佽皟鏁翠簡demo搴旂敤绛夌瓑 +* **dubbox-2.8.0**锛氫富瑕佹敮鎸丷EST椋庢牸杩滅▼璋冪敤銆佹敮鎸並ryo鍜孎ST搴忓垪鍖栥佸崌绾т簡Spring鍜孼ookeeper瀹㈡埛绔佽皟鏁翠簡demo搴旂敤绛夌瓑 * **dubbox-2.8.1**锛氫富瑕佹敮鎸佸熀浜庡祵鍏ュ紡tomcat鐨刪ttp-remoting锛屼紭鍖栦簡REST瀹㈡埛绔ц兘锛屽湪REST涓敮鎸侀檺鍒舵湇鍔$鎺ョ撼鐨勬渶澶TTP杩炴帴鏁扮瓑绛 * **dubbox-2.8.2**锛 * 鏀寔REST涓殑HTTP logging锛屽寘鎷琀TTP header鐨勫瓧娈靛拰HTTP body涓殑娑堟伅浣擄紝鏂逛究璋冭瘯銆佹棩蹇楃邯褰曠瓑绛 From be868d312640cfbe274978cf5dee19e895c910a9 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Thu, 4 Dec 2014 18:20:44 +0800 Subject: [PATCH 152/200] add configurable timeout support for zk clients --- .../src/main/java/com/alibaba/dubbo/common/Constants.java | 2 ++ .../remoting/zookeeper/curator/CuratorZookeeperClient.java | 4 +++- .../zookeeper/zkclient/ZkclientZookeeperClient.java | 6 +++++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java index cf80fae5da8f..2c712237bc62 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/Constants.java @@ -136,6 +136,8 @@ public class Constants { public static final int DEFAULT_CONNECT_TIMEOUT = 3000; + public static final int DEFAULT_REGISTRY_CONNECT_TIMEOUT = 5000; + public static final int DEFAULT_RETRIES = 2; // default buffer size is 8k. diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java index 51c078a1bd3a..6011e91c892d 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/curator/CuratorZookeeperClient.java @@ -2,6 +2,7 @@ import java.util.List; +import com.alibaba.dubbo.common.Constants; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.CuratorFrameworkFactory.Builder; @@ -29,7 +30,8 @@ public CuratorZookeeperClient(URL url) { Builder builder = CuratorFrameworkFactory.builder() .connectString(url.getBackupAddress()) .retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000)) - .connectionTimeoutMs(5000); + .connectionTimeoutMs(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_REGISTRY_CONNECT_TIMEOUT)) + .sessionTimeoutMs(url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT)); String authority = url.getAuthority(); if (authority != null && authority.length() > 0) { builder = builder.authorization("digest", authority.getBytes()); diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/zkclient/ZkclientZookeeperClient.java b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/zkclient/ZkclientZookeeperClient.java index 55c3c6c0694e..f1f43e6ba681 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/zkclient/ZkclientZookeeperClient.java +++ b/dubbo-remoting/dubbo-remoting-zookeeper/src/main/java/com/alibaba/dubbo/remoting/zookeeper/zkclient/ZkclientZookeeperClient.java @@ -2,6 +2,7 @@ import java.util.List; +import com.alibaba.dubbo.common.Constants; import org.I0Itec.zkclient.IZkChildListener; import org.I0Itec.zkclient.IZkStateListener; import org.I0Itec.zkclient.ZkClient; @@ -22,7 +23,10 @@ public class ZkclientZookeeperClient extends AbstractZookeeperClient Date: Fri, 5 Dec 2014 17:05:29 +0800 Subject: [PATCH 153/200] fix issue in kryo and fst --- .../rpc/protocol/dubbo/DecodeableRpcInvocation.java | 5 ++--- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 13 ++++++++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java index 41177317df80..38e6f7827f90 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java @@ -103,9 +103,8 @@ public Object decode(Channel channel, InputStream input) throws IOException { Class[] pts; // NOTICE modified by lishen - // TODO - if (CodecSupport.getSerialization(channel.getUrl(), serializationType) instanceof OptimizedSerialization) { - int argNum = in.readInt(); + int argNum = in.readInt(); + if (argNum >= 0) { if (argNum == 0) { pts = DubboCodec.EMPTY_CLASS_ARRAY; args = DubboCodec.EMPTY_OBJECT_ARRAY; diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java index 19ce3df6e0ae..b2e4b9603cad 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -183,9 +183,10 @@ protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) // NOTICE modified by lishen // TODO - if (getSerialization(channel) instanceof OptimizedSerialization) { + if (getSerialization(channel) instanceof OptimizedSerialization && !containComplexArguments(inv)) { out.writeInt(inv.getParameterTypes().length); } else { + out.writeInt(-1); out.writeUTF(ReflectUtils.getDesc(inv.getParameterTypes())); } Object[] args = inv.getArguments(); @@ -214,4 +215,14 @@ protected void encodeResponseData(Channel channel, ObjectOutput out, Object data out.writeObject(th); } } + + // workaround for the target method matching of kryo & fst + private boolean containComplexArguments(RpcInvocation invocation) { + for (int i = 0; i < invocation.getParameterTypes().length; i++) { + if (invocation.getParameterTypes()[i] != invocation.getArguments()[i]) { + return true; + } + } + return false; + } } \ No newline at end of file From ea645c76a72d29bd019c41e0dce1f1abfe6d886e Mon Sep 17 00:00:00 2001 From: Li Shen Date: Fri, 5 Dec 2014 17:51:55 +0800 Subject: [PATCH 154/200] disable dubbo monitor in demo --- .../src/main/resources/META-INF/spring/dubbo-demo-consumer.xml | 3 ++- .../src/main/resources/META-INF/spring/dubbo-demo-provider.xml | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml index e7888cddc0e7..6dd555c68f92 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml @@ -9,7 +9,8 @@ - + + diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml index fa1c601bf89b..265645ab00ba 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml @@ -24,7 +24,8 @@ - + + From 27320195e5765734f831e8ba2d6de80b0340cace Mon Sep 17 00:00:00 2001 From: Li Shen Date: Fri, 5 Dec 2014 18:10:16 +0800 Subject: [PATCH 155/200] fix issue in kryo and fst --- .../dubbo/rpc/protocol/dubbo/DubboCodec.java | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java index b2e4b9603cad..b70a84dce74c 100644 --- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java +++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java @@ -93,15 +93,15 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro } else { DecodeableRpcResult result; if (channel.getUrl().getParameter( - Constants.DECODE_IN_IO_THREAD_KEY, - Constants.DEFAULT_DECODE_IN_IO_THREAD)) { + Constants.DECODE_IN_IO_THREAD_KEY, + Constants.DEFAULT_DECODE_IN_IO_THREAD)) { result = new DecodeableRpcResult(channel, res, is, - (Invocation)getRequestData(id), proto); + (Invocation)getRequestData(id), proto); result.decode(); } else { result = new DecodeableRpcResult(channel, res, - new UnsafeByteArrayInputStream(readMessageData(is)), - (Invocation) getRequestData(id), proto); + new UnsafeByteArrayInputStream(readMessageData(is)), + (Invocation) getRequestData(id), proto); } data = result; } @@ -134,13 +134,13 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro } else { DecodeableRpcInvocation inv; if (channel.getUrl().getParameter( - Constants.DECODE_IN_IO_THREAD_KEY, - Constants.DEFAULT_DECODE_IN_IO_THREAD)) { + Constants.DECODE_IN_IO_THREAD_KEY, + Constants.DEFAULT_DECODE_IN_IO_THREAD)) { inv = new DecodeableRpcInvocation(channel, req, is, proto); inv.decode(); } else { inv = new DecodeableRpcInvocation(channel, req, - new UnsafeByteArrayInputStream(readMessageData(is)), proto); + new UnsafeByteArrayInputStream(readMessageData(is)), proto); } data = inv; } @@ -158,7 +158,7 @@ protected Object decodeBody(Channel channel, InputStream is, byte[] header) thro } private ObjectInput deserialize(Serialization serialization, URL url, InputStream is) - throws IOException { + throws IOException { return serialization.deserialize(url, is); } @@ -191,9 +191,9 @@ protected void encodeRequestData(Channel channel, ObjectOutput out, Object data) } Object[] args = inv.getArguments(); if (args != null) - for (int i = 0; i < args.length; i++){ - out.writeObject(encodeInvocationArgument(channel, inv, i)); - } + for (int i = 0; i < args.length; i++){ + out.writeObject(encodeInvocationArgument(channel, inv, i)); + } out.writeObject(inv.getAttachments()); } @@ -219,7 +219,7 @@ protected void encodeResponseData(Channel channel, ObjectOutput out, Object data // workaround for the target method matching of kryo & fst private boolean containComplexArguments(RpcInvocation invocation) { for (int i = 0; i < invocation.getParameterTypes().length; i++) { - if (invocation.getParameterTypes()[i] != invocation.getArguments()[i]) { + if (invocation.getParameterTypes()[i] != invocation.getArguments()[i].getClass()) { return true; } } From 0384a591f7d4237abc796d9171f5fc5bd412b3b6 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Mon, 8 Dec 2014 17:26:04 +0800 Subject: [PATCH 156/200] update docs --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9de3d30a5c11..36e3497df90a 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p **娉細dubbox鍜宒ubbo 2.x鏄吋瀹圭殑锛屾病鏈夋敼鍙榙ubbo鐨勪换浣曞凡鏈夌殑鍔熻兘鍜岄厤缃柟寮忥紙闄や簡鍗囩骇浜唖pring涔嬬被鐨勭増鏈級** -## Dubbox鏂囨。 +## 鏂囨。璧勬枡 [鍦―ubbo涓紑鍙慠EST椋庢牸鐨勮繙绋嬭皟鐢紙RESTful Remoting锛塢(http://dangdangdotcom.github.io/dubbox/rest.html) @@ -45,6 +45,10 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p [Demo搴旂敤绠鍗曡繍琛屾寚鍗梋(http://dangdangdotcom.github.io/dubbox/demo.html) +[Dubbox@InfoQ](http://www.infoq.com/cn/news/2014/10/dubbox-open-source) + +[Dubbox Wiki](https://github.com/dangdangdotcom/dubbox/wiki) 锛堢敱绀惧尯鑷効鑰呰嚜鐢辩紪杈戠殑锛 + ## 鐗堟湰 璇﹁锛歨ttps://github.com/dangdangdotcom/dubbox/releases From 02c9f3b8bd0757004b09d03da1bd5afe1c727242 Mon Sep 17 00:00:00 2001 From: Li Shen Date: Tue, 9 Dec 2014 11:35:53 +0800 Subject: [PATCH 157/200] re-enable source jar release --- dubbo/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 130815d23ed9..2346581c4e43 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -313,7 +313,7 @@ shade - false + true true From d59d7254711969e74841f50533db2c86a4491cdc Mon Sep 17 00:00:00 2001 From: Li Shen Date: Thu, 11 Dec 2014 14:53:03 +0800 Subject: [PATCH 158/200] add protocol config in @Reference --- .../java/com/alibaba/dubbo/config/annotation/Reference.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java index e1d8ffddd044..6d403362837c 100644 --- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java +++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java @@ -110,6 +110,8 @@ String monitor() default ""; + String protocol() default ""; + String[] registry() default {}; } From 6cebaa538de65191bbae98a173ea1de99b268256 Mon Sep 17 00:00:00 2001 From: kangfoo Date: Thu, 11 Dec 2014 23:23:33 +0800 Subject: [PATCH 159/200] add ignore --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 59f507d15802..af3d4f9128b7 100644 --- a/.gitignore +++ b/.gitignore @@ -23,6 +23,9 @@ target/ *.diff *.patch *.tmp +*.java~ +*.properties~ +*.xml~ # system ignore .DS_Store From 7971649c1f21ace138e65bc4fa1e68577b377fc8 Mon Sep 17 00:00:00 2001 From: kangfoo Date: Thu, 11 Dec 2014 23:33:48 +0800 Subject: [PATCH 160/200] define org.apache.tomcat.embed dependency to parent pom.xml --- dubbo-remoting/dubbo-remoting-http/pom.xml | 2 -- pom.xml | 16 ++++++++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index 7fb25c527de2..d5e1f4af8cd1 100644 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ b/dubbo-remoting/dubbo-remoting-http/pom.xml @@ -47,12 +47,10 @@ org.apache.tomcat.embed tomcat-embed-core - 8.0.11 org.apache.tomcat.embed tomcat-embed-logging-juli - 8.0.11 \ No newline at end of file diff --git a/pom.xml b/pom.xml index 41a954131769..3a2ec33b9f4e 100644 --- a/pom.xml +++ b/pom.xml @@ -113,6 +113,8 @@ 2.2 3.0.8 2.3.3 + 1.6 + 8.0.11 1.6.2 1.1 @@ -374,8 +376,18 @@ commons-pool commons-pool - 1.6 - + ${commons_pool_version} + + + org.apache.tomcat.embed + tomcat-embed-core + ${tomcat_embed_version} + + + org.apache.tomcat.embed + tomcat-embed-logging-juli + ${tomcat_embed_version} + From 5bbe775c32be05f83902526e671c3bc63c744ee2 Mon Sep 17 00:00:00 2001 From: kangfoo Date: Thu, 11 Dec 2014 23:52:24 +0800 Subject: [PATCH 161/200] create new module of maven-archetype from the dubbo-demo-lite project. --- pom.xml | 2 + .../dubbo-demo-lite-api/pom.xml | 45 ++++ .../demolite/SerializationOptimizerImpl.java | 37 ++++ .../demolite/extension/ClientTraceFilter.java | 36 ++++ .../extension/CustomExceptionMapper.java | 34 +++ .../extension/DynamicTraceBinding.java | 30 +++ .../extension/DynamicTraceInterceptor.java | 42 ++++ .../dubbo/demolite/extension/TraceFilter.java | 39 ++++ .../demolite/extension/TraceInterceptor.java | 42 ++++ .../com/alibaba/dubbo/demolite/user/User.java | 77 +++++++ .../dubbo/demolite/user/UserService.java | 25 +++ .../user/facade/RegistrationResult.java | 45 ++++ .../demolite/user/facade/UserRestService.java | 48 +++++ .../dubbo-demo-lite-consumer/pom.xml | 180 ++++++++++++++++ .../src/main/assembly/assembly.xml | 39 ++++ .../src/main/assembly/conf/dubbo.properties | 25 +++ .../dubbo/demolite/consumer/DemoAction.java | 50 +++++ .../spring/dubbo-demo-lite-action.xml | 29 +++ .../spring/dubbo-demo-lite-consumer.xml | 21 ++ .../dubbo/demolite/consumer/DemoConsumer.java | 24 +++ .../dubbo/demolite/consumer/RestClient.java | 89 ++++++++ .../src/test/resources/log4j.xml | 28 +++ .../dubbo-demo-lite-provider/pom.xml | 195 ++++++++++++++++++ .../dubbo/demolite/user/UserServiceImpl.java | 38 ++++ .../user/facade/UserRestServiceImpl.java | 63 ++++++ .../spring/dubbo-demo-lite-provider.xml | 75 +++++++ .../src/main/resources/log4j.xml | 28 +++ .../src/main/webapp/WEB-INF/web.xml | 30 +++ .../dubbo/demolite/provider/DemoProvider.java | 34 +++ support/dubbo-demo-lite/pom.xml | 46 +++++ support/maven-archetype/pom.xml | 114 ++++++++++ support/maven-archetype/readme.md | 20 ++ .../META-INF/maven/archetype-metadata.xml | 80 +++++++ .../__rootArtifactId__-api/pom.xml | 44 ++++ .../main/java/SerializationOptimizerImpl.java | 40 ++++ .../java/extension/ClientTraceFilter.java | 39 ++++ .../java/extension/CustomExceptionMapper.java | 37 ++++ .../java/extension/DynamicTraceBinding.java | 33 +++ .../extension/DynamicTraceInterceptor.java | 45 ++++ .../src/main/java/extension/TraceFilter.java | 42 ++++ .../main/java/extension/TraceInterceptor.java | 45 ++++ .../src/main/java/user/User.java | 80 +++++++ .../src/main/java/user/UserService.java | 28 +++ .../java/user/facade/RegistrationResult.java | 48 +++++ .../java/user/facade/UserRestService.java | 51 +++++ .../__rootArtifactId__-consumer/pom.xml | 179 ++++++++++++++++ .../src/main/assembly/assembly.xml | 42 ++++ .../src/main/assembly/conf/dubbo.properties | 28 +++ .../src/main/java/consumer/DemoAction.java | 52 +++++ .../spring/dubbo-demo-lite-action.xml | 30 +++ .../spring/dubbo-demo-lite-consumer.xml | 24 +++ .../src/test/java/consumer/DemoConsumer.java | 27 +++ .../src/test/java/consumer/RestClient.java | 92 +++++++++ .../src/test/resources/log4j.xml | 31 +++ .../__rootArtifactId__-provider/pom.xml | 193 +++++++++++++++++ .../src/main/java/user/UserServiceImpl.java | 41 ++++ .../java/user/facade/UserRestServiceImpl.java | 66 ++++++ .../spring/dubbo-demo-lite-provider.xml | 80 +++++++ .../src/main/resources/log4j.xml | 31 +++ .../src/main/webapp/WEB-INF/web.xml | 33 +++ .../src/test/java/provider/DemoProvider.java | 37 ++++ .../resources/archetype-resources/pom.xml | 42 ++++ .../projects/basic/archetype.properties | 5 + 63 files changed, 3275 insertions(+) create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/SerializationOptimizerImpl.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/ClientTraceFilter.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/CustomExceptionMapper.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceBinding.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceInterceptor.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceFilter.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceInterceptor.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/User.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/RegistrationResult.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestService.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/assembly.xml create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/conf/dubbo.properties create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/java/com/alibaba/dubbo/demolite/consumer/DemoAction.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/DemoConsumer.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/RestClient.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/resources/log4j.xml create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/UserServiceImpl.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestServiceImpl.java create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/log4j.xml create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/webapp/WEB-INF/web.xml create mode 100644 support/dubbo-demo-lite/dubbo-demo-lite-provider/src/test/java/com/alibaba/dubbo/demolite/provider/DemoProvider.java create mode 100644 support/dubbo-demo-lite/pom.xml create mode 100644 support/maven-archetype/pom.xml create mode 100644 support/maven-archetype/readme.md create mode 100644 support/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/SerializationOptimizerImpl.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/ClientTraceFilter.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/CustomExceptionMapper.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceBinding.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceInterceptor.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceFilter.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceInterceptor.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/User.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/UserService.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/RegistrationResult.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/UserRestService.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/assembly.xml create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/conf/dubbo.properties create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/java/consumer/DemoAction.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/DemoConsumer.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/RestClient.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/resources/log4j.xml create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/UserServiceImpl.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/facade/UserRestServiceImpl.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/log4j.xml create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/webapp/WEB-INF/web.xml create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/test/java/provider/DemoProvider.java create mode 100644 support/maven-archetype/src/main/resources/archetype-resources/pom.xml create mode 100644 support/maven-archetype/src/test/resources/projects/basic/archetype.properties diff --git a/pom.xml b/pom.xml index 3a2ec33b9f4e..d66e896dc1af 100644 --- a/pom.xml +++ b/pom.xml @@ -53,6 +53,8 @@ dubbo-admin dubbo-demo hessian-lite + support/dubbo-demo-lite + support/maven-archetype diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml b/support/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml new file mode 100644 index 000000000000..d68347cbdeb1 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml @@ -0,0 +1,45 @@ + + + 4.0.0 + + com.alibaba + dubbo-demo-lite + 2.8.3 + + dubbo-demo-lite-api + jar + ${project.artifactId} + The demo module of dubbo project + + true + + + + com.alibaba + dubbo + + + javax.servlet + javax.servlet-api + + + javax.validation + validation-api + + + diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/SerializationOptimizerImpl.java b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/SerializationOptimizerImpl.java new file mode 100644 index 000000000000..f82006a14c60 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/SerializationOptimizerImpl.java @@ -0,0 +1,37 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite; + +import com.alibaba.dubbo.common.serialize.support.SerializationOptimizer; +import com.alibaba.dubbo.demolite.user.User; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +/** + * This class must be accessible from both the provider and consumer + * + * @author lishen + */ +public class SerializationOptimizerImpl implements SerializationOptimizer { + + public Collection getSerializableClasses() { + List classes = new LinkedList(); + classes.add(User.class); + return classes; + } +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/ClientTraceFilter.java b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/ClientTraceFilter.java new file mode 100644 index 000000000000..108b09fbc2b7 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/ClientTraceFilter.java @@ -0,0 +1,36 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.extension; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import java.io.IOException; + +/** + * @author lishen + */ +public class ClientTraceFilter implements ClientRequestFilter, ClientResponseFilter { + + public void filter(ClientRequestContext requestContext) throws IOException { + System.out.println("Client request filter invoked"); + } + + public void filter(ClientRequestContext clientRequestContext, ClientResponseContext clientResponseContext) throws IOException { + System.out.println("Client response filter invoked"); + } +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/CustomExceptionMapper.java b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/CustomExceptionMapper.java new file mode 100644 index 000000000000..d73838a18ece --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/CustomExceptionMapper.java @@ -0,0 +1,34 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.extension; + +import com.alibaba.dubbo.rpc.RpcContext; + +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + +/** + * @author lishen + */ +public class CustomExceptionMapper implements ExceptionMapper { + + public Response toResponse(NotFoundException e) { + System.out.println("Exception mapper successfully got an exception: " + e + ":" + e.getMessage()); + System.out.println("Client IP is " + RpcContext.getContext().getRemoteAddressString()); + return Response.status(Response.Status.NOT_FOUND).entity("Oops! the requested resource is not found!").type("text/plain").build(); + } +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceBinding.java b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceBinding.java new file mode 100644 index 000000000000..eaf81d4d5570 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceBinding.java @@ -0,0 +1,30 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.extension; + +import javax.ws.rs.container.DynamicFeature; +import javax.ws.rs.container.ResourceInfo; +import javax.ws.rs.core.FeatureContext; + +/** + * @author lishen + */ +public class DynamicTraceBinding implements DynamicFeature { + + public void configure(ResourceInfo resourceInfo, FeatureContext context) { + context.register(DynamicTraceInterceptor.class); + } +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceInterceptor.java b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceInterceptor.java new file mode 100644 index 000000000000..8f6a249e1fad --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceInterceptor.java @@ -0,0 +1,42 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.extension; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.ext.ReaderInterceptor; +import javax.ws.rs.ext.ReaderInterceptorContext; +import javax.ws.rs.ext.WriterInterceptor; +import javax.ws.rs.ext.WriterInterceptorContext; +import java.io.IOException; + +/** + * @author lishen + */ +@Priority(Priorities.USER) +public class DynamicTraceInterceptor implements ReaderInterceptor, WriterInterceptor { + + public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Dynamic reader interceptor invoked"); + return readerInterceptorContext.proceed(); + } + + public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Dynamic writer interceptor invoked"); + writerInterceptorContext.proceed(); + } +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceFilter.java b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceFilter.java new file mode 100644 index 000000000000..457a28fde86b --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceFilter.java @@ -0,0 +1,39 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.extension; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import java.io.IOException; + +/** + * @author lishen + */ +@Priority(Priorities.USER) +public class TraceFilter implements ContainerRequestFilter, ContainerResponseFilter { + + public void filter(ContainerRequestContext requestContext) throws IOException { + System.out.println("Request filter invoked"); + } + + public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException { + System.out.println("Response filter invoked"); + } +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceInterceptor.java b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceInterceptor.java new file mode 100644 index 000000000000..4354f90850f5 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceInterceptor.java @@ -0,0 +1,42 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.extension; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.ext.ReaderInterceptor; +import javax.ws.rs.ext.ReaderInterceptorContext; +import javax.ws.rs.ext.WriterInterceptor; +import javax.ws.rs.ext.WriterInterceptorContext; +import java.io.IOException; + +/** + * @author lishen + */ +@Priority(Priorities.USER) +public class TraceInterceptor implements ReaderInterceptor, WriterInterceptor { + + public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Reader interceptor invoked"); + return readerInterceptorContext.proceed(); + } + + public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Writer interceptor invoked"); + writerInterceptorContext.proceed(); + } +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/User.java b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/User.java new file mode 100644 index 000000000000..005ff3794a52 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/User.java @@ -0,0 +1,77 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.user; + +import org.codehaus.jackson.annotate.JsonProperty; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * @author lishen + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +public class User implements Serializable { + + @NotNull + @Min(1L) + private Long id; + + @JsonProperty("username") + @XmlElement(name = "username") + @NotNull + @Size(min = 6, max = 50) + private String name; + + public User() { + } + + public User(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "User (" + + "id=" + id + + ", name='" + name + '\'' + + ')'; + } +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java new file mode 100644 index 000000000000..43b503067564 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java @@ -0,0 +1,25 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.user; + +/** + * @author lishen + */ +public interface UserService { + User getUser(Long id); + + Long registerUser(User user); +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/RegistrationResult.java b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/RegistrationResult.java new file mode 100644 index 000000000000..c58f7d73d19b --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/RegistrationResult.java @@ -0,0 +1,45 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.user.facade; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * DTO to customize the returned message + * + * @author lishen + */ +@XmlRootElement +public class RegistrationResult implements Serializable { + + private Long id; + + public RegistrationResult() { + } + + public RegistrationResult(Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestService.java b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestService.java new file mode 100644 index 000000000000..b753eea68bdb --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestService.java @@ -0,0 +1,48 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.user.facade; + +import com.alibaba.dubbo.demolite.user.User; +import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType; + +import javax.validation.constraints.Min; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + +/** + * This interface acts as some kind of service broker for the original UserService + + * Here we want to simulate the twitter/weibo rest api, e.g. + * + * http://localhost:8888/user/1.json + * http://localhost:8888/user/1.xml + * + * @author lishen + */ + +@Path("users") +@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) +public interface UserRestService { + + @GET + @Path("{id : \\d+}") + public User getUser(@Min(value=1L, message="User ID must be greater than 1") @PathParam("id") Long id/*, @Context HttpServletRequest request*/) ; + + @POST + @Path("register") + RegistrationResult registerUser(User user); +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml new file mode 100644 index 000000000000..59080ccd29d1 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml @@ -0,0 +1,180 @@ + + + 4.0.0 + + com.alibaba + dubbo-demo-lite + 2.8.3 + + dubbo-demo-lite-consumer + jar + ${project.artifactId} + The demo consumer module of dubbo project + + false + + + + com.alibaba + dubbo-demo-lite-api + ${project.parent.version} + + + com.alibaba + dubbo + + + org.javassist + javassist + + + org.jboss.netty + netty + + + org.apache.mina + mina-core + + + org.glassfish.grizzly + grizzly-core + + + org.apache.httpcomponents + httpclient + + + com.alibaba + fastjson + + + com.thoughtworks.xstream + xstream + + + org.apache.bsf + bsf-api + + + org.apache.zookeeper + zookeeper + + + com.github.sgroschupf + zkclient + + + org.apache.curator + curator-framework + + + com.googlecode.xmemcached + xmemcached + + + org.apache.cxf + cxf-rt-frontend-simple + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.thrift + libthrift + + + com.caucho + hessian + + + javax.servlet + javax.servlet-api + + + org.mortbay.jetty + jetty + + + log4j + log4j + + + org.slf4j + slf4j-api + + + redis.clients + jedis + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + javax.cache + cache-api + + + + + + maven-dependency-plugin + + + unpack + package + + unpack + + + + + com.alibaba + dubbo + ${project.parent.version} + ${project.build.directory}/dubbo + META-INF/assembly/** + + + + + + + + maven-assembly-plugin + + src/main/assembly/assembly.xml + + + + make-assembly + package + + single + + + + + + + diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/assembly.xml b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/assembly.xml new file mode 100644 index 000000000000..1bdbe518dcd3 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/assembly.xml @@ -0,0 +1,39 @@ + + + assembly + + tar.gz + + true + + + ${project.build.directory}/dubbo/META-INF/assembly/bin + bin + 0755 + + + src/main/assembly/conf + conf + 0644 + + + + + lib + + + diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/conf/dubbo.properties b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/conf/dubbo.properties new file mode 100644 index 000000000000..8d1835e8f0b5 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/conf/dubbo.properties @@ -0,0 +1,25 @@ +## +# Copyright 1999-2011 Alibaba Group. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +## +dubbo.container=log4j,spring +dubbo.application.name=demo-lite-consumer +dubbo.application.owner= +#dubbo.registry.address=multicast://224.5.6.7:1234 +dubbo.registry.address=zookeeper://127.0.0.1:2181 +#dubbo.registry.address=redis://127.0.0.1:6379 +#dubbo.registry.address=dubbo://127.0.0.1:9090 +dubbo.monitor.protocol=registry +dubbo.log4j.file=logs/dubbo-demo-consumer.log +dubbo.log4j.level=WARN diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/java/com/alibaba/dubbo/demolite/consumer/DemoAction.java b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/java/com/alibaba/dubbo/demolite/consumer/DemoAction.java new file mode 100644 index 000000000000..32699c7b51a2 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/java/com/alibaba/dubbo/demolite/consumer/DemoAction.java @@ -0,0 +1,50 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.consumer; + +import com.alibaba.dubbo.demolite.user.User; +import com.alibaba.dubbo.demolite.user.UserService; +import com.alibaba.dubbo.demolite.user.facade.UserRestService; + +/** + * + * User: kangfoo + * Date: 14-12-9 + * Time: 涓嬪崍4:12 + */ +public class DemoAction { + + private UserRestService userRestService; + private UserService userService; + + public void setUserService(UserService userService) { + this.userService = userService; + } + + public void setUserRestService(UserRestService userRestService) { + this.userRestService = userRestService; + } + + public void start() throws Exception { + + + User user = new User(1L, "larrypage"); + System.out.println("SUCESS: registered user with id " + userRestService.registerUser(user).getId()); + + System.out.println("SUCESS: got user " + userService.getUser(1L)); + } + +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml new file mode 100644 index 000000000000..c0aa4f9b6e89 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml new file mode 100644 index 000000000000..88f5164cbde2 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/DemoConsumer.java b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/DemoConsumer.java new file mode 100644 index 000000000000..e87a3f3acc6e --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/DemoConsumer.java @@ -0,0 +1,24 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.consumer; + +public class DemoConsumer { + + public static void main(String[] args) { + com.alibaba.dubbo.container.Main.main(args); + } + +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/RestClient.java b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/RestClient.java new file mode 100644 index 000000000000..5e4942160b77 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/RestClient.java @@ -0,0 +1,89 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.consumer; + +import com.alibaba.dubbo.demolite.user.User; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +/** + * @author lishen + */ +public class RestClient { + + public static void main(String[] args) { + final String port = "8888"; +// final String port = "8080"; + +// for (int i = 0; i < 500; i++) { +// final int index = i + 1; +// new Thread(new Runnable() { +// public void run() { +// System.out.println("Starting thread " + index + "..."); +// for (int j = 0; j < 500; j++) { + registerUser("http://localhost:" + port + "/services/users/register.json", MediaType.APPLICATION_JSON_TYPE); + + registerUser("http://localhost:" + port + "/services/users/register.xml", MediaType.TEXT_XML_TYPE); + + getUser("http://localhost:" + port + "/services/users/1.json"); + + getUser("http://localhost:" + port + "/services/users/2.xml"); + +// } +// } +// }).start(); +// } + } + + private static void registerUser(String url, MediaType mediaType) { + System.out.println("Registering user via " + url); + User user = new User(1L, "larrypage"); + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(url); + Response response = target.request().post(Entity.entity(user, mediaType)); + + try { + if (response.getStatus() != 200) { + throw new RuntimeException("Failed with HTTP error code : " + response.getStatus()); + } + System.out.println("Successfully got result: " + response.readEntity(String.class)); + } finally { + response.close(); + client.close(); + } + } + + private static void getUser(String url) { + System.out.println("Getting user via " + url); + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(url); + Response response = target.request().get(); + try { + if (response.getStatus() != 200) { + throw new RuntimeException("Failed with HTTP error code : " + response.getStatus()); + } + System.out.println("Successfully got result: " + response.readEntity(String.class)); + } finally { + response.close(); + client.close(); + } + } +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/resources/log4j.xml b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/resources/log4j.xml new file mode 100644 index 000000000000..5375cc32f395 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/resources/log4j.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml b/support/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml new file mode 100644 index 000000000000..185c45195013 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml @@ -0,0 +1,195 @@ + + + 4.0.0 + + com.alibaba + dubbo-demo-lite + 2.8.3 + + dubbo-demo-lite-provider + war + ${project.artifactId} + The demo provider module of dubbo project + + false + + + + com.alibaba + dubbo-demo-lite-api + ${project.parent.version} + + + com.alibaba + dubbo + ${project.parent.version} + + + org.javassist + javassist + + + org.jboss.netty + netty + + + org.apache.mina + mina-core + + + org.glassfish.grizzly + grizzly-core + + + org.apache.httpcomponents + httpclient + + + com.alibaba + fastjson + + + com.thoughtworks.xstream + xstream + + + org.apache.bsf + bsf-api + + + org.apache.zookeeper + zookeeper + + + com.github.sgroschupf + zkclient + + + org.apache.curator + curator-framework + + + com.googlecode.xmemcached + xmemcached + + + org.apache.cxf + cxf-rt-frontend-simple + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.thrift + libthrift + + + com.caucho + hessian + + + javax.servlet + javax.servlet-api + + + org.mortbay.jetty + jetty + + + org.mortbay.jetty + servlet-api + + + + + log4j + log4j + + + org.slf4j + slf4j-api + + + redis.clients + jedis + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + javax.cache + cache-api + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/UserServiceImpl.java b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/UserServiceImpl.java new file mode 100644 index 000000000000..837a0bc8bec5 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/UserServiceImpl.java @@ -0,0 +1,38 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.user; + +import java.util.concurrent.atomic.AtomicLong; + +/** + * User: kangfoo + * Date: 14-12-9 + * Time: 涓嬪崍3:45 + */ +public class UserServiceImpl implements UserService { + + private final AtomicLong idGen = new AtomicLong(); + + public User getUser(Long id) { + return new User(id, "username" + id); + } + + + public Long registerUser(User user) { +// System.out.println("Username is " + user.getName()); + return idGen.incrementAndGet(); + } +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestServiceImpl.java b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestServiceImpl.java new file mode 100644 index 000000000000..ccbaa904ce14 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestServiceImpl.java @@ -0,0 +1,63 @@ +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.user.facade; + +import com.alibaba.dubbo.demolite.user.User; +import com.alibaba.dubbo.demolite.user.UserService; +import com.alibaba.dubbo.rpc.RpcContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.validation.constraints.Min; +import javax.ws.rs.PathParam; + +/** + * User: kangfoo + * Date: 14-12-9 + * Time: 涓嬪崍3:45 + */ +public class UserRestServiceImpl implements UserRestService { + + private static final Logger logger = LoggerFactory.getLogger(UserRestServiceImpl.class); + + private UserService userService; + + public void setUserService(UserService userService) { + this.userService = userService; + } + + @Override + public User getUser(@Min(value = 1L, message = "User ID must be greater than 1") @PathParam("id") Long id) { + // test context injection +// System.out.println("Client address from @Context injection: " + (request != null ? request.getRemoteAddr() : "")); +// System.out.println("Client address from RpcContext: " + RpcContext.getContext().getRemoteAddressString()); + if (RpcContext.getContext().getRequest(HttpServletRequest.class) != null) { + System.out.println("Client IP address from RpcContext: " + RpcContext.getContext().getRequest(HttpServletRequest.class).getRemoteAddr()); + } + if (RpcContext.getContext().getResponse(HttpServletResponse.class) != null) { + System.out.println("Response object from RpcContext: " + RpcContext.getContext().getResponse(HttpServletResponse.class)); + } + return userService.getUser(id); + } + + @Override + public RegistrationResult registerUser(User user) { + return new RegistrationResult(userService.registerUser(user)); + } + +} diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml new file mode 100644 index 000000000000..3d4f93e308c9 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/log4j.xml b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/log4j.xml new file mode 100644 index 000000000000..33bf5d8a725d --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/log4j.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/webapp/WEB-INF/web.xml b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000000..242c3741c52f --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,30 @@ + + + + + + contextConfigLocation + /WEB-INF/classes/META-INF/spring/dubbo-demo-lite-provider.xml + + + + + com.alibaba.dubbo.remoting.http.servlet.BootstrapListener + + + + org.springframework.web.context.ContextLoaderListener + + + + dispatcher + com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet + 1 + + + + dispatcher + /services/* + + diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/test/java/com/alibaba/dubbo/demolite/provider/DemoProvider.java b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/test/java/com/alibaba/dubbo/demolite/provider/DemoProvider.java new file mode 100644 index 000000000000..eaa78d67af21 --- /dev/null +++ b/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/test/java/com/alibaba/dubbo/demolite/provider/DemoProvider.java @@ -0,0 +1,34 @@ +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.dubbo.demolite.provider; + +public class DemoProvider { + + public static void main(String[] args) { +// new Thread(new Runnable() { +// public void run() { +// try { +// Thread.sleep(20000); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// ProtocolConfig.destroyAll(); +// } +// }).start(); + com.alibaba.dubbo.container.Main.main(args); + } + +} diff --git a/support/dubbo-demo-lite/pom.xml b/support/dubbo-demo-lite/pom.xml new file mode 100644 index 000000000000..4dd1940fbb45 --- /dev/null +++ b/support/dubbo-demo-lite/pom.xml @@ -0,0 +1,46 @@ + + + 4.0.0 + + com.alibaba + dubbo-parent + 2.8.3 + + dubbo-demo-lite + pom + ${project.artifactId} + The demo lite module of dubbo project + + true + + + dubbo-demo-lite-api + dubbo-demo-lite-provider + dubbo-demo-lite-consumer + + + + + + com.alibaba + dubbo + 2.8.3 + + + + diff --git a/support/maven-archetype/pom.xml b/support/maven-archetype/pom.xml new file mode 100644 index 000000000000..34a79cffd2c9 --- /dev/null +++ b/support/maven-archetype/pom.xml @@ -0,0 +1,114 @@ + + + 4.0.0 + + com.alibaba + dubbo-demo-lite-archetype + 2.8.3 + maven-archetype + + dubbo-demo-lite-archetype + + + + + org.apache.maven.archetype + archetype-packaging + 2.2 + + + + + + + maven-archetype-plugin + 2.2 + + + + + + The demo lite module of dubbo project + + http://code.alibabatech.com/wiki/display/dubbo/dubbo-demo-lite + + + + shawn.qianx + QianXiao(Shawn) + shawn.qianx (AT) alibaba-inc.com + + Developer + + +8 + + + william.liangf + LiangFei(William) + william.liangf (AT) alibaba-inc.com + + Developer + + +8 + + + ding.lid + LiDing(Jerry) + ding.lid (AT) alibaba-inc.com + + Developer + + +8 + + + chao.liuc + LiuChao(Charles) + chao.liuc (AT) alibaba-inc.com + + Developer + + +8 + + + haoming.liuhm + LiuHaoMin(Ludvik) + haoming.liuhm (AT) alibaba-inc.com + + Developer + + +8 + + + tony.chenl + ChenLei(Tony) + tony.chenl (AT) alibaba-inc.com + + Developer + + +8 + + + gang.lvg + LvGang(Kimi) + gang.lvg (AT) alibaba-inc.com + + Developer + + +8 + + + + + + Apache 2 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + A business-friendly OSS license + + + + + scm:svn:http://code.alibabatech.com/svn/dubbo/trunk/dubbo-demo-lite + http://code.alibabatech.com/svn/dubbo/trunk/dubbo-demo-lite + + diff --git a/support/maven-archetype/readme.md b/support/maven-archetype/readme.md new file mode 100644 index 000000000000..34b639ab96e4 --- /dev/null +++ b/support/maven-archetype/readme.md @@ -0,0 +1,20 @@ +鐩殑锛 +蹇熺殑浣跨敤 maven archetype 杩涜 dubbox rest 椤圭洰宸ョ▼鎼缓銆 +鏈榛樿浠 dubbo-demo-lite 鏋勫缓涓涓 rest 鐗堟湰鐨 dubbox 妗嗘灦缁撴瀯銆 + +鍛戒护鍙傝冿細 + +1. 浠庝竴涓凡鏈夌殑椤圭洰涓瀯寤轰竴涓 maven archetype锛 +$ mvn archetype:create-from-project -Darchetype.filteredExtentions=java,xml,jsp,properties,sql + +2. 鐒跺悗鍐嶄慨鏀规ā鏉夸腑鐨勬枃浠讹紝骞舵墽琛 +$ mvn clean install + +3. 寮濮嬩粠涓涓凡鏈夌殑 maven archetype 涓鍒堕」鐩 +$ mkdir tmp +$ cd tmp +$ mvn archetype:generate -DarchetypeCatalog=local + +鏇村璧勬枡璇峰弬鑰 +http://maven.apache.org/archetype/maven-archetype-plugin/examples/create-multi-module-project.html + diff --git a/support/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml b/support/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml new file mode 100644 index 000000000000..b610f8b1764a --- /dev/null +++ b/support/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml @@ -0,0 +1,80 @@ + + + + + + + src/main/java + + **/*.java + + + + + + + + src/main/java + + **/*.java + + + + src/main/webapp + + **/*.xml + + + + src/main/resources + + **/*.xml + + + + src/test/java + + **/*.java + + + + + + + + src/main/java + + **/*.java + + + + src/main/assembly + + **/*.xml + **/*.properties + + + + src/main/resources + + **/*.xml + + + + src/test/java + + **/*.java + + + + src/test/resources + + **/*.xml + + + + + + diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml new file mode 100644 index 000000000000..0e6f85553e49 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + ${groupId} + ${rootArtifactId} + ${version} + + ${artifactId} + jar + ${project.artifactId} + The demo module of dubbo project + + true + + + + com.alibaba + dubbo + + + javax.servlet + javax.servlet-api + + + javax.validation + validation-api + + + diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/SerializationOptimizerImpl.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/SerializationOptimizerImpl.java new file mode 100644 index 000000000000..51c2ea26f9ab --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/SerializationOptimizerImpl.java @@ -0,0 +1,40 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}; + +import com.alibaba.dubbo.common.serialize.support.SerializationOptimizer; +import ${package}.user.User; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +/** + * This class must be accessible from both the provider and consumer + * + * @author lishen + */ +public class SerializationOptimizerImpl implements SerializationOptimizer { + + public Collection getSerializableClasses() { + List classes = new LinkedList(); + classes.add(User.class); + return classes; + } +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/ClientTraceFilter.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/ClientTraceFilter.java new file mode 100644 index 000000000000..b626753c5d07 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/ClientTraceFilter.java @@ -0,0 +1,39 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.extension; + +import javax.ws.rs.client.ClientRequestContext; +import javax.ws.rs.client.ClientRequestFilter; +import javax.ws.rs.client.ClientResponseContext; +import javax.ws.rs.client.ClientResponseFilter; +import java.io.IOException; + +/** + * @author lishen + */ +public class ClientTraceFilter implements ClientRequestFilter, ClientResponseFilter { + + public void filter(ClientRequestContext requestContext) throws IOException { + System.out.println("Client request filter invoked"); + } + + public void filter(ClientRequestContext clientRequestContext, ClientResponseContext clientResponseContext) throws IOException { + System.out.println("Client response filter invoked"); + } +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/CustomExceptionMapper.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/CustomExceptionMapper.java new file mode 100644 index 000000000000..a2ed960e38b4 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/CustomExceptionMapper.java @@ -0,0 +1,37 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.extension; + +import com.alibaba.dubbo.rpc.RpcContext; + +import javax.ws.rs.NotFoundException; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + +/** + * @author lishen + */ +public class CustomExceptionMapper implements ExceptionMapper { + + public Response toResponse(NotFoundException e) { + System.out.println("Exception mapper successfully got an exception: " + e + ":" + e.getMessage()); + System.out.println("Client IP is " + RpcContext.getContext().getRemoteAddressString()); + return Response.status(Response.Status.NOT_FOUND).entity("Oops! the requested resource is not found!").type("text/plain").build(); + } +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceBinding.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceBinding.java new file mode 100644 index 000000000000..ae97a785da74 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceBinding.java @@ -0,0 +1,33 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.extension; + +import javax.ws.rs.container.DynamicFeature; +import javax.ws.rs.container.ResourceInfo; +import javax.ws.rs.core.FeatureContext; + +/** + * @author lishen + */ +public class DynamicTraceBinding implements DynamicFeature { + + public void configure(ResourceInfo resourceInfo, FeatureContext context) { + context.register(DynamicTraceInterceptor.class); + } +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceInterceptor.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceInterceptor.java new file mode 100644 index 000000000000..8418dcd253c1 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceInterceptor.java @@ -0,0 +1,45 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.extension; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.ext.ReaderInterceptor; +import javax.ws.rs.ext.ReaderInterceptorContext; +import javax.ws.rs.ext.WriterInterceptor; +import javax.ws.rs.ext.WriterInterceptorContext; +import java.io.IOException; + +/** + * @author lishen + */ +@Priority(Priorities.USER) +public class DynamicTraceInterceptor implements ReaderInterceptor, WriterInterceptor { + + public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Dynamic reader interceptor invoked"); + return readerInterceptorContext.proceed(); + } + + public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Dynamic writer interceptor invoked"); + writerInterceptorContext.proceed(); + } +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceFilter.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceFilter.java new file mode 100644 index 000000000000..e760d90bc660 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceFilter.java @@ -0,0 +1,42 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.extension; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import java.io.IOException; + +/** + * @author lishen + */ +@Priority(Priorities.USER) +public class TraceFilter implements ContainerRequestFilter, ContainerResponseFilter { + + public void filter(ContainerRequestContext requestContext) throws IOException { + System.out.println("Request filter invoked"); + } + + public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException { + System.out.println("Response filter invoked"); + } +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceInterceptor.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceInterceptor.java new file mode 100644 index 000000000000..2c969205eecb --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceInterceptor.java @@ -0,0 +1,45 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.extension; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.ext.ReaderInterceptor; +import javax.ws.rs.ext.ReaderInterceptorContext; +import javax.ws.rs.ext.WriterInterceptor; +import javax.ws.rs.ext.WriterInterceptorContext; +import java.io.IOException; + +/** + * @author lishen + */ +@Priority(Priorities.USER) +public class TraceInterceptor implements ReaderInterceptor, WriterInterceptor { + + public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Reader interceptor invoked"); + return readerInterceptorContext.proceed(); + } + + public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException { + System.out.println("Writer interceptor invoked"); + writerInterceptorContext.proceed(); + } +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/User.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/User.java new file mode 100644 index 000000000000..556de6f43805 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/User.java @@ -0,0 +1,80 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.user; + +import org.codehaus.jackson.annotate.JsonProperty; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * @author lishen + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +public class User implements Serializable { + + @NotNull + @Min(1L) + private Long id; + + @JsonProperty("username") + @XmlElement(name = "username") + @NotNull + @Size(min = 6, max = 50) + private String name; + + public User() { + } + + public User(Long id, String name) { + this.id = id; + this.name = name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "User (" + + "id=" + id + + ", name='" + name + '${symbol_escape}'' + + ')'; + } +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/UserService.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/UserService.java new file mode 100644 index 000000000000..240260c533a1 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/UserService.java @@ -0,0 +1,28 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.user; + +/** + * @author lishen + */ +public interface UserService { + User getUser(Long id); + + Long registerUser(User user); +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/RegistrationResult.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/RegistrationResult.java new file mode 100644 index 000000000000..bff9e83fd9c7 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/RegistrationResult.java @@ -0,0 +1,48 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.user.facade; + +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +/** + * DTO to customize the returned message + * + * @author lishen + */ +@XmlRootElement +public class RegistrationResult implements Serializable { + + private Long id; + + public RegistrationResult() { + } + + public RegistrationResult(Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/UserRestService.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/UserRestService.java new file mode 100644 index 000000000000..9118713a3a40 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/UserRestService.java @@ -0,0 +1,51 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.user.facade; + +import ${package}.user.User; +import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType; + +import javax.validation.constraints.Min; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + +/** + * This interface acts as some kind of service broker for the original UserService + *

+ * Here we want to simulate the twitter/weibo rest api, e.g. + *

+ * http://localhost:8888/user/1.json + * http://localhost:8888/user/1.xml + * + * @author lishen + */ + +@Path("users") +@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) +public interface UserRestService { + + @GET + @Path("{id : ${symbol_escape}${symbol_escape}d+}") + public User getUser(@Min(value = 1L, message = "User ID must be greater than 1") @PathParam("id") Long id/*, @Context HttpServletRequest request*/); + + @POST + @Path("register") + RegistrationResult registerUser(User user); +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml new file mode 100644 index 000000000000..2dc917ff2ec9 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml @@ -0,0 +1,179 @@ + + + 4.0.0 + + ${groupId} + ${rootArtifactId} + ${version} + + ${artifactId} + jar + ${project.artifactId} + The demo consumer module of dubbo project + + false + + + + ${groupId} + ${rootArtifactId}-api + ${version} + + + com.alibaba + dubbo + + + org.javassist + javassist + + + org.jboss.netty + netty + + + org.apache.mina + mina-core + + + org.glassfish.grizzly + grizzly-core + + + org.apache.httpcomponents + httpclient + + + com.alibaba + fastjson + + + com.thoughtworks.xstream + xstream + + + org.apache.bsf + bsf-api + + + org.apache.zookeeper + zookeeper + + + com.github.sgroschupf + zkclient + + + org.apache.curator + curator-framework + + + com.googlecode.xmemcached + xmemcached + + + org.apache.cxf + cxf-rt-frontend-simple + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.thrift + libthrift + + + com.caucho + hessian + + + javax.servlet + javax.servlet-api + + + org.mortbay.jetty + jetty + + + log4j + log4j + + + org.slf4j + slf4j-api + + + redis.clients + jedis + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + javax.cache + cache-api + + + + + + maven-dependency-plugin + + + unpack + package + + unpack + + + + + com.alibaba + dubbo + ${project.parent.version} + ${project.build.directory}/dubbo + META-INF/assembly/** + + + + + + + + maven-assembly-plugin + + src/main/assembly/assembly.xml + + + + make-assembly + package + + single + + + + + + + diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/assembly.xml b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/assembly.xml new file mode 100644 index 000000000000..3516e43dc66f --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/assembly.xml @@ -0,0 +1,42 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) + + + assembly + + tar.gz + + true + + + ${symbol_dollar}{project.build.directory}/dubbo/META-INF/assembly/bin + bin + 0755 + + + src/main/assembly/conf + conf + 0644 + + + + + lib + + + diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/conf/dubbo.properties b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/conf/dubbo.properties new file mode 100644 index 000000000000..f6e6daa4122f --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/conf/dubbo.properties @@ -0,0 +1,28 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +${symbol_pound}${symbol_pound} +${symbol_pound} Copyright 1999-2011 Alibaba Group. +${symbol_pound} +${symbol_pound} Licensed under the Apache License, Version 2.0 (the "License"); +${symbol_pound} you may not use this file except in compliance with the License. +${symbol_pound} You may obtain a copy of the License at +${symbol_pound} +${symbol_pound} http://www.apache.org/licenses/LICENSE-2.0 +${symbol_pound} +${symbol_pound} Unless required by applicable law or agreed to in writing, software +${symbol_pound} distributed under the License is distributed on an "AS IS" BASIS, +${symbol_pound} WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +${symbol_pound} See the License for the specific language governing permissions and +${symbol_pound} limitations under the License. +${symbol_pound}${symbol_pound} +dubbo.container=log4j,spring +dubbo.application.name=demo-lite-consumer +dubbo.application.owner= +${symbol_pound}dubbo.registry.address=multicast://224.5.6.7:1234 +dubbo.registry.address=zookeeper://127.0.0.1:2181 +${symbol_pound}dubbo.registry.address=redis://127.0.0.1:6379 +${symbol_pound}dubbo.registry.address=dubbo://127.0.0.1:9090 +dubbo.monitor.protocol=registry +dubbo.log4j.file=logs/dubbo-demo-consumer.log +dubbo.log4j.level=WARN diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/java/consumer/DemoAction.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/java/consumer/DemoAction.java new file mode 100644 index 000000000000..3ebc5e7f8cdd --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/java/consumer/DemoAction.java @@ -0,0 +1,52 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.consumer; + +import ${package}.user.User; +import ${package}.user.UserService; +import ${package}.user.facade.UserRestService; + +/** + * User: kangfoo + * Date: 14-12-9 + * Time: 涓嬪崍4:12 + */ +public class DemoAction { + + private UserRestService userRestService; + private UserService userService; + + public void setUserService(UserService userService) { + this.userService = userService; + } + + public void setUserRestService(UserRestService userRestService) { + this.userRestService = userRestService; + } + + public void start() throws Exception { + + + User user = new User(1L, "larrypage"); + System.out.println("SUCESS: registered user with id " + userRestService.registerUser(user).getId()); + + System.out.println("SUCESS: got user " + userService.getUser(1L)); + } + +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml new file mode 100644 index 000000000000..ce672ebbeee7 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml @@ -0,0 +1,30 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) + + + + + + + + + + + diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml new file mode 100644 index 000000000000..63a302ba7e9f --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml @@ -0,0 +1,24 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) + + + + + + + + + + + + + + + + + diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/DemoConsumer.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/DemoConsumer.java new file mode 100644 index 000000000000..01ca2d6aa467 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/DemoConsumer.java @@ -0,0 +1,27 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.consumer; + +public class DemoConsumer { + + public static void main(String[] args) { + com.alibaba.dubbo.container.Main.main(args); + } + +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/RestClient.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/RestClient.java new file mode 100644 index 000000000000..8512b0234656 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/RestClient.java @@ -0,0 +1,92 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.consumer; + +import ${package}.user.User; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +/** + * @author lishen + */ +public class RestClient { + + public static void main(String[] args) { + final String port = "8888"; +// final String port = "8080"; + +// for (int i = 0; i < 500; i++) { +// final int index = i + 1; +// new Thread(new Runnable() { +// public void run() { +// System.out.println("Starting thread " + index + "..."); +// for (int j = 0; j < 500; j++) { + registerUser("http://localhost:" + port + "/services/users/register.json", MediaType.APPLICATION_JSON_TYPE); + + registerUser("http://localhost:" + port + "/services/users/register.xml", MediaType.TEXT_XML_TYPE); + + getUser("http://localhost:" + port + "/services/users/1.json"); + + getUser("http://localhost:" + port + "/services/users/2.xml"); + +// } +// } +// }).start(); +// } + } + + private static void registerUser(String url, MediaType mediaType) { + System.out.println("Registering user via " + url); + User user = new User(1L, "larrypage"); + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(url); + Response response = target.request().post(Entity.entity(user, mediaType)); + + try { + if (response.getStatus() != 200) { + throw new RuntimeException("Failed with HTTP error code : " + response.getStatus()); + } + System.out.println("Successfully got result: " + response.readEntity(String.class)); + } finally { + response.close(); + client.close(); + } + } + + private static void getUser(String url) { + System.out.println("Getting user via " + url); + Client client = ClientBuilder.newClient(); + WebTarget target = client.target(url); + Response response = target.request().get(); + try { + if (response.getStatus() != 200) { + throw new RuntimeException("Failed with HTTP error code : " + response.getStatus()); + } + System.out.println("Successfully got result: " + response.readEntity(String.class)); + } finally { + response.close(); + client.close(); + } + } +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/resources/log4j.xml b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/resources/log4j.xml new file mode 100644 index 000000000000..77898f221fdb --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/resources/log4j.xml @@ -0,0 +1,31 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) + + + + + + + + + + + + + + diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml new file mode 100644 index 000000000000..51842e825b04 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml @@ -0,0 +1,193 @@ + + + 4.0.0 + + ${groupId} + ${rootArtifactId} + ${version} + + ${artifactId} + war + ${project.artifactId} + The demo provider module of dubbo project + + false + + + + ${groupId} + ${rootArtifactId}-api + ${version} + + + com.alibaba + dubbo + + + org.javassist + javassist + + + org.jboss.netty + netty + + + org.apache.mina + mina-core + + + org.glassfish.grizzly + grizzly-core + + + org.apache.httpcomponents + httpclient + + + com.alibaba + fastjson + + + com.thoughtworks.xstream + xstream + + + org.apache.bsf + bsf-api + + + org.apache.zookeeper + zookeeper + + + com.github.sgroschupf + zkclient + + + org.apache.curator + curator-framework + + + com.googlecode.xmemcached + xmemcached + + + org.apache.cxf + cxf-rt-frontend-simple + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.thrift + libthrift + + + com.caucho + hessian + + + javax.servlet + javax.servlet-api + + + org.mortbay.jetty + jetty + + + org.mortbay.jetty + servlet-api + + + + + log4j + log4j + + + org.slf4j + slf4j-api + + + redis.clients + jedis + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + javax.cache + cache-api + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/UserServiceImpl.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/UserServiceImpl.java new file mode 100644 index 000000000000..b084730140a6 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/UserServiceImpl.java @@ -0,0 +1,41 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.user; + +import java.util.concurrent.atomic.AtomicLong; + +/** + * User: kangfoo + * Date: 14-12-9 + * Time: 涓嬪崍3:45 + */ +public class UserServiceImpl implements UserService { + + private final AtomicLong idGen = new AtomicLong(); + + public User getUser(Long id) { + return new User(id, "username" + id); + } + + + public Long registerUser(User user) { +// System.out.println("Username is " + user.getName()); + return idGen.incrementAndGet(); + } +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/facade/UserRestServiceImpl.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/facade/UserRestServiceImpl.java new file mode 100644 index 000000000000..3bf9cf567cbb --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/facade/UserRestServiceImpl.java @@ -0,0 +1,66 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/** + * Copyright 1999-2014 dangdang.com. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.user.facade; + +import ${package}.user.User; +import ${package}.user.UserService; +import com.alibaba.dubbo.rpc.RpcContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.validation.constraints.Min; +import javax.ws.rs.PathParam; + +/** + * User: kangfoo + * Date: 14-12-9 + * Time: 涓嬪崍3:45 + */ +public class UserRestServiceImpl implements UserRestService { + + private static final Logger logger = LoggerFactory.getLogger(UserRestServiceImpl.class); + + private UserService userService; + + public void setUserService(UserService userService) { + this.userService = userService; + } + + @Override + public User getUser(@Min(value = 1L, message = "User ID must be greater than 1") @PathParam("id") Long id) { + // test context injection +// System.out.println("Client address from @Context injection: " + (request != null ? request.getRemoteAddr() : "")); +// System.out.println("Client address from RpcContext: " + RpcContext.getContext().getRemoteAddressString()); + if (RpcContext.getContext().getRequest(HttpServletRequest.class) != null) { + System.out.println("Client IP address from RpcContext: " + RpcContext.getContext().getRequest(HttpServletRequest.class).getRemoteAddr()); + } + if (RpcContext.getContext().getResponse(HttpServletResponse.class) != null) { + System.out.println("Response object from RpcContext: " + RpcContext.getContext().getResponse(HttpServletResponse.class)); + } + return userService.getUser(id); + } + + @Override + public RegistrationResult registerUser(User user) { + return new RegistrationResult(userService.registerUser(user)); + } + +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml new file mode 100644 index 000000000000..bee031cc66a0 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml @@ -0,0 +1,80 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/log4j.xml b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/log4j.xml new file mode 100644 index 000000000000..77898f221fdb --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/log4j.xml @@ -0,0 +1,31 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) + + + + + + + + + + + + + + diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/webapp/WEB-INF/web.xml b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000000..f9cf14fa6769 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,33 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) + + + + + + contextConfigLocation + /WEB-INF/classes/META-INF/spring/dubbo-demo-lite-provider.xml + + + + + com.alibaba.dubbo.remoting.http.servlet.BootstrapListener + + + + org.springframework.web.context.ContextLoaderListener + + + + dispatcher + com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet + 1 + + + + dispatcher + /services/* + + diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/test/java/provider/DemoProvider.java b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/test/java/provider/DemoProvider.java new file mode 100644 index 000000000000..258856f9e56b --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/test/java/provider/DemoProvider.java @@ -0,0 +1,37 @@ +#set( $symbol_pound = '#' ) +#set( $symbol_dollar = '$' ) +#set( $symbol_escape = '\' ) +/* + * Copyright 1999-2011 Alibaba Group. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ${package}.provider; + +public class DemoProvider { + + public static void main(String[] args) { +// new Thread(new Runnable() { +// public void run() { +// try { +// Thread.sleep(20000); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } +// ProtocolConfig.destroyAll(); +// } +// }).start(); + com.alibaba.dubbo.container.Main.main(args); + } + +} diff --git a/support/maven-archetype/src/main/resources/archetype-resources/pom.xml b/support/maven-archetype/src/main/resources/archetype-resources/pom.xml new file mode 100644 index 000000000000..c1424a7766c8 --- /dev/null +++ b/support/maven-archetype/src/main/resources/archetype-resources/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + com.alibaba + dubbo-parent + 2.8.3 + + ${artifactId} + ${groupId} + pom + ${project.artifactId} + The demo lite module of dubbo project + ${version} + + true + + + + + + com.alibaba + dubbo + 2.8.3 + + + + diff --git a/support/maven-archetype/src/test/resources/projects/basic/archetype.properties b/support/maven-archetype/src/test/resources/projects/basic/archetype.properties new file mode 100644 index 000000000000..dc09b753b730 --- /dev/null +++ b/support/maven-archetype/src/test/resources/projects/basic/archetype.properties @@ -0,0 +1,5 @@ +#Thu Dec 11 15:57:06 CST 2014 +package=it.pkg +version=0.1-SNAPSHOT +groupId=archetype.it +artifactId=basic From 80481c605c0370ab5b8fc9a0903d3cb5ec0d0411 Mon Sep 17 00:00:00 2001 From: LinKang Date: Fri, 12 Dec 2014 14:54:46 +0800 Subject: [PATCH 162/200] rename support 2 dubbo-tool --- .../dubbo-demo-lite-archetype}/pom.xml | 0 .../dubbo-demo-lite-archetype/readme.md | 86 +++++++++++++++++++ .../META-INF/maven/archetype-metadata.xml | 0 .../__rootArtifactId__-api/pom.xml | 0 .../main/java/SerializationOptimizerImpl.java | 0 .../java/extension/ClientTraceFilter.java | 0 .../java/extension/CustomExceptionMapper.java | 0 .../java/extension/DynamicTraceBinding.java | 0 .../extension/DynamicTraceInterceptor.java | 0 .../src/main/java/extension/TraceFilter.java | 0 .../main/java/extension/TraceInterceptor.java | 0 .../src/main/java/user/User.java | 0 .../src/main/java/user/UserService.java | 0 .../java/user/facade/RegistrationResult.java | 0 .../java/user/facade/UserRestService.java | 0 .../__rootArtifactId__-consumer/pom.xml | 0 .../src/main/assembly/assembly.xml | 0 .../src/main/assembly/conf/dubbo.properties | 0 .../src/main/java/consumer/DemoAction.java | 0 .../spring/dubbo-demo-lite-action.xml | 0 .../spring/dubbo-demo-lite-consumer.xml | 0 .../src/test/java/consumer/DemoConsumer.java | 0 .../src/test/java/consumer/RestClient.java | 0 .../src/test/resources/log4j.xml | 0 .../__rootArtifactId__-provider/pom.xml | 0 .../src/main/java/user/UserServiceImpl.java | 0 .../java/user/facade/UserRestServiceImpl.java | 0 .../spring/dubbo-demo-lite-provider.xml | 0 .../src/main/resources/log4j.xml | 0 .../src/main/webapp/WEB-INF/web.xml | 0 .../src/test/java/provider/DemoProvider.java | 0 .../resources/archetype-resources/pom.xml | 0 .../projects/basic/archetype.properties | 0 .../dubbo-demo-lite-api/pom.xml | 0 .../demolite/SerializationOptimizerImpl.java | 0 .../demolite/extension/ClientTraceFilter.java | 0 .../extension/CustomExceptionMapper.java | 0 .../extension/DynamicTraceBinding.java | 0 .../extension/DynamicTraceInterceptor.java | 0 .../dubbo/demolite/extension/TraceFilter.java | 0 .../demolite/extension/TraceInterceptor.java | 0 .../com/alibaba/dubbo/demolite/user/User.java | 0 .../dubbo/demolite/user/UserService.java | 0 .../user/facade/RegistrationResult.java | 0 .../demolite/user/facade/UserRestService.java | 0 .../dubbo-demo-lite-consumer/pom.xml | 0 .../src/main/assembly/assembly.xml | 0 .../src/main/assembly/conf/dubbo.properties | 0 .../dubbo/demolite/consumer/DemoAction.java | 0 .../spring/dubbo-demo-lite-action.xml | 0 .../spring/dubbo-demo-lite-consumer.xml | 0 .../dubbo/demolite/consumer/DemoConsumer.java | 0 .../dubbo/demolite/consumer/RestClient.java | 0 .../src/test/resources/log4j.xml | 0 .../dubbo-demo-lite-provider/pom.xml | 0 .../dubbo/demolite/user/UserServiceImpl.java | 0 .../user/facade/UserRestServiceImpl.java | 0 .../spring/dubbo-demo-lite-provider.xml | 0 .../src/main/resources/log4j.xml | 0 .../src/main/webapp/WEB-INF/web.xml | 0 .../dubbo/demolite/provider/DemoProvider.java | 0 .../dubbo-demo-lite/pom.xml | 0 pom.xml | 3 +- support/maven-archetype/readme.md | 20 ----- 64 files changed, 87 insertions(+), 22 deletions(-) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/pom.xml (100%) create mode 100644 dubbo-tool/dubbo-demo-lite-archetype/readme.md rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/META-INF/maven/archetype-metadata.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/SerializationOptimizerImpl.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/ClientTraceFilter.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/CustomExceptionMapper.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceBinding.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceInterceptor.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceFilter.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceInterceptor.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/User.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/UserService.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/RegistrationResult.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/UserRestService.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/assembly.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/conf/dubbo.properties (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/java/consumer/DemoAction.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/DemoConsumer.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/RestClient.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/resources/log4j.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/UserServiceImpl.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/facade/UserRestServiceImpl.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/log4j.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/webapp/WEB-INF/web.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/test/java/provider/DemoProvider.java (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/main/resources/archetype-resources/pom.xml (100%) rename {support/maven-archetype => dubbo-tool/dubbo-demo-lite-archetype}/src/test/resources/projects/basic/archetype.properties (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/SerializationOptimizerImpl.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/ClientTraceFilter.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/CustomExceptionMapper.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceBinding.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceInterceptor.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceFilter.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceInterceptor.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/User.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/RegistrationResult.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestService.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/assembly.xml (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/conf/dubbo.properties (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/java/com/alibaba/dubbo/demolite/consumer/DemoAction.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/DemoConsumer.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/RestClient.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/resources/log4j.xml (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/UserServiceImpl.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestServiceImpl.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/log4j.xml (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/webapp/WEB-INF/web.xml (100%) rename {support => dubbo-tool}/dubbo-demo-lite/dubbo-demo-lite-provider/src/test/java/com/alibaba/dubbo/demolite/provider/DemoProvider.java (100%) rename {support => dubbo-tool}/dubbo-demo-lite/pom.xml (100%) delete mode 100644 support/maven-archetype/readme.md diff --git a/support/maven-archetype/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/pom.xml similarity index 100% rename from support/maven-archetype/pom.xml rename to dubbo-tool/dubbo-demo-lite-archetype/pom.xml diff --git a/dubbo-tool/dubbo-demo-lite-archetype/readme.md b/dubbo-tool/dubbo-demo-lite-archetype/readme.md new file mode 100644 index 000000000000..0d5494bc0b3a --- /dev/null +++ b/dubbo-tool/dubbo-demo-lite-archetype/readme.md @@ -0,0 +1,86 @@ +鐩殑锛 +蹇熺殑浣跨敤 maven archetype 杩涜 dubbox rest 椤圭洰宸ョ▼鎼缓銆 +鏈榛樿浠 dubbo-demo-lite 鏋勫缓涓涓 rest 鐗堟湰鐨 dubbox 妗嗘灦缁撴瀯銆 + +鍛戒护鍙傝冿細 + +1. 浠庝竴涓凡鏈夌殑椤圭洰涓瀯寤轰竴涓 maven archetype锛 +$ mvn archetype:create-from-project -Darchetype.filteredExtentions=java,xml,jsp,properties,sql + +2. 鐒跺悗鍐嶄慨鏀规ā鏉夸腑鐨勬枃浠讹紝骞舵墽琛 +$ mvn clean install + +3. 寮濮嬩粠涓涓凡鏈夌殑 maven archetype 涓鍒堕」鐩 +$ mkdir tmp +$ cd tmp +$ mvn archetype:generate -DarchetypeCatalog=local + +鏇村璧勬枡璇峰弬鑰 +http://maven.apache.org/archetype/maven-archetype-plugin/examples/create-multi-module-project.html + + +浣跨敤绀轰緥鍒椾妇锛 + +

+kangfoo@kangfoo-dk:~/work/hawkeye/tmp$ mvn archetype:generate -DarchetypeCatalog=local
+[INFO] Scanning for projects...
+[INFO]
+[INFO] ------------------------------------------------------------------------
+[INFO] Building Maven Stub Project (No POM) 1
+[INFO] ------------------------------------------------------------------------
+[INFO]
+[INFO] >>> maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom >>>
+[INFO]
+[INFO] <<< maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom <<<
+[INFO]
+[INFO] --- maven-archetype-plugin:2.2:generate (default-cli) @ standalone-pom ---
+[INFO] Generating project in Interactive mode
+[INFO] No archetype defined. Using maven-archetype-quickstart (org.apache.maven.archetypes:maven-archetype-quickstart:1.0)
+Choose archetype:
+1: local -> com.alibaba:dubbo-demo-lite-archetype (The demo lite module of dubbo project)
+Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): : 1
+Define value for property 'groupId': : com.tima
+Define value for property 'artifactId': : test3
+Define value for property 'version':  1.0-SNAPSHOT: :
+Define value for property 'package':  com.tima: : com.tima.test3
+Confirm properties configuration:
+groupId: com.tima
+artifactId: test3
+version: 1.0-SNAPSHOT
+package: com.tima.test3
+ Y: : Y
+[INFO] ----------------------------------------------------------------------------
+[INFO] Using following parameters for creating project from Archetype: dubbo-demo-lite-archetype:2.8.3
+[INFO] ----------------------------------------------------------------------------
+[INFO] Parameter: groupId, Value: com.tima
+[INFO] Parameter: artifactId, Value: test3
+[INFO] Parameter: version, Value: 1.0-SNAPSHOT
+[INFO] Parameter: package, Value: com.tima.test3
+[INFO] Parameter: packageInPathFormat, Value: com/tima/test3
+[INFO] Parameter: package, Value: com.tima.test3
+[INFO] Parameter: version, Value: 1.0-SNAPSHOT
+[INFO] Parameter: groupId, Value: com.tima
+[INFO] Parameter: artifactId, Value: test3
+[INFO] Parent element not overwritten in /home/kangfoo/work/hawkeye/tmp/test3/test3-api/pom.xml
+[INFO] Parent element not overwritten in /home/kangfoo/work/hawkeye/tmp/test3/test3-provider/pom.xml
+[INFO] Parent element not overwritten in /home/kangfoo/work/hawkeye/tmp/test3/test3-consumer/pom.xml
+[INFO] project created from Archetype in dir: /home/kangfoo/work/hawkeye/tmp/test3
+[INFO] ------------------------------------------------------------------------
+[INFO] BUILD SUCCESS
+[INFO] ------------------------------------------------------------------------
+[INFO] Total time: 27.023s
+[INFO] Finished at: Fri Dec 12 14:49:00 CST 2014
+[INFO] Final Memory: 12M/105M
+[INFO] ------------------------------------------------------------------------
+kangfoo@kangfoo-dk:~/work/hawkeye/tmp$ cd test3/
+kangfoo@kangfoo-dk:~/work/hawkeye/tmp/test3$ ll
+鎬荤敤閲 24
+drwxrwxr-x 5 kangfoo kangfoo 4096 12鏈 12 14:49 ./
+drwxrwxr-x 4 kangfoo kangfoo 4096 12鏈 12 14:49 ../
+-rw-rw-r-- 1 kangfoo kangfoo 1793 12鏈 12 14:49 pom.xml
+drwxrwxr-x 3 kangfoo kangfoo 4096 12鏈 12 14:49 test3-api/
+drwxrwxr-x 3 kangfoo kangfoo 4096 12鏈 12 14:49 test3-consumer/
+drwxrwxr-x 3 kangfoo kangfoo 4096 12鏈 12 14:49 test3-provider/
+
+
+
diff --git a/support/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/SerializationOptimizerImpl.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/SerializationOptimizerImpl.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/SerializationOptimizerImpl.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/SerializationOptimizerImpl.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/ClientTraceFilter.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/ClientTraceFilter.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/ClientTraceFilter.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/ClientTraceFilter.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/CustomExceptionMapper.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/CustomExceptionMapper.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/CustomExceptionMapper.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/CustomExceptionMapper.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceBinding.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceBinding.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceBinding.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceBinding.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceInterceptor.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceInterceptor.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceInterceptor.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceInterceptor.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceFilter.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceFilter.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceFilter.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceFilter.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceInterceptor.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceInterceptor.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceInterceptor.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceInterceptor.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/User.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/User.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/User.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/User.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/UserService.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/UserService.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/UserService.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/UserService.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/RegistrationResult.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/RegistrationResult.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/RegistrationResult.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/RegistrationResult.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/UserRestService.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/UserRestService.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/UserRestService.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/UserRestService.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/assembly.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/assembly.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/assembly.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/assembly.xml
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/conf/dubbo.properties b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/conf/dubbo.properties
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/conf/dubbo.properties
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/conf/dubbo.properties
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/java/consumer/DemoAction.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/java/consumer/DemoAction.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/java/consumer/DemoAction.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/java/consumer/DemoAction.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/DemoConsumer.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/DemoConsumer.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/DemoConsumer.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/DemoConsumer.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/RestClient.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/RestClient.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/RestClient.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/RestClient.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/resources/log4j.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/resources/log4j.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/resources/log4j.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/resources/log4j.xml
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/UserServiceImpl.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/UserServiceImpl.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/UserServiceImpl.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/UserServiceImpl.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/facade/UserRestServiceImpl.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/facade/UserRestServiceImpl.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/facade/UserRestServiceImpl.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/facade/UserRestServiceImpl.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/log4j.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/log4j.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/log4j.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/log4j.xml
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/webapp/WEB-INF/web.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/webapp/WEB-INF/web.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/webapp/WEB-INF/web.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/webapp/WEB-INF/web.xml
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/test/java/provider/DemoProvider.java b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/test/java/provider/DemoProvider.java
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/test/java/provider/DemoProvider.java
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/test/java/provider/DemoProvider.java
diff --git a/support/maven-archetype/src/main/resources/archetype-resources/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml
similarity index 100%
rename from support/maven-archetype/src/main/resources/archetype-resources/pom.xml
rename to dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml
diff --git a/support/maven-archetype/src/test/resources/projects/basic/archetype.properties b/dubbo-tool/dubbo-demo-lite-archetype/src/test/resources/projects/basic/archetype.properties
similarity index 100%
rename from support/maven-archetype/src/test/resources/projects/basic/archetype.properties
rename to dubbo-tool/dubbo-demo-lite-archetype/src/test/resources/projects/basic/archetype.properties
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/SerializationOptimizerImpl.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/SerializationOptimizerImpl.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/SerializationOptimizerImpl.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/SerializationOptimizerImpl.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/ClientTraceFilter.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/ClientTraceFilter.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/ClientTraceFilter.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/ClientTraceFilter.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/CustomExceptionMapper.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/CustomExceptionMapper.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/CustomExceptionMapper.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/CustomExceptionMapper.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceBinding.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceBinding.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceBinding.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceBinding.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceInterceptor.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceInterceptor.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceInterceptor.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceInterceptor.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceFilter.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceFilter.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceFilter.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceFilter.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceInterceptor.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceInterceptor.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceInterceptor.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceInterceptor.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/User.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/User.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/User.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/User.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/RegistrationResult.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/RegistrationResult.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/RegistrationResult.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/RegistrationResult.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestService.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestService.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestService.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestService.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/assembly.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/assembly.xml
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/assembly.xml
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/assembly.xml
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/conf/dubbo.properties b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/conf/dubbo.properties
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/conf/dubbo.properties
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/conf/dubbo.properties
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/java/com/alibaba/dubbo/demolite/consumer/DemoAction.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/java/com/alibaba/dubbo/demolite/consumer/DemoAction.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/java/com/alibaba/dubbo/demolite/consumer/DemoAction.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/java/com/alibaba/dubbo/demolite/consumer/DemoAction.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/DemoConsumer.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/DemoConsumer.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/DemoConsumer.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/DemoConsumer.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/RestClient.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/RestClient.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/RestClient.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/RestClient.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/resources/log4j.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/resources/log4j.xml
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/resources/log4j.xml
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/resources/log4j.xml
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/UserServiceImpl.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/UserServiceImpl.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/UserServiceImpl.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/UserServiceImpl.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestServiceImpl.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestServiceImpl.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestServiceImpl.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestServiceImpl.java
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/log4j.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/log4j.xml
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/log4j.xml
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/log4j.xml
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/webapp/WEB-INF/web.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/webapp/WEB-INF/web.xml
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/webapp/WEB-INF/web.xml
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/webapp/WEB-INF/web.xml
diff --git a/support/dubbo-demo-lite/dubbo-demo-lite-provider/src/test/java/com/alibaba/dubbo/demolite/provider/DemoProvider.java b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/test/java/com/alibaba/dubbo/demolite/provider/DemoProvider.java
similarity index 100%
rename from support/dubbo-demo-lite/dubbo-demo-lite-provider/src/test/java/com/alibaba/dubbo/demolite/provider/DemoProvider.java
rename to dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/test/java/com/alibaba/dubbo/demolite/provider/DemoProvider.java
diff --git a/support/dubbo-demo-lite/pom.xml b/dubbo-tool/dubbo-demo-lite/pom.xml
similarity index 100%
rename from support/dubbo-demo-lite/pom.xml
rename to dubbo-tool/dubbo-demo-lite/pom.xml
diff --git a/pom.xml b/pom.xml
index d66e896dc1af..97a386bf9dc1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -53,8 +53,7 @@
 		dubbo-admin
 		dubbo-demo
 		hessian-lite
-        support/dubbo-demo-lite
-        support/maven-archetype
+        dubbo-tool/dubbo-demo-lite-archetype
 	
 	
 		
diff --git a/support/maven-archetype/readme.md b/support/maven-archetype/readme.md
deleted file mode 100644
index 34b639ab96e4..000000000000
--- a/support/maven-archetype/readme.md
+++ /dev/null
@@ -1,20 +0,0 @@
-鐩殑锛
-蹇熺殑浣跨敤 maven archetype 杩涜 dubbox rest 椤圭洰宸ョ▼鎼缓銆
-鏈榛樿浠 dubbo-demo-lite 鏋勫缓涓涓 rest 鐗堟湰鐨 dubbox 妗嗘灦缁撴瀯銆
-
-鍛戒护鍙傝冿細
-
-1. 浠庝竴涓凡鏈夌殑椤圭洰涓瀯寤轰竴涓 maven archetype锛
-$ mvn archetype:create-from-project -Darchetype.filteredExtentions=java,xml,jsp,properties,sql
-
-2. 鐒跺悗鍐嶄慨鏀规ā鏉夸腑鐨勬枃浠讹紝骞舵墽琛
-$ mvn clean install
-
-3. 寮濮嬩粠涓涓凡鏈夌殑 maven archetype 涓鍒堕」鐩
-$ mkdir tmp
-$ cd tmp
-$ mvn archetype:generate -DarchetypeCatalog=local
-
-鏇村璧勬枡璇峰弬鑰
-http://maven.apache.org/archetype/maven-archetype-plugin/examples/create-multi-module-project.html
-

From 0e6afd7dc466c32b6f717d4e66a2e2eb00003092 Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Fri, 19 Dec 2014 11:42:47 +0800
Subject: [PATCH 163/200] update docs

---
 README.md | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/README.md b/README.md
index 36e3497df90a..ff9565565106 100644
--- a/README.md
+++ b/README.md
@@ -8,8 +8,9 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p
 * 鐜嬪畤杞 [褰撳綋缃慮(http://www.dangdang.com/) wangyuxuan@dangdang.com
 * 椹噾鍑 [闊╅兘琛h垗](http://www.handu.com/) majinkai@handu.com
 * Dylan 鐙珛寮鍙戣 dinguangx@163.com
+* Kangfoo 鐙珛寮鍙戣
 
-**璁ㄨQQ缇**锛305896472
+**璁ㄨQQ缇**锛305896472  锛堜笉闄愪簬dubbox锛屽寘鎷琒OA璁捐绛夌瓑鍏磋叮浜ゆ祦锛
 
 ## Dubbox褰撳墠鐨勪富瑕佸姛鑳
 
@@ -47,7 +48,7 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p
 
 [Dubbox@InfoQ](http://www.infoq.com/cn/news/2014/10/dubbox-open-source) 
 
-[Dubbox Wiki](https://github.com/dangdangdotcom/dubbox/wiki) 锛堢敱绀惧尯鑷効鑰呰嚜鐢辩紪杈戠殑锛
+[Dubbox Wiki](https://github.com/dangdangdotcom/dubbox/wiki) 锛堢敱绀惧尯蹇楁効鑰呰嚜鐢辩紪杈戠殑锛
 
 ## 鐗堟湰
 

From 539ed071a64c1d0e97749bb4bb5fb7c71be58742 Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Sat, 27 Dec 2014 17:01:48 +0800
Subject: [PATCH 164/200] add support for dubbo rest clients in webapp
 deployment

---
 .../dubbo/rpc/protocol/rest/RestProtocol.java | 30 +++++++++++++++++--
 1 file changed, 27 insertions(+), 3 deletions(-)

diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java
index 3bbfadfb3954..ef217f222bba 100644
--- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java
+++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java
@@ -19,6 +19,8 @@
 import com.alibaba.dubbo.common.URL;
 import com.alibaba.dubbo.common.utils.StringUtils;
 import com.alibaba.dubbo.remoting.http.HttpBinder;
+import com.alibaba.dubbo.remoting.http.servlet.BootstrapListener;
+import com.alibaba.dubbo.remoting.http.servlet.ServletManager;
 import com.alibaba.dubbo.rpc.RpcException;
 import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol;
 import com.alibaba.dubbo.rpc.protocol.ServiceImplHolder;
@@ -40,6 +42,7 @@
 import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
 import org.jboss.resteasy.util.GetRestful;
 
+import javax.servlet.ServletContext;
 import javax.ws.rs.ProcessingException;
 import javax.ws.rs.WebApplicationException;
 import java.util.Collections;
@@ -87,8 +90,30 @@ protected  Runnable doExport(T impl, Class type, URL url) throws RpcExcept
             servers.put(addr, server);
         }
 
+        String contextPath = getContextPath(url);
+        if ("servlet".equalsIgnoreCase(url.getParameter(Constants.SERVER_KEY, "jetty"))) {
+            ServletContext servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT);
+            if (servletContext == null) {
+                throw new RpcException("No servlet context found. Since you are using server='servlet', " +
+                        "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml");
+            }
+            String webappPath = servletContext.getContextPath();
+            if (StringUtils.isNotEmpty(webappPath)) {
+                webappPath = webappPath.substring(1);
+                if (!contextPath.startsWith(webappPath)) {
+                    throw new RpcException("Since you are using server='servlet', " +
+                            "make sure that the 'contextpath' property starts with the path of external webapp");
+                }
+                contextPath = contextPath.substring(webappPath.length());
+                if (contextPath.startsWith("/")) {
+                    contextPath = contextPath.substring(1);
+                }
+            }
+        }
+
         final Class resourceDef = GetRestful.getRootResourceClass(implClass) != null ? implClass : type;
-        server.deploy(resourceDef, impl, getContextPath(url));
+
+        server.deploy(resourceDef, impl, contextPath);
 
         final RestServer s = server;
         return new Runnable() {
@@ -199,8 +224,7 @@ public void destroy() {
     }
 
     protected String getContextPath(URL url) {
-        // TODO better solution?
-        int pos = url.getPath().indexOf("/");
+        int pos = url.getPath().lastIndexOf("/");
         return pos > 0 ? url.getPath().substring(0, pos) : "";
     }
 

From 306372b67878cbfa4fbf32bba3e6f686809e2ad3 Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Sat, 27 Dec 2014 17:05:11 +0800
Subject: [PATCH 165/200] disable dubbo-tool fow now

---
 pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/pom.xml b/pom.xml
index 97a386bf9dc1..2ce11152ecbf 100644
--- a/pom.xml
+++ b/pom.xml
@@ -53,7 +53,7 @@
 		dubbo-admin
 		dubbo-demo
 		hessian-lite
-        dubbo-tool/dubbo-demo-lite-archetype
+        
 	
 	
 		

From 500909b610f206973433c72c820c37c4366c1d8c Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Mon, 29 Dec 2014 14:52:17 +0800
Subject: [PATCH 166/200] update docs

---
 README.md | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/README.md b/README.md
index ff9565565106..9c32dd023623 100644
--- a/README.md
+++ b/README.md
@@ -73,6 +73,10 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p
 
 ## FAQ锛堟殏瀛橈級
 
+### Dubbox闇瑕佷粈涔堢増鏈殑JDK锛
+
+鐩墠鏈濂藉湪JDK 1.7浠ヤ笂杩愯
+
 ### Dubbo REST鐨勬湇鍔¤兘鍜孌ubbo娉ㄥ唽涓績銆佺洃鎺т腑蹇冮泦鎴愬悧锛
 
 鍙互鐨勶紝鑰屼笖鏄嚜鍔ㄩ泦鎴愮殑锛屼篃灏辨槸浣犲湪dubbo涓紑鍙戠殑鎵鏈塕EST鏈嶅姟閮戒細鑷姩娉ㄥ唽鍒版湇鍔″唽涓績鍜岀洃鎺т腑蹇冿紝鍙互閫氳繃瀹冧滑鍋氱鐞嗐

From f49ae8dbd0149c7512d1abe110fdd2fb166b888f Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Mon, 29 Dec 2014 15:41:42 +0800
Subject: [PATCH 167/200] refactor rest and dependencies

---
 dubbo-common/pom.xml                          |   7 +-
 dubbo-demo/dubbo-demo-api/pom.xml             |  42 +-
 dubbo-demo/dubbo-demo-consumer/pom.xml        |  57 +
 .../dubbo/demo/consumer/DemoAction.java       |   9 +-
 dubbo-demo/dubbo-demo-provider/pom.xml        | 192 ++--
 .../facade/AnotherUserRestServiceImpl.java    |   3 +
 .../dubbo/rpc/filter/ContextFilter.java       |  16 +-
 .../dubbo/rpc/protocol/dubbo/DubboCodec.java  |   2 -
 dubbo-rpc/dubbo-rpc-rest/pom.xml              | 102 +-
 .../dubbo/rpc/protocol/rest/RestProtocol.java |   1 +
 .../rpc/protocol/rest/RpcContextFilter.java   |  49 +-
 .../rpc/protocol/rest/UndertowServer.java     |  86 +-
 dubbo/pom.xml                                 | 974 +++++++++---------
 pom.xml                                       |  52 +
 14 files changed, 916 insertions(+), 676 deletions(-)

diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml
index 0fd4705f3535..668a692ab0a9 100644
--- a/dubbo-common/pom.xml
+++ b/dubbo-common/pom.xml
@@ -69,21 +69,22 @@
         
             com.esotericsoftware.kryo
             kryo
-            2.24.0
+            provided
         
         
             de.javakaffee
             kryo-serializers
-            0.26
+            provided
         
         
             de.ruedigermoeller
             fst
-            1.55
+            provided
         
         
             com.fasterxml.jackson.core
             jackson-databind
+            provided
         
     
 
\ No newline at end of file
diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml
index 0b3df71b6365..1cd8b001f90a 100644
--- a/dubbo-demo/dubbo-demo-api/pom.xml
+++ b/dubbo-demo/dubbo-demo-api/pom.xml
@@ -14,20 +14,20 @@
  - limitations under the License.
 -->
 
-	4.0.0
-	
-		com.alibaba
-		dubbo-demo
-		2.8.3
-	
-	dubbo-demo-api
-	jar
-	${project.artifactId}
-	The demo module of dubbo project
-	
-		true
-	
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    4.0.0
+    
+        com.alibaba
+        dubbo-demo
+        2.8.3
+    
+    dubbo-demo-api
+    jar
+    ${project.artifactId}
+    The demo module of dubbo project
+    
+        true
+    
     
         
             com.alibaba
@@ -42,5 +42,19 @@
             javax.validation
             validation-api
         
+        
+            javax.ws.rs
+            javax.ws.rs-api
+        
+        
+            javax.annotation
+            javax.annotation-api
+            1.2
+        
+        
+            org.codehaus.jackson
+            jackson-mapper-asl
+            1.9.12
+        
     
 
\ No newline at end of file
diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml
index 237843945fe8..8d9600bf599c 100644
--- a/dubbo-demo/dubbo-demo-consumer/pom.xml
+++ b/dubbo-demo/dubbo-demo-consumer/pom.xml
@@ -135,6 +135,63 @@
             javax.cache
             cache-api
         
+
+        
+            javax.ws.rs
+            javax.ws.rs-api
+        
+
+        
+            org.jboss.resteasy
+            resteasy-jaxrs
+        
+
+        
+            org.jboss.resteasy
+            resteasy-client
+        
+
+        
+            org.jboss.resteasy
+            resteasy-netty
+        
+
+        
+            org.jboss.resteasy
+            resteasy-jdk-http
+        
+
+        
+            org.jboss.resteasy
+            resteasy-jackson-provider
+        
+
+        
+            org.jboss.resteasy
+            resteasy-jaxb-provider
+        
+
+        
+            org.apache.tomcat.embed
+            tomcat-embed-core
+        
+        
+            org.apache.tomcat.embed
+            tomcat-embed-logging-juli
+        
+
+        
+            com.esotericsoftware.kryo
+            kryo
+        
+        
+            de.javakaffee
+            kryo-serializers
+        
+        
+            de.ruedigermoeller
+            fst
+        
     
     
         
diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java
index a65bd214e78b..b6138e729adc 100644
--- a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java
+++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java
@@ -21,6 +21,7 @@
 import com.alibaba.dubbo.demo.bid.*;
 import com.alibaba.dubbo.demo.user.User;
 import com.alibaba.dubbo.demo.user.facade.AnotherUserRestService;
+import com.alibaba.dubbo.rpc.RpcContext;
 
 public class DemoAction {
 
@@ -65,7 +66,7 @@ public void start() throws Exception {
 
 //        for (int i = 0; i < 10000; i ++) {
 //        System.out.println(bidService.bid(request).getId());
-        System.out.println("SUCESS: got bid response id: " + bidService.bid(request).getId());
+        System.out.println("SUCCESS: got bid response id: " + bidService.bid(request).getId());
 //        }
 
 //        System.out.println(">>>>> Total time consumed:" + (System.currentTimeMillis() - start));
@@ -78,9 +79,11 @@ public void start() throws Exception {
         }
 
         User user = new User(1L, "larrypage");
-        System.out.println("SUCESS: registered user with id " + anotherUserRestService.registerUser(user).getId());
+        System.out.println("SUCCESS: registered user with id " + anotherUserRestService.registerUser(user).getId());
 
-        System.out.println("SUCESS: got user " + anotherUserRestService.getUser(1L));
+        RpcContext.getContext().setAttachment("clientName", "demo");
+        RpcContext.getContext().setAttachment("clientImpl", "dubbox");
+        System.out.println("SUCCESS: got user " + anotherUserRestService.getUser(1L));
     }
 
 }
\ No newline at end of file
diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml
index f71f03f06228..d06474c27c57 100644
--- a/dubbo-demo/dubbo-demo-provider/pom.xml
+++ b/dubbo-demo/dubbo-demo-provider/pom.xml
@@ -14,31 +14,31 @@
  - limitations under the License.
 -->
 
-	4.0.0
-	
-		com.alibaba
-		dubbo-demo
-		2.8.3
-	
-	dubbo-demo-provider
-	war
-	${project.artifactId}
-	The demo provider module of dubbo project
-	
-		false
-	
-	
-		
-			com.alibaba
-			dubbo-demo-api
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo
-			${project.parent.version}
-		
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    4.0.0
+    
+        com.alibaba
+        dubbo-demo
+        2.8.3
+    
+    dubbo-demo-provider
+    war
+    ${project.artifactId}
+    The demo provider module of dubbo project
+    
+        false
+    
+    
+        
+            com.alibaba
+            dubbo-demo-api
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo
+            ${project.parent.version}
+        
         
             org.javassist
             javassist
@@ -144,50 +144,100 @@
         
             javax.ws.rs
             javax.ws.rs-api
-            2.0
-            
-        
-	
-	
-		
-			
-				
-				
-					
-						
-						
-						
-							
-						
-						
-							
-								
-									
-									
-									
-									
-									
-								
-							
-						
-					
-				
-			
-			
-				
-                
-                    
-                
-                
-					
-						
-						
-						
-							
-						
-					
-				
-            
-		
-	
+        
+
+        
+            org.jboss.resteasy
+            resteasy-jaxrs
+        
+
+        
+            org.jboss.resteasy
+            resteasy-client
+        
+
+        
+            org.jboss.resteasy
+            resteasy-netty
+        
+
+        
+            org.jboss.resteasy
+            resteasy-jdk-http
+        
+
+        
+            org.jboss.resteasy
+            resteasy-jackson-provider
+        
+
+        
+            org.jboss.resteasy
+            resteasy-jaxb-provider
+        
+
+        
+            org.apache.tomcat.embed
+            tomcat-embed-core
+        
+        
+            org.apache.tomcat.embed
+            tomcat-embed-logging-juli
+        
+
+        
+            com.esotericsoftware.kryo
+            kryo
+        
+        
+            de.javakaffee
+            kryo-serializers
+        
+        
+            de.ruedigermoeller
+            fst
+        
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
+    
 
\ No newline at end of file
diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestServiceImpl.java
index 31da5f93aa63..23a1ba282e23 100644
--- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestServiceImpl.java
+++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestServiceImpl.java
@@ -17,6 +17,7 @@
 
 import com.alibaba.dubbo.demo.user.User;
 import com.alibaba.dubbo.demo.user.UserService;
+import com.alibaba.dubbo.rpc.RpcContext;
 
 /**
  * @author lishen
@@ -30,6 +31,8 @@ public void setUserService(UserService userService) {
     }
 
     public User getUser(Long id) {
+        System.out.println("Client name is " + RpcContext.getContext().getAttachment("clientName"));
+        System.out.println("Client impl is " + RpcContext.getContext().getAttachment("clientImpl"));
         return userService.getUser(id);
     }
 
diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java
index f3736907a05a..4097697ecfbe 100644
--- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java
+++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/filter/ContextFilter.java
@@ -50,9 +50,19 @@ public Result invoke(Invoker invoker, Invocation invocation) throws RpcExcept
         RpcContext.getContext()
                 .setInvoker(invoker)
                 .setInvocation(invocation)
-                .setAttachments(attachments)
-                .setLocalAddress(invoker.getUrl().getHost(), 
-                                 invoker.getUrl().getPort());
+//                .setAttachments(attachments)  // modified by lishen
+                .setLocalAddress(invoker.getUrl().getHost(),
+                        invoker.getUrl().getPort());
+
+        // modified by lishen
+        if (attachments != null) {
+            if (RpcContext.getContext().getAttachments() != null) {
+                RpcContext.getContext().getAttachments().putAll(attachments);
+            } else {
+                RpcContext.getContext().setAttachments(attachments);
+            }
+        }
+
         if (invocation instanceof RpcInvocation) {
             ((RpcInvocation)invocation).setInvoker(invoker);
         }
diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java
index b70a84dce74c..3c748bf36efd 100644
--- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java
+++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java
@@ -29,7 +29,6 @@
 import com.alibaba.dubbo.common.serialize.ObjectOutput;
 import com.alibaba.dubbo.common.serialize.OptimizedSerialization;
 import com.alibaba.dubbo.common.serialize.Serialization;
-import com.alibaba.dubbo.common.serialize.support.kryo.KryoSerialization;
 import com.alibaba.dubbo.common.utils.ReflectUtils;
 import com.alibaba.dubbo.common.utils.StringUtils;
 import com.alibaba.dubbo.remoting.Channel;
@@ -41,7 +40,6 @@
 import com.alibaba.dubbo.rpc.Invocation;
 import com.alibaba.dubbo.rpc.Result;
 import com.alibaba.dubbo.rpc.RpcInvocation;
-import com.esotericsoftware.kryo.KryoSerializable;
 
 import static com.alibaba.dubbo.rpc.protocol.dubbo.CallbackServiceCodec.encodeInvocationArgument;
 
diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml
index de1328ddb1cc..c4282b5f9b74 100644
--- a/dubbo-rpc/dubbo-rpc-rest/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml
@@ -41,71 +41,31 @@
             ${project.parent.version}
         
 
-        
-            
-            
-        
-
-		
-			
-			
-			
-		
-
-        
-            
-            
-            
-        
-
-        
+        
+            org.jboss.resteasy
+            resteasy-jaxrs
+        
 
-        
-            
-            
-            
-        
+        
+            org.jboss.resteasy
+            resteasy-client
+        
 
-        
-            
-            
-            
-        
-        
-            
-            
-            
-            
-        
-        
-            
-            
-            
-            
-        
-        
-            
-            
-            
-            
-        
+        
+            javax.validation
+            validation-api
+        
 
-        
-            
-            
-            
-        
+        
 
         
             org.jboss.resteasy
             resteasy-netty
-            3.0.7.Final
         
 
         
             org.jboss.resteasy
             resteasy-jdk-http
-            3.0.7.Final
         
 
         
@@ -114,36 +74,30 @@
             
         
 
-        
-            org.jboss.resteasy
-            resteasy-undertow
-            3.0.7.Final
-        
-        
-            io.undertow
-            undertow-servlet
-            1.0.1.Final
-        
-        
-            io.undertow
-            undertow-core
-            1.0.1.Final
-        
+        
+            
+            
+            
+        
+        
+            
+            
+            
+        
+        
+            
+            
+            
+        
 
         
             org.jboss.resteasy
             resteasy-jackson-provider
-            3.0.7.Final
         
 
         
             org.jboss.resteasy
             resteasy-jaxb-provider
-            3.0.7.Final
-        
-        
-            javax.validation
-            validation-api
         
     
 
\ No newline at end of file
diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java
index ef217f222bba..bfe212505878 100644
--- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java
+++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java
@@ -171,6 +171,7 @@ public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
         ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
         clients.add(client);
 
+        client.register(RpcContextFilter.class);
         for (String clazz : Constants.COMMA_SPLIT_PATTERN.split(url.getParameter(Constants.EXTENSION_KEY, ""))) {
             if (!StringUtils.isEmpty(clazz)) {
                 try {
diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java
index a9667c432d85..5c678d964b99 100644
--- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java
+++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RpcContextFilter.java
@@ -15,19 +15,30 @@
  */
 package com.alibaba.dubbo.rpc.protocol.rest;
 
+import com.alibaba.dubbo.common.utils.StringUtils;
 import com.alibaba.dubbo.rpc.RpcContext;
 import org.jboss.resteasy.spi.ResteasyProviderFactory;
 
+import javax.annotation.Priority;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.client.ClientRequestContext;
+import javax.ws.rs.client.ClientRequestFilter;
 import javax.ws.rs.container.ContainerRequestContext;
 import javax.ws.rs.container.ContainerRequestFilter;
 import java.io.IOException;
+import java.util.Map;
 
 /**
  * @author lishen
  */
-public class RpcContextFilter implements ContainerRequestFilter {
+@Priority(Integer.MIN_VALUE + 1)
+public class RpcContextFilter implements ContainerRequestFilter, ClientRequestFilter {
+
+    private static final String DUBBO_ATTACHMENT_HEADER = "Dubbo-Attachments";
+
+    // currently we use a single header to hold the attachments so that the total attachment size limit is about 8k
+    private static final int MAX_HEADER_SIZE = 8 * 1024;
 
     public void filter(ContainerRequestContext requestContext) throws IOException {
         HttpServletRequest request = ResteasyProviderFactory.getContextData(HttpServletRequest.class);
@@ -39,5 +50,41 @@ public void filter(ContainerRequestContext requestContext) throws IOException {
         }
 
         RpcContext.getContext().setResponse(ResteasyProviderFactory.getContextData(HttpServletResponse.class));
+
+        String headers = requestContext.getHeaderString(DUBBO_ATTACHMENT_HEADER);
+        if (headers != null) {
+            for (String header : headers.split(",")) {
+                int index = header.indexOf("=");
+                if (index > 0) {
+                    String key = header.substring(0, index);
+                    String value = header.substring(index + 1);
+                    if (!StringUtils.isEmpty(key)) {
+                        RpcContext.getContext().setAttachment(key.trim(), value.trim());
+                    }
+                }
+            }
+        }
+    }
+
+    public void filter(ClientRequestContext requestContext) throws IOException {
+        int size = 0;
+        for (Map.Entry entry : RpcContext.getContext().getAttachments().entrySet()) {
+            if (entry.getValue().contains(",") || entry.getValue().contains("=")
+                    || entry.getKey().contains(",") || entry.getKey().contains("=")) {
+                throw new IllegalArgumentException("The attachments of " + RpcContext.class.getSimpleName() + " must not contain ',' or '=' when using rest protocol");
+            }
+
+            // TODO for now we don't consider the differences of encoding and server limit
+            size += entry.getValue().getBytes("UTF-8").length;
+            if (size > MAX_HEADER_SIZE) {
+                throw new IllegalArgumentException("The attachments of " + RpcContext.class.getSimpleName() + " is too big");
+            }
+
+            StringBuilder attachments = new StringBuilder();
+            attachments.append(entry.getKey());
+            attachments.append("=");
+            attachments.append(entry.getValue());
+            requestContext.getHeaders().add(DUBBO_ATTACHMENT_HEADER, attachments.toString());
+        }
     }
 }
diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java
index 4b6eac4973e3..d8d7ff060283 100644
--- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java
+++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/UndertowServer.java
@@ -15,54 +15,54 @@
  */
 package com.alibaba.dubbo.rpc.protocol.rest;
 
-import com.alibaba.dubbo.common.URL;
-import com.alibaba.dubbo.common.utils.StringUtils;
-import io.undertow.Undertow;
-import io.undertow.servlet.api.DeploymentInfo;
-import org.jboss.resteasy.plugins.server.undertow.UndertowJaxrsServer;
-import org.jboss.resteasy.spi.ResteasyDeployment;
+//import com.alibaba.dubbo.common.URL;
+//import com.alibaba.dubbo.common.utils.StringUtils;
+//import io.undertow.Undertow;
+//import io.undertow.servlet.api.DeploymentInfo;
+//import org.jboss.resteasy.plugins.server.undertow.UndertowJaxrsServer;
+//import org.jboss.resteasy.spi.ResteasyDeployment;
 
 /**
  * TODO this impl hasn't been well tested, and we can consider move undertow to a general remoting-http impl in the future
  *
  * @author lishen
  */
-public class UndertowServer implements RestServer {
+public class UndertowServer /*implements RestServer*/ {
 
-    // Note that UndertowJaxrsServer doesn't implement EmbeddedJaxrsServer
-
-    private final ResteasyDeployment deployment = new ResteasyDeployment();
-
-    private final UndertowJaxrsServer server = new UndertowJaxrsServer();
-
-    public void start(URL url) {
-        deployment.start();
-        DeploymentInfo deploymentInfo = server.undertowDeployment(deployment);
-        deploymentInfo.setContextPath("/");
-        deploymentInfo.setDeploymentName("dubbo-rest");
-        deploymentInfo.setClassLoader(Thread.currentThread().getContextClassLoader());
-        server.deploy(deploymentInfo);
-        server.start(Undertow.builder().addHttpListener(url.getPort(), url.getHost()));
-    }
-
-    public void deploy(Class resourceDef, Object resourceInstance, String contextPath) {
-        if (StringUtils.isEmpty(contextPath)) {
-            deployment.getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef));
-        } else {
-            deployment.getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef), contextPath);
-        }
-    }
-
-    public void undeploy(Class resourceDef) {
-        deployment.getRegistry().removeRegistrations(resourceDef);
-    }
-
-    public void deploy(Class resourceDef, Object resourceInstance) {
-        deploy(resourceDef, resourceInstance, "/");
-    }
-
-    public void stop() {
-        deployment.stop();
-        server.stop();
-    }
+//    // Note that UndertowJaxrsServer doesn't implement EmbeddedJaxrsServer
+//
+//    private final ResteasyDeployment deployment = new ResteasyDeployment();
+//
+//    private final UndertowJaxrsServer server = new UndertowJaxrsServer();
+//
+//    public void start(URL url) {
+//        deployment.start();
+//        DeploymentInfo deploymentInfo = server.undertowDeployment(deployment);
+//        deploymentInfo.setContextPath("/");
+//        deploymentInfo.setDeploymentName("dubbo-rest");
+//        deploymentInfo.setClassLoader(Thread.currentThread().getContextClassLoader());
+//        server.deploy(deploymentInfo);
+//        server.start(Undertow.builder().addHttpListener(url.getPort(), url.getHost()));
+//    }
+//
+//    public void deploy(Class resourceDef, Object resourceInstance, String contextPath) {
+//        if (StringUtils.isEmpty(contextPath)) {
+//            deployment.getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef));
+//        } else {
+//            deployment.getRegistry().addResourceFactory(new DubboResourceFactory(resourceInstance, resourceDef), contextPath);
+//        }
+//    }
+//
+//    public void undeploy(Class resourceDef) {
+//        deployment.getRegistry().removeRegistrations(resourceDef);
+//    }
+//
+//    public void deploy(Class resourceDef, Object resourceInstance) {
+//        deploy(resourceDef, resourceInstance, "/");
+//    }
+//
+//    public void stop() {
+//        deployment.stop();
+//        server.stop();
+//    }
 }
diff --git a/dubbo/pom.xml b/dubbo/pom.xml
index 2346581c4e43..cbac4736c37f 100644
--- a/dubbo/pom.xml
+++ b/dubbo/pom.xml
@@ -14,479 +14,529 @@
  - limitations under the License.
 -->
 
-	4.0.0
-	
-		com.alibaba
-		dubbo-parent
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    4.0.0
+    
+        com.alibaba
+        dubbo-parent
         2.8.3
-	
-	dubbo
-	jar
-	${project.artifactId}
-	The all in one project of dubbo
-	
-		false
-	
-	
-		
-			com.alibaba
-			dubbo-config-api
-			${project.parent.version}
-			
-				
-					org.mortbay.jetty
-					jetty
-				
-			
-		
-		
-			com.alibaba
-			dubbo-config-spring
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-remoting-netty
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-remoting-mina
-			${project.parent.version}
-			
-				
-					org.apache.mina
-					mina-core
-				
-				
-					org.slf4j
-					slf4j-api
-				
-			
-		
-		
-			com.alibaba
-			dubbo-remoting-grizzly
-			${project.parent.version}
-			
-				
-					org.glassfish.grizzly
-					grizzly-core
-				
-			
-		
-		
-			com.alibaba
-			dubbo-remoting-p2p
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-remoting-http
-			${project.parent.version}
-			
-				
-					org.mortbay.jetty
-					jetty
-				
-				
-					org.apache.httpcomponents
-		    		httpclient
-				
-			
-		
-		
-			com.alibaba
-			dubbo-rpc-default
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-rpc-injvm
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-rpc-rmi
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-rpc-hessian
-			${project.parent.version}
-			
-				
-					com.caucho
-    				hessian
-				
-			
-		
-		
-			com.alibaba
-			dubbo-rpc-http
-			${project.parent.version}
-			
-				
-					com.caucho
-    				hessian
-				
-			
-		
-		
-			com.alibaba
-			dubbo-rpc-webservice
-			${project.parent.version}
-			
-				
-					org.apache.cxf
-					cxf-rt-frontend-simple
-				
-				
-					org.apache.cxf
-					cxf-rt-transports-http
-				
-			
-		
-		
-			com.alibaba
-			dubbo-rpc-thrift
-			${project.parent.version}
-			
-				
-					org.apache.thrift
-					libthrift
-				
-			
-		
-		
-			com.alibaba
-			dubbo-rpc-memcached
-			${project.parent.version}
-			
-				
-					com.googlecode.xmemcached
-		    		xmemcached
-				
-			
-		
-		
-			com.alibaba
-			dubbo-rpc-redis
-			${project.parent.version}
-			
-				
-					redis.clients
-					jedis
-				
-			
-		
+    
+    dubbo
+    jar
+    ${project.artifactId}
+    The all in one project of dubbo
+    
+        false
+    
+    
+        
+            com.alibaba
+            dubbo-config-api
+            ${project.parent.version}
+            
+                
+                    org.mortbay.jetty
+                    jetty
+                
+            
+        
+        
+            com.alibaba
+            dubbo-config-spring
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo-remoting-netty
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo-remoting-mina
+            ${project.parent.version}
+            
+                
+                    org.apache.mina
+                    mina-core
+                
+                
+                    org.slf4j
+                    slf4j-api
+                
+            
+        
+        
+            com.alibaba
+            dubbo-remoting-grizzly
+            ${project.parent.version}
+            
+                
+                    org.glassfish.grizzly
+                    grizzly-core
+                
+            
+        
+        
+            com.alibaba
+            dubbo-remoting-p2p
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo-remoting-http
+            ${project.parent.version}
+            
+                
+                    org.mortbay.jetty
+                    jetty
+                
+                
+                    org.apache.httpcomponents
+                    httpclient
+                
+                
+                    org.apache.tomcat.embed
+                    tomcat-embed-core
+                
+                
+                    org.apache.tomcat.embed
+                    tomcat-embed-logging-juli
+                
+            
+        
+        
+            com.alibaba
+            dubbo-rpc-default
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo-rpc-injvm
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo-rpc-rmi
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo-rpc-hessian
+            ${project.parent.version}
+            
+                
+                    com.caucho
+                    hessian
+                
+            
+        
+        
+            com.alibaba
+            dubbo-rpc-http
+            ${project.parent.version}
+            
+                
+                    com.caucho
+                    hessian
+                
+            
+        
+        
+            com.alibaba
+            dubbo-rpc-webservice
+            ${project.parent.version}
+            
+                
+                    org.apache.cxf
+                    cxf-rt-frontend-simple
+                
+                
+                    org.apache.cxf
+                    cxf-rt-transports-http
+                
+            
+        
+        
+            com.alibaba
+            dubbo-rpc-thrift
+            ${project.parent.version}
+            
+                
+                    org.apache.thrift
+                    libthrift
+                
+            
+        
+        
+            com.alibaba
+            dubbo-rpc-memcached
+            ${project.parent.version}
+            
+                
+                    com.googlecode.xmemcached
+                    xmemcached
+                
+            
+        
+        
+            com.alibaba
+            dubbo-rpc-redis
+            ${project.parent.version}
+            
+                
+                    redis.clients
+                    jedis
+                
+            
+        
         
             com.alibaba
             dubbo-rpc-rest
             ${project.parent.version}
+            
+                
+                    org.jboss.resteasy
+                    resteasy-jaxrs
+                
+                
+                    org.jboss.resteasy
+                    resteasy-client
+                
+                
+                    org.jboss.resteasy
+                    resteasy-netty
+                
+                
+                    org.jboss.resteasy
+                    resteasy-jdk-http
+                
+                
+                    org.jboss.resteasy
+                    resteasy-undertow
+                
+                
+                    io.undertow
+                    undertow-servlet
+                
+                
+                    io.undertow
+                    undertow-core
+                
+                
+                    org.jboss.resteasy
+                    resteasy-jackson-provider
+                
+                
+                    org.jboss.resteasy
+                    resteasy-jaxb-provider
+                
+                
+                    javax.validation
+                    validation-api
+                
+            
+        
+        
+            com.alibaba
+            dubbo-registry-default
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo-registry-multicast
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo-registry-zookeeper
+            ${project.parent.version}
+            
+                
+                    org.apache.zookeeper
+                    zookeeper
+                
+                
+                    com.github.sgroschupf
+                    zkclient
+                
+                
+                    com.netflix.curator
+                    curator-framework
+                
+            
+        
+        
+            com.alibaba
+            dubbo-registry-redis
+            ${project.parent.version}
+            
+                
+                    redis.clients
+                    jedis
+                
+            
+        
+        
+            com.alibaba
+            dubbo-monitor-default
+            ${project.parent.version}
         
-		
-			com.alibaba
-			dubbo-registry-default
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-registry-multicast
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-registry-zookeeper
-			${project.parent.version}
-			
-				
-					org.apache.zookeeper
-		    		zookeeper
-				
-				
-					com.github.sgroschupf
-					zkclient
-				
-				
-					com.netflix.curator
-					curator-framework
-				
-			
-		
-		
-			com.alibaba
-			dubbo-registry-redis
-			${project.parent.version}
-			
-				
-					redis.clients
-					jedis
-				
-			
-		
-		
-			com.alibaba
-			dubbo-monitor-default
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-container-spring
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-container-javaconfig
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-container-jetty
-			${project.parent.version}
-			
-				
-					org.mortbay.jetty
-					jetty
-				
-			
-		
-		
-			com.alibaba
-			dubbo-container-log4j
-			${project.parent.version}
-		
-		
-			com.alibaba
-			dubbo-container-logback
-			${project.parent.version}
-			
-				
-					ch.qos.logback
-					logback-classic
-				
-			
-		
-	
-	
-		
-			
-				maven-source-plugin
-				
-					
-						attach-sources
-						none
-					
-				
-			
-			
-				maven-javadoc-plugin
-				
+        
+            com.alibaba
+            dubbo-container-spring
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo-container-javaconfig
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo-container-jetty
+            ${project.parent.version}
+            
+                
+                    org.mortbay.jetty
+                    jetty
+                
+            
+        
+        
+            com.alibaba
+            dubbo-container-log4j
+            ${project.parent.version}
+        
+        
+            com.alibaba
+            dubbo-container-logback
+            ${project.parent.version}
+            
+                
+                    ch.qos.logback
+                    logback-classic
+                
+            
+        
+    
+    
+        
+            
+                maven-source-plugin
+                
+                    
+                        attach-sources
+                        none
+                    
+                
+            
+            
+                maven-javadoc-plugin
+                
                     
                         attach-javadoc
-						deploy
+                        deploy
                         
                             jar
                         
                     
                 
-				
-					public
-					UTF-8
-					UTF-8
-					UTF-8
-					com.alibaba.com.*
-					
-						http://docs.oracle.com/javase/6/docs/api
-					
-				
-			
-			
-				org.apache.maven.plugins
-				maven-shade-plugin
-				1.4
-				
-					
-						package
-						
-							shade
-						
-						
-							true
-							true
-							
-								
-								    com.alibaba:hessian-lite
-									com.alibaba:dubbo-common
-									com.alibaba:dubbo-remoting-api
-									com.alibaba:dubbo-remoting-netty
-									com.alibaba:dubbo-remoting-mina
-									com.alibaba:dubbo-remoting-grizzly
-									com.alibaba:dubbo-remoting-p2p
-									com.alibaba:dubbo-remoting-http
-									com.alibaba:dubbo-remoting-zookeeper
-									com.alibaba:dubbo-rpc-api
-									com.alibaba:dubbo-rpc-default
-									com.alibaba:dubbo-rpc-injvm
-									com.alibaba:dubbo-rpc-rmi
-									com.alibaba:dubbo-rpc-hessian
-									com.alibaba:dubbo-rpc-http
-									com.alibaba:dubbo-rpc-webservice
-									com.alibaba:dubbo-rpc-thrift
-									com.alibaba:dubbo-rpc-memcached
-									com.alibaba:dubbo-rpc-redis
-									com.alibaba:dubbo-rpc-rest
-									com.alibaba:dubbo-filter-validation
-									com.alibaba:dubbo-filter-cache
-									com.alibaba:dubbo-cluster
-									com.alibaba:dubbo-registry-api
-									com.alibaba:dubbo-registry-default
-									com.alibaba:dubbo-registry-multicast
-									com.alibaba:dubbo-registry-zookeeper
-									com.alibaba:dubbo-registry-redis
-									com.alibaba:dubbo-monitor-api
-									com.alibaba:dubbo-monitor-default
-									com.alibaba:dubbo-config-api
-									com.alibaba:dubbo-config-spring
-									com.alibaba:dubbo-container-api
-									com.alibaba:dubbo-container-spring
-									com.alibaba:dubbo-container-javaconfig
-									com.alibaba:dubbo-container-jetty
-									com.alibaba:dubbo-container-log4j
-									com.alibaba:dubbo-container-logback
-								
-							
-							
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.common.compiler.Compiler
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.common.extension.ExtensionFactory
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.common.status.StatusChecker
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.common.threadpool.ThreadPool
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.remoting.exchange.Exchanger
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.remoting.http.HttpBinder
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.remoting.p2p.Networker
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.remoting.telnet.TelnetHandler
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.remoting.zookeeper.ZookeeperTransporter
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.rpc.InvokerListener
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ExporterListener
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.LoadBalance
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Merger
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.RouterFactory
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.ConfiguratorFactory
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.container.Container
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.container.page.PageHandler
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.monitor.MonitorFactory
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.validation.Validation
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.cache.CacheFactory
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.common.store.DataStore
-								
-								
-									META-INF/dubbo/internal/com.alibaba.dubbo.common.logger.LoggerAdapter
-								
-							
-						
-					
-				
-			
-		
-	
+                
+                    public
+                    UTF-8
+                    UTF-8
+                    UTF-8
+                    com.alibaba.com.*
+                    
+                        http://docs.oracle.com/javase/6/docs/api
+                    
+                
+            
+            
+                org.apache.maven.plugins
+                maven-shade-plugin
+                1.4
+                
+                    
+                        package
+                        
+                            shade
+                        
+                        
+                            true
+                            true
+                            
+                                
+                                    com.alibaba:hessian-lite
+                                    com.alibaba:dubbo-common
+                                    com.alibaba:dubbo-remoting-api
+                                    com.alibaba:dubbo-remoting-netty
+                                    com.alibaba:dubbo-remoting-mina
+                                    com.alibaba:dubbo-remoting-grizzly
+                                    com.alibaba:dubbo-remoting-p2p
+                                    com.alibaba:dubbo-remoting-http
+                                    com.alibaba:dubbo-remoting-zookeeper
+                                    com.alibaba:dubbo-rpc-api
+                                    com.alibaba:dubbo-rpc-default
+                                    com.alibaba:dubbo-rpc-injvm
+                                    com.alibaba:dubbo-rpc-rmi
+                                    com.alibaba:dubbo-rpc-hessian
+                                    com.alibaba:dubbo-rpc-http
+                                    com.alibaba:dubbo-rpc-webservice
+                                    com.alibaba:dubbo-rpc-thrift
+                                    com.alibaba:dubbo-rpc-memcached
+                                    com.alibaba:dubbo-rpc-redis
+                                    com.alibaba:dubbo-rpc-rest
+                                    com.alibaba:dubbo-filter-validation
+                                    com.alibaba:dubbo-filter-cache
+                                    com.alibaba:dubbo-cluster
+                                    com.alibaba:dubbo-registry-api
+                                    com.alibaba:dubbo-registry-default
+                                    com.alibaba:dubbo-registry-multicast
+                                    com.alibaba:dubbo-registry-zookeeper
+                                    com.alibaba:dubbo-registry-redis
+                                    com.alibaba:dubbo-monitor-api
+                                    com.alibaba:dubbo-monitor-default
+                                    com.alibaba:dubbo-config-api
+                                    com.alibaba:dubbo-config-spring
+                                    com.alibaba:dubbo-container-api
+                                    com.alibaba:dubbo-container-spring
+                                    com.alibaba:dubbo-container-javaconfig
+                                    com.alibaba:dubbo-container-jetty
+                                    com.alibaba:dubbo-container-log4j
+                                    com.alibaba:dubbo-container-logback
+                                
+                            
+                            
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.common.compiler.Compiler
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.common.extension.ExtensionFactory
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.common.status.StatusChecker
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.common.threadpool.ThreadPool
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Dispatcher
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Transporter
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.remoting.exchange.Exchanger
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.remoting.http.HttpBinder
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.remoting.p2p.Networker
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.remoting.telnet.TelnetHandler
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.remoting.zookeeper.ZookeeperTransporter
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Filter
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.rpc.InvokerListener
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ExporterListener
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.rpc.ProxyFactory
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Cluster
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.LoadBalance
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.Merger
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.RouterFactory
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.ConfiguratorFactory
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.container.Container
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.container.page.PageHandler
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.monitor.MonitorFactory
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.validation.Validation
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.cache.CacheFactory
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.common.store.DataStore
+                                
+                                
+                                    META-INF/dubbo/internal/com.alibaba.dubbo.common.logger.LoggerAdapter
+                                
+                            
+                        
+                    
+                
+            
+        
+    
 
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 2ce11152ecbf..3d7ca8d7be0a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -389,6 +389,58 @@
                 tomcat-embed-logging-juli
                 ${tomcat_embed_version}
             
+
+            
+            
+                javax.ws.rs
+                javax.ws.rs-api
+                2.0
+            
+            
+                org.jboss.resteasy
+                resteasy-jaxrs
+                3.0.7.Final
+            
+            
+                org.jboss.resteasy
+                resteasy-client
+                3.0.7.Final
+            
+            
+                org.jboss.resteasy
+                resteasy-netty
+                3.0.7.Final
+            
+            
+                org.jboss.resteasy
+                resteasy-jdk-http
+                3.0.7.Final
+            
+            
+                org.jboss.resteasy
+                resteasy-jackson-provider
+                3.0.7.Final
+            
+            
+                org.jboss.resteasy
+                resteasy-jaxb-provider
+                3.0.7.Final
+            
+            
+                com.esotericsoftware.kryo
+                kryo
+                2.24.0
+            
+            
+                de.javakaffee
+                kryo-serializers
+                0.26
+            
+            
+                de.ruedigermoeller
+                fst
+                1.55
+            
 		
 	
 	

From c92d33338ff2626759a792176ddf1731a3f94319 Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Tue, 30 Dec 2014 16:03:15 +0800
Subject: [PATCH 168/200] refactor dependencies

---
 dubbo-admin/pom.xml                                        | 2 +-
 dubbo-demo/dubbo-demo-consumer/pom.xml                     | 7 +------
 dubbo-demo/dubbo-demo-provider/pom.xml                     | 6 +-----
 dubbo-maven/pom.xml                                        | 2 +-
 dubbo-remoting/dubbo-remoting-netty/pom.xml                | 2 +-
 dubbo-simple/dubbo-monitor-simple/pom.xml                  | 2 +-
 dubbo-test/dubbo-test-benchmark-client/pom.xml             | 2 +-
 dubbo-test/dubbo-test-benchmark-server/pom.xml             | 2 +-
 .../__rootArtifactId__-consumer/pom.xml                    | 2 +-
 .../__rootArtifactId__-provider/pom.xml                    | 2 +-
 .../dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml       | 2 +-
 .../dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml       | 2 +-
 pom.xml                                                    | 4 ++--
 13 files changed, 14 insertions(+), 23 deletions(-)

diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml
index 40738e793673..c463e3ee870c 100644
--- a/dubbo-admin/pom.xml
+++ b/dubbo-admin/pom.xml
@@ -46,7 +46,7 @@
 			javassist
 		
 		
-			org.jboss.netty
+			io.netty
 			netty
 		
 		
diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml
index 8d9600bf599c..a55a1e0b9a43 100644
--- a/dubbo-demo/dubbo-demo-consumer/pom.xml
+++ b/dubbo-demo/dubbo-demo-consumer/pom.xml
@@ -44,7 +44,7 @@
             javassist
         
         
-            org.jboss.netty
+            io.netty
             netty
         
         
@@ -136,11 +136,6 @@
             cache-api
         
 
-        
-            javax.ws.rs
-            javax.ws.rs-api
-        
-
         
             org.jboss.resteasy
             resteasy-jaxrs
diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml
index d06474c27c57..0613eee18f5e 100644
--- a/dubbo-demo/dubbo-demo-provider/pom.xml
+++ b/dubbo-demo/dubbo-demo-provider/pom.xml
@@ -44,7 +44,7 @@
             javassist
         
         
-            org.jboss.netty
+            io.netty
             netty
         
         
@@ -141,10 +141,6 @@
             javax.cache
             cache-api
         
-        
-            javax.ws.rs
-            javax.ws.rs-api
-        
 
         
             org.jboss.resteasy
diff --git a/dubbo-maven/pom.xml b/dubbo-maven/pom.xml
index bdc00ad29a59..68893fdf6c63 100644
--- a/dubbo-maven/pom.xml
+++ b/dubbo-maven/pom.xml
@@ -53,7 +53,7 @@
 			3.15.0-GA
 		
 		
-			org.jboss.netty
+			io.netty
 			netty
 			3.2.5.Final
 		
diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml
index adad78b783b2..b7674c762721 100644
--- a/dubbo-remoting/dubbo-remoting-netty/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml
@@ -35,7 +35,7 @@
 			${project.parent.version}
 		
 		
-			org.jboss.netty
+			io.netty
 			netty
 		
 	
diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml
index eebb21d03acb..a6ebd987da6d 100644
--- a/dubbo-simple/dubbo-monitor-simple/pom.xml
+++ b/dubbo-simple/dubbo-monitor-simple/pom.xml
@@ -43,7 +43,7 @@
 			javassist
 		
 		
-			org.jboss.netty
+			io.netty
 			netty
 		
 		
diff --git a/dubbo-test/dubbo-test-benchmark-client/pom.xml b/dubbo-test/dubbo-test-benchmark-client/pom.xml
index f467b9b5510a..8c99e00b971b 100644
--- a/dubbo-test/dubbo-test-benchmark-client/pom.xml
+++ b/dubbo-test/dubbo-test-benchmark-client/pom.xml
@@ -49,7 +49,7 @@
             javassist
         
         
-            org.jboss.netty
+            io.netty
             netty
         
         
diff --git a/dubbo-test/dubbo-test-benchmark-server/pom.xml b/dubbo-test/dubbo-test-benchmark-server/pom.xml
index 9caea44212a9..d261efce75e7 100644
--- a/dubbo-test/dubbo-test-benchmark-server/pom.xml
+++ b/dubbo-test/dubbo-test-benchmark-server/pom.xml
@@ -44,7 +44,7 @@
             javassist
         
         
-            org.jboss.netty
+            io.netty
             netty
         
         
diff --git a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml
index 2dc917ff2ec9..8a771dd82f28 100644
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml
@@ -42,7 +42,7 @@
             javassist
         
         
-            org.jboss.netty
+            io.netty
             netty
         
         
diff --git a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml
index 51842e825b04..3c40d8258686 100644
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml
@@ -42,7 +42,7 @@
             javassist
         
         
-            org.jboss.netty
+            io.netty
             netty
         
         
diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
index 59080ccd29d1..0a3679850c4e 100644
--- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
@@ -43,7 +43,7 @@
             javassist
         
         
-            org.jboss.netty
+            io.netty
             netty
         
         
diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
index 185c45195013..a3bfa1603b8b 100644
--- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
@@ -44,7 +44,7 @@
             javassist
         
         
-            org.jboss.netty
+            io.netty
             netty
         
         
diff --git a/pom.xml b/pom.xml
index 3d7ca8d7be0a..e2101838507a 100644
--- a/pom.xml
+++ b/pom.xml
@@ -86,7 +86,7 @@
 		
 		3.2.9.RELEASE
 		3.15.0-GA
-		3.2.5.Final
+		3.7.0.Final
 		1.1.7
 		2.1.4
 		4.2.1
@@ -174,7 +174,7 @@
 				${javassist_version}
 			
 			
-				org.jboss.netty
+				io.netty
 				netty
 				${netty_version}
 			

From d62022c53cd45196d9e65e4f187d66b3de3bfbf6 Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Wed, 31 Dec 2014 10:04:59 +0800
Subject: [PATCH 169/200] update docs

---
 README.md | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 104 insertions(+)

diff --git a/README.md b/README.md
index 9c32dd023623..9a68187866c0 100644
--- a/README.md
+++ b/README.md
@@ -71,6 +71,110 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p
     * 淇@Reference annotation涓璸rotocol璁剧疆涓嶈捣浣滅敤鐨刡ug锛堟矆鐞嗭級
     * 淇@Reference annotation鏀惧湪setter鏂规硶涓婂嵆浼氬嚭閿欑殑bug锛圖ylan锛
 
+## 渚濊禆
+
+浠巇ubbox-2.8.4寮濮嬶紝鎵鏈変緷璧栧簱鐨勪娇鐢ㄦ柟寮忓皢鍜宒ubbo鍘熸潵鐨勪竴鏍凤細鍗冲鏋滆浣跨敤REST銆並yro銆丗ST銆丣ackson绛夊姛鑳斤紝闇瑕佺敤鎴疯嚜琛屾墜宸ユ坊鍔犵浉鍏崇殑渚濊禆銆備緥濡傦細
+
+### REST椋庢牸杩滅▼璋冪敤
+
+```xml
+
+    org.jboss.resteasy
+    resteasy-jaxrs
+    3.0.7.Final
+
+
+    org.jboss.resteasy
+    resteasy-client
+    3.0.7.Final
+
+
+    javax.validation
+    validation-api
+    1.0.0.GA
+
+
+
+
+    org.jboss.resteasy
+    resteasy-jackson-provider
+    3.0.7.Final
+
+
+
+
+    org.jboss.resteasy
+    resteasy-jaxb-provider
+    3.0.7.Final
+
+
+
+
+    org.jboss.resteasy
+    resteasy-netty
+    3.0.7.Final
+
+
+
+
+    org.jboss.resteasy
+    resteasy-jdk-http
+    3.0.7.Final
+
+
+
+
+    org.apache.tomcat.embed
+    tomcat-embed-core
+    8.0.11
+
+
+    org.apache.tomcat.embed
+    tomcat-embed-logging-juli
+    8.0.11
+
+```
+
+### Kyro搴忓垪鍖
+
+```xml
+
+    com.esotericsoftware.kryo
+    kryo
+    2.24.0
+
+
+    de.javakaffee
+    kryo-serializers
+    0.26
+
+```
+
+### FST搴忓垪鍖
+
+```xml
+
+    de.ruedigermoeller
+    fst
+    1.55
+
+```
+
+### Jackson搴忓垪鍖
+
+```xml
+
+    com.fasterxml.jackson.core
+    jackson-core
+    2.3.3
+
+
+    com.fasterxml.jackson.core
+    jackson-databind
+    2.3.3
+
+```
+   
 ## FAQ锛堟殏瀛橈級
 
 ### Dubbox闇瑕佷粈涔堢増鏈殑JDK锛

From ff85f993814d764015fbbb0a84d4ee5bdca39d1b Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Mon, 5 Jan 2015 14:42:00 +0800
Subject: [PATCH 170/200] enable netty cleanup

---
 .../alibaba/dubbo/remoting/transport/netty/NettyClient.java  | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java
index 7825f88183fb..de28e5101853 100644
--- a/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java
+++ b/dubbo-remoting/dubbo-remoting-netty/src/main/java/com/alibaba/dubbo/remoting/transport/netty/NettyClient.java
@@ -147,11 +147,12 @@ protected void doDisConnect() throws Throwable {
     
     @Override
     protected void doClose() throws Throwable {
-        /*try {
+        // modified by lishen
+        try {
             bootstrap.releaseExternalResources();
         } catch (Throwable t) {
             logger.warn(t.getMessage());
-        }*/
+        }
     }
 
     @Override

From 00a66c0adaf6540e6326e8e78ea3b46dae4dbf61 Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Mon, 5 Jan 2015 14:51:12 +0800
Subject: [PATCH 171/200] add support for aop proxy in rest service

---
 .../java/com/alibaba/dubbo/config/ServiceConfig.java   | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java
index 8cb59a7f0fc6..0b7a35e589c0 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java
@@ -48,6 +48,7 @@
 import com.alibaba.dubbo.rpc.protocol.ServiceImplHolder;
 import com.alibaba.dubbo.rpc.service.GenericService;
 import com.alibaba.dubbo.rpc.support.ProtocolUtils;
+import org.springframework.aop.support.AopUtils;
 
 /**
  * ServiceConfig
@@ -508,7 +509,14 @@ private void exportLocal(URL url) {
                     .setProtocol(Constants.LOCAL_PROTOCOL)
                     .setHost(NetUtils.LOCALHOST)
                     .setPort(0);
-            ServiceImplHolder.getInstance().pushServiceImpl(ref);
+
+            // modified by lishen
+            Object impl = ref;
+            if (AopUtils.isAopProxy(ref.getClass()) || AopUtils.isCglibProxy(ref.getClass()) || AopUtils.isJdkDynamicProxy(ref.getClass())) {
+                impl = AopUtils.getTargetClass(ref);
+            }
+            ServiceImplHolder.getInstance().pushServiceImpl(impl);
+
             Exporter exporter = protocol.export(
                     proxyFactory.getInvoker(ref, (Class) interfaceClass, local));
             exporters.add(exporter);

From 506f088572dc318c8bd87cce7dd3b042d8726aa4 Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Mon, 5 Jan 2015 17:50:54 +0800
Subject: [PATCH 172/200] fix bug for proxy support

---
 .../alibaba/dubbo/config/ServiceConfig.java   | 10 +++----
 .../dubbo/config/spring/AnnotationBean.java   |  2 +-
 .../rpc/protocol/ServiceClassHolder.java      | 30 +++++++++++++++++++
 .../dubbo/rpc/protocol/ServiceImplHolder.java | 30 -------------------
 .../dubbo/rpc/protocol/rest/RestProtocol.java |  4 +--
 5 files changed, 38 insertions(+), 38 deletions(-)
 create mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceClassHolder.java
 delete mode 100644 dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceImplHolder.java

diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java
index 0b7a35e589c0..cf8e28a08376 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java
@@ -45,7 +45,7 @@
 import com.alibaba.dubbo.rpc.Protocol;
 import com.alibaba.dubbo.rpc.ProxyFactory;
 import com.alibaba.dubbo.rpc.cluster.ConfiguratorFactory;
-import com.alibaba.dubbo.rpc.protocol.ServiceImplHolder;
+import com.alibaba.dubbo.rpc.protocol.ServiceClassHolder;
 import com.alibaba.dubbo.rpc.service.GenericService;
 import com.alibaba.dubbo.rpc.support.ProtocolUtils;
 import org.springframework.aop.support.AopUtils;
@@ -511,11 +511,11 @@ private void exportLocal(URL url) {
                     .setPort(0);
 
             // modified by lishen
-            Object impl = ref;
-            if (AopUtils.isAopProxy(ref.getClass()) || AopUtils.isCglibProxy(ref.getClass()) || AopUtils.isJdkDynamicProxy(ref.getClass())) {
-                impl = AopUtils.getTargetClass(ref);
+            Class clazz = ref.getClass();
+            if (AopUtils.isAopProxy(ref)) {
+                clazz = AopUtils.getTargetClass(ref);
             }
-            ServiceImplHolder.getInstance().pushServiceImpl(impl);
+            ServiceClassHolder.getInstance().pushServiceClass(clazz);
 
             Exporter exporter = protocol.export(
                     proxyFactory.getInvoker(ref, (Class) interfaceClass, local));
diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java
index 04afefe348c8..8f54baacee88 100644
--- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java
+++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/AnnotationBean.java
@@ -335,7 +335,7 @@ private boolean isMatchPackage(Object bean) {
     }
 
     private boolean isProxyBean(Object bean) {
-        return AopUtils.isAopProxy(bean) || AopUtils.isCglibProxy(bean) || AopUtils.isJdkDynamicProxy(bean);
+        return AopUtils.isAopProxy(bean);
     }
 
 }
diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceClassHolder.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceClassHolder.java
new file mode 100644
index 000000000000..ac875a31e545
--- /dev/null
+++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceClassHolder.java
@@ -0,0 +1,30 @@
+package com.alibaba.dubbo.rpc.protocol;
+
+/**
+ * TODO this is just a workround for rest protocol, and now we just ensure it works in the most common dubbo usages
+ *
+ * @author lishen
+ */
+public class ServiceClassHolder {
+
+    private static final ServiceClassHolder INSTANCE = new ServiceClassHolder();
+
+    private final ThreadLocal holder  = new ThreadLocal();
+
+    public static ServiceClassHolder getInstance() {
+        return INSTANCE;
+    }
+
+    private ServiceClassHolder() {
+    }
+
+    public Class popServiceClass() {
+        Class clazz = holder.get();
+        holder.remove();
+        return clazz;
+    }
+
+    public void pushServiceClass(Class clazz) {
+        holder.set(clazz);
+    }
+}
diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceImplHolder.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceImplHolder.java
deleted file mode 100644
index 9371d91de264..000000000000
--- a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/protocol/ServiceImplHolder.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.alibaba.dubbo.rpc.protocol;
-
-/**
- * TODO this is just a workround for rest protocol, and now we just ensure it works in the most common dubbo usages
- *
- * @author lishen
- */
-public class ServiceImplHolder {
-
-    private static final ServiceImplHolder INSTANCE = new ServiceImplHolder();
-
-    private final ThreadLocal holder  = new ThreadLocal();
-
-    public static ServiceImplHolder getInstance() {
-        return INSTANCE;
-    }
-
-    private ServiceImplHolder() {
-    }
-
-    public Object popServiceImpl() {
-        Object impl = holder.get();
-        holder.remove();
-        return impl;
-    }
-
-    public void pushServiceImpl(Object impl) {
-        holder.set(impl);
-    }
-}
diff --git a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java
index bfe212505878..9265c9ff4be8 100644
--- a/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java
+++ b/dubbo-rpc/dubbo-rpc-rest/src/main/java/com/alibaba/dubbo/rpc/protocol/rest/RestProtocol.java
@@ -23,7 +23,7 @@
 import com.alibaba.dubbo.remoting.http.servlet.ServletManager;
 import com.alibaba.dubbo.rpc.RpcException;
 import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol;
-import com.alibaba.dubbo.rpc.protocol.ServiceImplHolder;
+import com.alibaba.dubbo.rpc.protocol.ServiceClassHolder;
 import org.apache.http.HeaderElement;
 import org.apache.http.HeaderElementIterator;
 import org.apache.http.HttpResponse;
@@ -82,7 +82,7 @@ public int getDefaultPort() {
 
     protected  Runnable doExport(T impl, Class type, URL url) throws RpcException {
         String addr = url.getIp() + ":" + url.getPort();
-        Class implClass = ServiceImplHolder.getInstance().popServiceImpl().getClass();
+        Class implClass = ServiceClassHolder.getInstance().popServiceClass();
         RestServer server = servers.get(addr);
         if (server == null) {
             server = serverFactory.createServer(url.getParameter(Constants.SERVER_KEY, "jetty"));

From 20ba08fe9557213f5b302735589fea57da23b133 Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Tue, 6 Jan 2015 16:10:50 +0800
Subject: [PATCH 173/200] upgrade zk version

---
 pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/pom.xml b/pom.xml
index e2101838507a..c07b100f4569 100644
--- a/pom.xml
+++ b/pom.xml
@@ -95,7 +95,7 @@
 		1.1.39
 		3.1
 		0.8
-		3.3.3
+		3.4.6
 		0.1
 		2.5.0
 		2.1.0

From c3f58fabf12948ff8934b1b28200bb615377bc61 Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Wed, 7 Jan 2015 11:33:14 +0800
Subject: [PATCH 174/200] update versions

---
 dubbo-admin/pom.xml                                   |  2 +-
 dubbo-cluster/pom.xml                                 |  2 +-
 dubbo-common/pom.xml                                  |  2 +-
 dubbo-config/dubbo-config-api/pom.xml                 |  2 +-
 .../java/com/alibaba/dubbo/config/ServiceConfig.java  | 11 +++++------
 dubbo-config/dubbo-config-spring/pom.xml              |  2 +-
 .../com/alibaba/dubbo/config/spring/ServiceBean.java  |  9 +++++++++
 dubbo-config/pom.xml                                  |  2 +-
 dubbo-container/dubbo-container-api/pom.xml           |  2 +-
 dubbo-container/dubbo-container-javaconfig/pom.xml    |  2 +-
 dubbo-container/dubbo-container-jetty/pom.xml         |  2 +-
 dubbo-container/dubbo-container-log4j/pom.xml         |  2 +-
 dubbo-container/dubbo-container-logback/pom.xml       |  2 +-
 dubbo-container/dubbo-container-spring/pom.xml        |  2 +-
 dubbo-container/pom.xml                               |  2 +-
 dubbo-demo/dubbo-demo-api/pom.xml                     |  2 +-
 dubbo-demo/dubbo-demo-consumer/pom.xml                |  2 +-
 dubbo-demo/dubbo-demo-provider/pom.xml                |  2 +-
 dubbo-demo/pom.xml                                    |  2 +-
 dubbo-filter/dubbo-filter-cache/pom.xml               |  2 +-
 dubbo-filter/dubbo-filter-validation/pom.xml          |  2 +-
 dubbo-filter/pom.xml                                  |  2 +-
 dubbo-monitor/dubbo-monitor-api/pom.xml               |  2 +-
 dubbo-monitor/dubbo-monitor-default/pom.xml           |  2 +-
 dubbo-monitor/pom.xml                                 |  2 +-
 dubbo-registry/dubbo-registry-api/pom.xml             |  2 +-
 dubbo-registry/dubbo-registry-default/pom.xml         |  2 +-
 dubbo-registry/dubbo-registry-multicast/pom.xml       |  2 +-
 dubbo-registry/dubbo-registry-redis/pom.xml           |  2 +-
 dubbo-registry/dubbo-registry-zookeeper/pom.xml       |  2 +-
 dubbo-registry/pom.xml                                |  2 +-
 dubbo-remoting/dubbo-remoting-api/pom.xml             |  2 +-
 dubbo-remoting/dubbo-remoting-grizzly/pom.xml         |  2 +-
 dubbo-remoting/dubbo-remoting-http/pom.xml            |  2 +-
 dubbo-remoting/dubbo-remoting-mina/pom.xml            |  2 +-
 dubbo-remoting/dubbo-remoting-netty/pom.xml           |  2 +-
 dubbo-remoting/dubbo-remoting-p2p/pom.xml             |  2 +-
 dubbo-remoting/dubbo-remoting-zookeeper/pom.xml       |  2 +-
 dubbo-remoting/pom.xml                                |  2 +-
 dubbo-rpc/dubbo-rpc-api/pom.xml                       |  2 +-
 dubbo-rpc/dubbo-rpc-default/pom.xml                   |  2 +-
 dubbo-rpc/dubbo-rpc-hessian/pom.xml                   |  2 +-
 dubbo-rpc/dubbo-rpc-http/pom.xml                      |  2 +-
 dubbo-rpc/dubbo-rpc-injvm/pom.xml                     |  2 +-
 dubbo-rpc/dubbo-rpc-memcached/pom.xml                 |  2 +-
 dubbo-rpc/dubbo-rpc-redis/pom.xml                     |  2 +-
 dubbo-rpc/dubbo-rpc-rest/pom.xml                      |  2 +-
 dubbo-rpc/dubbo-rpc-rmi/pom.xml                       |  2 +-
 dubbo-rpc/dubbo-rpc-thrift/pom.xml                    |  2 +-
 dubbo-rpc/dubbo-rpc-webservice/pom.xml                |  2 +-
 dubbo-rpc/pom.xml                                     |  2 +-
 dubbo-simple/dubbo-monitor-simple/pom.xml             |  2 +-
 dubbo-simple/dubbo-registry-simple/pom.xml            |  2 +-
 dubbo-simple/pom.xml                                  |  2 +-
 dubbo-test/dubbo-test-benchmark-api/pom.xml           |  2 +-
 dubbo-test/dubbo-test-benchmark-client/pom.xml        |  2 +-
 dubbo-test/dubbo-test-benchmark-server/pom.xml        |  2 +-
 dubbo-test/dubbo-test-benchmark/pom.xml               |  2 +-
 dubbo-test/dubbo-test-compatibility/pom.xml           |  2 +-
 dubbo-test/dubbo-test-examples/pom.xml                |  2 +-
 dubbo-test/dubbo-test-integration/pom.xml             |  2 +-
 dubbo-test/pom.xml                                    |  2 +-
 dubbo-tool/dubbo-demo-lite-archetype/pom.xml          |  2 +-
 .../src/main/resources/archetype-resources/pom.xml    |  4 ++--
 .../dubbo-demo-lite/dubbo-demo-lite-api/pom.xml       |  2 +-
 .../dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml  |  2 +-
 .../dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml  |  2 +-
 dubbo-tool/dubbo-demo-lite/pom.xml                    |  4 ++--
 dubbo/pom.xml                                         |  2 +-
 hessian-lite/pom.xml                                  |  2 +-
 pom.xml                                               |  2 +-
 71 files changed, 85 insertions(+), 77 deletions(-)

diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml
index c463e3ee870c..ec2a30be84ad 100644
--- a/dubbo-admin/pom.xml
+++ b/dubbo-admin/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-admin
 	war
diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml
index b3f6818440b5..ec6af560cb05 100644
--- a/dubbo-cluster/pom.xml
+++ b/dubbo-cluster/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-cluster
 	jar
diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml
index 668a692ab0a9..0d5e9f761de7 100644
--- a/dubbo-common/pom.xml
+++ b/dubbo-common/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-parent
-        2.8.3
+        2.8.4
     
     dubbo-common
     jar
diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml
index 95180e8bb5ad..d1f6a82c9c8c 100644
--- a/dubbo-config/dubbo-config-api/pom.xml
+++ b/dubbo-config/dubbo-config-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-config
-		2.8.3
+		2.8.4
 	
 	dubbo-config-api
 	jar
diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java
index cf8e28a08376..aab669d41770 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/ServiceConfig.java
@@ -48,7 +48,6 @@
 import com.alibaba.dubbo.rpc.protocol.ServiceClassHolder;
 import com.alibaba.dubbo.rpc.service.GenericService;
 import com.alibaba.dubbo.rpc.support.ProtocolUtils;
-import org.springframework.aop.support.AopUtils;
 
 /**
  * ServiceConfig
@@ -511,11 +510,7 @@ private void exportLocal(URL url) {
                     .setPort(0);
 
             // modified by lishen
-            Class clazz = ref.getClass();
-            if (AopUtils.isAopProxy(ref)) {
-                clazz = AopUtils.getTargetClass(ref);
-            }
-            ServiceClassHolder.getInstance().pushServiceClass(clazz);
+            ServiceClassHolder.getInstance().pushServiceClass(getServiceClass(ref));
 
             Exporter exporter = protocol.export(
                     proxyFactory.getInvoker(ref, (Class) interfaceClass, local));
@@ -524,6 +519,10 @@ private void exportLocal(URL url) {
         }
     }
 
+    protected Class getServiceClass(T ref) {
+        return ref.getClass();
+    }
+
     private void checkDefault() {
         if (provider == null) {
             provider = new ProviderConfig();
diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml
index c4d2a8771e41..9732dff29d63 100644
--- a/dubbo-config/dubbo-config-spring/pom.xml
+++ b/dubbo-config/dubbo-config-spring/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-config
-		2.8.3
+		2.8.4
 	
 	dubbo-config-spring
 	jar
diff --git a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java
index 0f3ff57196be..cc9c2a0776a3 100644
--- a/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java
+++ b/dubbo-config/dubbo-config-spring/src/main/java/com/alibaba/dubbo/config/spring/ServiceBean.java
@@ -20,6 +20,7 @@
 import java.util.List;
 import java.util.Map;
 
+import org.springframework.aop.support.AopUtils;
 import org.springframework.beans.factory.BeanFactoryUtils;
 import org.springframework.beans.factory.BeanNameAware;
 import org.springframework.beans.factory.DisposableBean;
@@ -255,4 +256,12 @@ public void destroy() throws Exception {
         unexport();
     }
 
+    // added by lishen
+    @Override
+    protected Class getServiceClass(T ref) {
+        if (AopUtils.isAopProxy(ref)) {
+            return AopUtils.getTargetClass(ref);
+        }
+        return super.getServiceClass(ref);
+    }
 }
\ No newline at end of file
diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml
index f2bbcbf5d69e..925195632b1d 100644
--- a/dubbo-config/pom.xml
+++ b/dubbo-config/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-config
 	pom
diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml
index 17587930fb68..3cb4bda94c49 100644
--- a/dubbo-container/dubbo-container-api/pom.xml
+++ b/dubbo-container/dubbo-container-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-container
-		2.8.3
+		2.8.4
 	
 	dubbo-container-api
 	jar
diff --git a/dubbo-container/dubbo-container-javaconfig/pom.xml b/dubbo-container/dubbo-container-javaconfig/pom.xml
index bdc600557fe9..3cc3985b60e1 100644
--- a/dubbo-container/dubbo-container-javaconfig/pom.xml
+++ b/dubbo-container/dubbo-container-javaconfig/pom.xml
@@ -19,7 +19,7 @@
   
     com.alibaba
     dubbo-container
-    2.8.3
+    2.8.4
   
   dubbo-container-javaconfig
   jar
diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml
index e130f94de31e..3fd180fb91a0 100644
--- a/dubbo-container/dubbo-container-jetty/pom.xml
+++ b/dubbo-container/dubbo-container-jetty/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-container
-		2.8.3
+		2.8.4
 	
 	dubbo-container-jetty
 	jar
diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml
index 42b1d97a41cf..be4637f32639 100644
--- a/dubbo-container/dubbo-container-log4j/pom.xml
+++ b/dubbo-container/dubbo-container-log4j/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-container
-		2.8.3
+		2.8.4
 	
 	dubbo-container-log4j
 	jar
diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml
index b74d2fe49ac1..a123294937e2 100644
--- a/dubbo-container/dubbo-container-logback/pom.xml
+++ b/dubbo-container/dubbo-container-logback/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-container
-		2.8.3
+		2.8.4
 	
 	dubbo-container-logback
 	jar
diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml
index f6dfd0bcf2df..9564561a899e 100644
--- a/dubbo-container/dubbo-container-spring/pom.xml
+++ b/dubbo-container/dubbo-container-spring/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-container
-		2.8.3
+		2.8.4
 	
 	dubbo-container-spring
 	jar
diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml
index 0a11e727390b..b277ac007626 100644
--- a/dubbo-container/pom.xml
+++ b/dubbo-container/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-container
 	pom
diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml
index 1cd8b001f90a..a311efe313b5 100644
--- a/dubbo-demo/dubbo-demo-api/pom.xml
+++ b/dubbo-demo/dubbo-demo-api/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-demo
-        2.8.3
+        2.8.4
     
     dubbo-demo-api
     jar
diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml
index a55a1e0b9a43..3e2427967bb3 100644
--- a/dubbo-demo/dubbo-demo-consumer/pom.xml
+++ b/dubbo-demo/dubbo-demo-consumer/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-demo
-        2.8.3
+        2.8.4
     
     dubbo-demo-consumer
     jar
diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml
index 0613eee18f5e..1d6192f7aec7 100644
--- a/dubbo-demo/dubbo-demo-provider/pom.xml
+++ b/dubbo-demo/dubbo-demo-provider/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-demo
-        2.8.3
+        2.8.4
     
     dubbo-demo-provider
     war
diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml
index 05e9a671b044..4d77e14ec9ab 100644
--- a/dubbo-demo/pom.xml
+++ b/dubbo-demo/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-demo
 	pom
diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml
index 9e5ee4e974a1..8431bef623d6 100644
--- a/dubbo-filter/dubbo-filter-cache/pom.xml
+++ b/dubbo-filter/dubbo-filter-cache/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-filter
-		2.8.3
+		2.8.4
 	
 	dubbo-filter-cache
 	jar
diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml
index 99555f86d10a..d3d9cc121344 100644
--- a/dubbo-filter/dubbo-filter-validation/pom.xml
+++ b/dubbo-filter/dubbo-filter-validation/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-filter
-		2.8.3
+		2.8.4
 	
 	dubbo-filter-validation
 	jar
diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml
index b5cb71737550..86e2ef12fbf7 100644
--- a/dubbo-filter/pom.xml
+++ b/dubbo-filter/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-filter
 	pom
diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml
index 2aa23613698c..e654f038a54f 100644
--- a/dubbo-monitor/dubbo-monitor-api/pom.xml
+++ b/dubbo-monitor/dubbo-monitor-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-monitor
-		2.8.3
+		2.8.4
 	
 	dubbo-monitor-api
 	jar
diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml
index fe93f4ae359b..957fda3e4228 100644
--- a/dubbo-monitor/dubbo-monitor-default/pom.xml
+++ b/dubbo-monitor/dubbo-monitor-default/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-monitor
-		2.8.3
+		2.8.4
 	
 	dubbo-monitor-default
 	jar
diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml
index 9181394e4f46..5061c3f56065 100644
--- a/dubbo-monitor/pom.xml
+++ b/dubbo-monitor/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-monitor
 	pom
diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml
index e8ddb66de429..25572a8b656d 100644
--- a/dubbo-registry/dubbo-registry-api/pom.xml
+++ b/dubbo-registry/dubbo-registry-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-registry
-		2.8.3
+		2.8.4
 	
 	dubbo-registry-api
 	jar
diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml
index 558672125188..2ee2515bed91 100644
--- a/dubbo-registry/dubbo-registry-default/pom.xml
+++ b/dubbo-registry/dubbo-registry-default/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-registry
-		2.8.3
+		2.8.4
 	
 	dubbo-registry-default
 	jar
diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml
index 9eb3763e7a07..478d4fb67b7a 100644
--- a/dubbo-registry/dubbo-registry-multicast/pom.xml
+++ b/dubbo-registry/dubbo-registry-multicast/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-registry
-		2.8.3
+		2.8.4
 	
 	dubbo-registry-multicast
 	jar
diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml
index fcd0ed3c35c4..10c9fa26b499 100644
--- a/dubbo-registry/dubbo-registry-redis/pom.xml
+++ b/dubbo-registry/dubbo-registry-redis/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-registry
-		2.8.3
+		2.8.4
 	
 	dubbo-registry-redis
 	jar
diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml
index d843b00c89ac..774d0b73bda7 100644
--- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml
+++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-registry
-		2.8.3
+		2.8.4
 	
 	dubbo-registry-zookeeper
 	jar
diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml
index b0b74ea2bc5f..4dedf4fc732e 100644
--- a/dubbo-registry/pom.xml
+++ b/dubbo-registry/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-registry
 	pom
diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml
index 6b4474d92a52..c8fe1460033c 100644
--- a/dubbo-remoting/dubbo-remoting-api/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.3
+		2.8.4
 	
 	dubbo-remoting-api
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml
index 744f47c4764d..ce4b65200722 100644
--- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.3
+		2.8.4
 	
 	dubbo-remoting-grizzly
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml
index d5e1f4af8cd1..c08a31deb77c 100644
--- a/dubbo-remoting/dubbo-remoting-http/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-http/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.3
+		2.8.4
 	
 	dubbo-remoting-http
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml
index b0a1198630d4..b3e36966f1a7 100644
--- a/dubbo-remoting/dubbo-remoting-mina/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.3
+		2.8.4
 	
 	dubbo-remoting-mina
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml
index b7674c762721..afe4f789749b 100644
--- a/dubbo-remoting/dubbo-remoting-netty/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.3
+		2.8.4
 	
 	dubbo-remoting-netty
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml
index 604ca605101e..0dce25f736f3 100644
--- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.3
+		2.8.4
 	
 	dubbo-remoting-p2p
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml
index d85e71039806..47520dae0d85 100644
--- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.3
+		2.8.4
 	
 	dubbo-remoting-zookeeper
 	jar
diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml
index a8751dcfe9e5..0c7faf42bbc0 100644
--- a/dubbo-remoting/pom.xml
+++ b/dubbo-remoting/pom.xml
@@ -18,7 +18,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-remoting
 	pom
diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml
index 49bd1f6e023d..e713642d38e9 100644
--- a/dubbo-rpc/dubbo-rpc-api/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc-api
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml
index 7c2a16d35716..a31250d37dbf 100644
--- a/dubbo-rpc/dubbo-rpc-default/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-default/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc-default
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml
index 4010b9b3c1bb..bf5e50cb4c61 100644
--- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc-hessian
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml
index c74dba205558..a2ad7c134f39 100644
--- a/dubbo-rpc/dubbo-rpc-http/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-http/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc-http
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml
index 03bd369d8533..dcdda8d53454 100644
--- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc-injvm
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml
index d99c29f63e67..6a2af14c3c6b 100644
--- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc-memcached
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml
index f3fe7af03232..9e39b9fa31f7 100644
--- a/dubbo-rpc/dubbo-rpc-redis/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc-redis
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml
index c4282b5f9b74..11edf84ca91d 100644
--- a/dubbo-rpc/dubbo-rpc-rest/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc-rest
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml
index fd60d58701cf..84b76b9a0593 100644
--- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc-rmi
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml
index c02426ee2d3f..3b8500aa105c 100644
--- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-thrift/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc-thrift
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml
index dfe06dd391eb..069d285b432d 100644
--- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc-webservice
 	jar
diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml
index 25b076c2239c..4dd07112ac0f 100644
--- a/dubbo-rpc/pom.xml
+++ b/dubbo-rpc/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-rpc
 	pom
diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml
index a6ebd987da6d..4068dfc52faf 100644
--- a/dubbo-simple/dubbo-monitor-simple/pom.xml
+++ b/dubbo-simple/dubbo-monitor-simple/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-simple
-		2.8.3
+		2.8.4
 	
 	dubbo-monitor-simple
 	jar
diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml
index 9a66eb905355..6c1912bee661 100644
--- a/dubbo-simple/dubbo-registry-simple/pom.xml
+++ b/dubbo-simple/dubbo-registry-simple/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-simple
-		2.8.3
+		2.8.4
 	
 	dubbo-registry-simple
 	jar
diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml
index f66c7f497d54..5bb270f01792 100644
--- a/dubbo-simple/pom.xml
+++ b/dubbo-simple/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-simple
 	pom
diff --git a/dubbo-test/dubbo-test-benchmark-api/pom.xml b/dubbo-test/dubbo-test-benchmark-api/pom.xml
index 03287eadbbad..79f9a30036c2 100644
--- a/dubbo-test/dubbo-test-benchmark-api/pom.xml
+++ b/dubbo-test/dubbo-test-benchmark-api/pom.xml
@@ -4,7 +4,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.3
+		2.8.4
 	
 	dubbo-test-benchmark-api
 	jar
diff --git a/dubbo-test/dubbo-test-benchmark-client/pom.xml b/dubbo-test/dubbo-test-benchmark-client/pom.xml
index 8c99e00b971b..09aded711066 100644
--- a/dubbo-test/dubbo-test-benchmark-client/pom.xml
+++ b/dubbo-test/dubbo-test-benchmark-client/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.3
+		2.8.4
 	
 	dubbo-test-benchmark-client
 	jar
diff --git a/dubbo-test/dubbo-test-benchmark-server/pom.xml b/dubbo-test/dubbo-test-benchmark-server/pom.xml
index d261efce75e7..9a97c7df23f4 100644
--- a/dubbo-test/dubbo-test-benchmark-server/pom.xml
+++ b/dubbo-test/dubbo-test-benchmark-server/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.3
+		2.8.4
 	
 	dubbo-test-benchmark-server
 	jar
diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml
index b9338265cfb5..2593c9e50547 100644
--- a/dubbo-test/dubbo-test-benchmark/pom.xml
+++ b/dubbo-test/dubbo-test-benchmark/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.3
+		2.8.4
 	
 	dubbo-test-benchmark
 	jar
diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml
index cd005173b762..d02370e64cc7 100644
--- a/dubbo-test/dubbo-test-compatibility/pom.xml
+++ b/dubbo-test/dubbo-test-compatibility/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.3
+		2.8.4
 	
 	dubbo-test-compatibility
 	jar
diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml
index 801876019e36..43b4b699291e 100644
--- a/dubbo-test/dubbo-test-examples/pom.xml
+++ b/dubbo-test/dubbo-test-examples/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.3
+		2.8.4
 	
 	dubbo-test-examples
 	jar
diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml
index 5a5065a08b2a..cbf43a6836a1 100644
--- a/dubbo-test/dubbo-test-integration/pom.xml
+++ b/dubbo-test/dubbo-test-integration/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.3
+		2.8.4
 	
 	dubbo-test-integration
 	jar
diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml
index c3f79938f685..8ccfec26d319 100644
--- a/dubbo-test/pom.xml
+++ b/dubbo-test/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-test
 	pom
diff --git a/dubbo-tool/dubbo-demo-lite-archetype/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/pom.xml
index 34a79cffd2c9..844d9844dbd3 100644
--- a/dubbo-tool/dubbo-demo-lite-archetype/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite-archetype/pom.xml
@@ -4,7 +4,7 @@
 
   com.alibaba
   dubbo-demo-lite-archetype
-  2.8.3
+  2.8.4
   maven-archetype
 
   dubbo-demo-lite-archetype
diff --git a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml
index c1424a7766c8..561a683e509e 100644
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml
@@ -18,7 +18,7 @@
     
         com.alibaba
         dubbo-parent
-        2.8.3
+        2.8.4
     
     ${artifactId}
     ${groupId}
@@ -35,7 +35,7 @@
             
                 com.alibaba
                 dubbo
-                2.8.3
+                2.8.4
             
         
     
diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml
index d68347cbdeb1..fb06b6404790 100644
--- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-demo-lite
-		2.8.3
+		2.8.4
 	
 	dubbo-demo-lite-api
 	jar
diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
index 0a3679850c4e..e59c2df0903c 100644
--- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-demo-lite
-        2.8.3
+        2.8.4
     
     dubbo-demo-lite-consumer
     jar
diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
index a3bfa1603b8b..ab2cead41cd3 100644
--- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-demo-lite
-        2.8.3
+        2.8.4
     
 	dubbo-demo-lite-provider
 	war
diff --git a/dubbo-tool/dubbo-demo-lite/pom.xml b/dubbo-tool/dubbo-demo-lite/pom.xml
index 4dd1940fbb45..b43142ae691e 100644
--- a/dubbo-tool/dubbo-demo-lite/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.3
+		2.8.4
 	
 	dubbo-demo-lite
 	pom
@@ -39,7 +39,7 @@
             
                 com.alibaba
                 dubbo
-                2.8.3
+                2.8.4
             
         
     
diff --git a/dubbo/pom.xml b/dubbo/pom.xml
index cbac4736c37f..447be40bdd40 100644
--- a/dubbo/pom.xml
+++ b/dubbo/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-parent
-        2.8.3
+        2.8.4
     
     dubbo
     jar
diff --git a/hessian-lite/pom.xml b/hessian-lite/pom.xml
index 535e8de68adf..c377884a45e9 100644
--- a/hessian-lite/pom.xml
+++ b/hessian-lite/pom.xml
@@ -6,7 +6,7 @@
     
         com.alibaba
         dubbo-parent
-        2.8.3
+        2.8.4
     
     hessian-lite
     jar
diff --git a/pom.xml b/pom.xml
index c07b100f4569..92096e7237dc 100644
--- a/pom.xml
+++ b/pom.xml
@@ -20,7 +20,7 @@
 		2.0  -->
 	com.alibaba
 	dubbo-parent
-	2.8.3
+	2.8.4
 	pom
 	${project.artifactId}
 	The parent project of dubbo

From c213cc262b1290cf7719d9dc8ebcc992bbb4ea4a Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Wed, 7 Jan 2015 14:19:55 +0800
Subject: [PATCH 175/200] update versions

---
 dubbo-admin/pom.xml                                           | 2 +-
 dubbo-cluster/pom.xml                                         | 2 +-
 dubbo-common/pom.xml                                          | 2 +-
 dubbo-config/dubbo-config-api/pom.xml                         | 2 +-
 dubbo-config/dubbo-config-spring/pom.xml                      | 2 +-
 dubbo-config/pom.xml                                          | 2 +-
 dubbo-container/dubbo-container-api/pom.xml                   | 2 +-
 dubbo-container/dubbo-container-javaconfig/pom.xml            | 2 +-
 dubbo-container/dubbo-container-jetty/pom.xml                 | 2 +-
 dubbo-container/dubbo-container-log4j/pom.xml                 | 2 +-
 dubbo-container/dubbo-container-logback/pom.xml               | 2 +-
 dubbo-container/dubbo-container-spring/pom.xml                | 2 +-
 dubbo-container/pom.xml                                       | 2 +-
 dubbo-demo/dubbo-demo-api/pom.xml                             | 2 +-
 dubbo-demo/dubbo-demo-consumer/pom.xml                        | 2 +-
 dubbo-demo/dubbo-demo-provider/pom.xml                        | 2 +-
 dubbo-demo/pom.xml                                            | 2 +-
 dubbo-filter/dubbo-filter-cache/pom.xml                       | 2 +-
 dubbo-filter/dubbo-filter-validation/pom.xml                  | 2 +-
 dubbo-filter/pom.xml                                          | 2 +-
 dubbo-monitor/dubbo-monitor-api/pom.xml                       | 2 +-
 dubbo-monitor/dubbo-monitor-default/pom.xml                   | 2 +-
 dubbo-monitor/pom.xml                                         | 2 +-
 dubbo-registry/dubbo-registry-api/pom.xml                     | 2 +-
 dubbo-registry/dubbo-registry-default/pom.xml                 | 2 +-
 dubbo-registry/dubbo-registry-multicast/pom.xml               | 2 +-
 dubbo-registry/dubbo-registry-redis/pom.xml                   | 2 +-
 dubbo-registry/dubbo-registry-zookeeper/pom.xml               | 2 +-
 dubbo-registry/pom.xml                                        | 2 +-
 dubbo-remoting/dubbo-remoting-api/pom.xml                     | 2 +-
 dubbo-remoting/dubbo-remoting-grizzly/pom.xml                 | 2 +-
 dubbo-remoting/dubbo-remoting-http/pom.xml                    | 2 +-
 dubbo-remoting/dubbo-remoting-mina/pom.xml                    | 2 +-
 dubbo-remoting/dubbo-remoting-netty/pom.xml                   | 2 +-
 dubbo-remoting/dubbo-remoting-p2p/pom.xml                     | 2 +-
 dubbo-remoting/dubbo-remoting-zookeeper/pom.xml               | 2 +-
 dubbo-remoting/pom.xml                                        | 2 +-
 dubbo-rpc/dubbo-rpc-api/pom.xml                               | 2 +-
 dubbo-rpc/dubbo-rpc-default/pom.xml                           | 2 +-
 dubbo-rpc/dubbo-rpc-hessian/pom.xml                           | 2 +-
 dubbo-rpc/dubbo-rpc-http/pom.xml                              | 2 +-
 dubbo-rpc/dubbo-rpc-injvm/pom.xml                             | 2 +-
 dubbo-rpc/dubbo-rpc-memcached/pom.xml                         | 2 +-
 dubbo-rpc/dubbo-rpc-redis/pom.xml                             | 2 +-
 dubbo-rpc/dubbo-rpc-rest/pom.xml                              | 2 +-
 dubbo-rpc/dubbo-rpc-rmi/pom.xml                               | 2 +-
 dubbo-rpc/dubbo-rpc-thrift/pom.xml                            | 2 +-
 dubbo-rpc/dubbo-rpc-webservice/pom.xml                        | 2 +-
 dubbo-rpc/pom.xml                                             | 2 +-
 dubbo-simple/dubbo-monitor-simple/pom.xml                     | 2 +-
 dubbo-simple/dubbo-registry-simple/pom.xml                    | 2 +-
 dubbo-simple/pom.xml                                          | 2 +-
 dubbo-test/dubbo-test-benchmark-api/pom.xml                   | 2 +-
 dubbo-test/dubbo-test-benchmark-client/pom.xml                | 2 +-
 dubbo-test/dubbo-test-benchmark-server/pom.xml                | 2 +-
 dubbo-test/dubbo-test-benchmark/pom.xml                       | 2 +-
 dubbo-test/dubbo-test-compatibility/pom.xml                   | 2 +-
 dubbo-test/dubbo-test-examples/pom.xml                        | 2 +-
 dubbo-test/dubbo-test-integration/pom.xml                     | 2 +-
 dubbo-test/pom.xml                                            | 2 +-
 dubbo-tool/dubbo-demo-lite-archetype/pom.xml                  | 2 +-
 .../src/main/resources/archetype-resources/pom.xml            | 4 ++--
 dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml        | 2 +-
 dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml   | 2 +-
 dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml   | 2 +-
 dubbo-tool/dubbo-demo-lite/pom.xml                            | 4 ++--
 dubbo/pom.xml                                                 | 2 +-
 hessian-lite/pom.xml                                          | 2 +-
 pom.xml                                                       | 2 +-
 69 files changed, 71 insertions(+), 71 deletions(-)

diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml
index ec2a30be84ad..d13bbabafd8a 100644
--- a/dubbo-admin/pom.xml
+++ b/dubbo-admin/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-admin
 	war
diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml
index ec6af560cb05..7ccc706a7e50 100644
--- a/dubbo-cluster/pom.xml
+++ b/dubbo-cluster/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-cluster
 	jar
diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml
index 0d5e9f761de7..b03965474301 100644
--- a/dubbo-common/pom.xml
+++ b/dubbo-common/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-parent
-        2.8.4
+        2.8.4-SNAPSHOT
     
     dubbo-common
     jar
diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml
index d1f6a82c9c8c..87f2573de082 100644
--- a/dubbo-config/dubbo-config-api/pom.xml
+++ b/dubbo-config/dubbo-config-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-config
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-config-api
 	jar
diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml
index 9732dff29d63..ee565970c700 100644
--- a/dubbo-config/dubbo-config-spring/pom.xml
+++ b/dubbo-config/dubbo-config-spring/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-config
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-config-spring
 	jar
diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml
index 925195632b1d..e24542325ed9 100644
--- a/dubbo-config/pom.xml
+++ b/dubbo-config/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-config
 	pom
diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml
index 3cb4bda94c49..e83a7be244cb 100644
--- a/dubbo-container/dubbo-container-api/pom.xml
+++ b/dubbo-container/dubbo-container-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-container
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-container-api
 	jar
diff --git a/dubbo-container/dubbo-container-javaconfig/pom.xml b/dubbo-container/dubbo-container-javaconfig/pom.xml
index 3cc3985b60e1..d8dce1120f9a 100644
--- a/dubbo-container/dubbo-container-javaconfig/pom.xml
+++ b/dubbo-container/dubbo-container-javaconfig/pom.xml
@@ -19,7 +19,7 @@
   
     com.alibaba
     dubbo-container
-    2.8.4
+    2.8.4-SNAPSHOT
   
   dubbo-container-javaconfig
   jar
diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml
index 3fd180fb91a0..6fa2865fd722 100644
--- a/dubbo-container/dubbo-container-jetty/pom.xml
+++ b/dubbo-container/dubbo-container-jetty/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-container
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-container-jetty
 	jar
diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml
index be4637f32639..6d121e671df7 100644
--- a/dubbo-container/dubbo-container-log4j/pom.xml
+++ b/dubbo-container/dubbo-container-log4j/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-container
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-container-log4j
 	jar
diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml
index a123294937e2..89a0e2b9d432 100644
--- a/dubbo-container/dubbo-container-logback/pom.xml
+++ b/dubbo-container/dubbo-container-logback/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-container
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-container-logback
 	jar
diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml
index 9564561a899e..151648fb1b48 100644
--- a/dubbo-container/dubbo-container-spring/pom.xml
+++ b/dubbo-container/dubbo-container-spring/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-container
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-container-spring
 	jar
diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml
index b277ac007626..e0ae9eb639f7 100644
--- a/dubbo-container/pom.xml
+++ b/dubbo-container/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-container
 	pom
diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml
index a311efe313b5..4d7b0ed16a3b 100644
--- a/dubbo-demo/dubbo-demo-api/pom.xml
+++ b/dubbo-demo/dubbo-demo-api/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-demo
-        2.8.4
+        2.8.4-SNAPSHOT
     
     dubbo-demo-api
     jar
diff --git a/dubbo-demo/dubbo-demo-consumer/pom.xml b/dubbo-demo/dubbo-demo-consumer/pom.xml
index 3e2427967bb3..561bc91b1dda 100644
--- a/dubbo-demo/dubbo-demo-consumer/pom.xml
+++ b/dubbo-demo/dubbo-demo-consumer/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-demo
-        2.8.4
+        2.8.4-SNAPSHOT
     
     dubbo-demo-consumer
     jar
diff --git a/dubbo-demo/dubbo-demo-provider/pom.xml b/dubbo-demo/dubbo-demo-provider/pom.xml
index 1d6192f7aec7..8e8223bff7f2 100644
--- a/dubbo-demo/dubbo-demo-provider/pom.xml
+++ b/dubbo-demo/dubbo-demo-provider/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-demo
-        2.8.4
+        2.8.4-SNAPSHOT
     
     dubbo-demo-provider
     war
diff --git a/dubbo-demo/pom.xml b/dubbo-demo/pom.xml
index 4d77e14ec9ab..9086092fa481 100644
--- a/dubbo-demo/pom.xml
+++ b/dubbo-demo/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-demo
 	pom
diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml
index 8431bef623d6..17e7f414c45d 100644
--- a/dubbo-filter/dubbo-filter-cache/pom.xml
+++ b/dubbo-filter/dubbo-filter-cache/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-filter
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-filter-cache
 	jar
diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml
index d3d9cc121344..1a39c8d22fd5 100644
--- a/dubbo-filter/dubbo-filter-validation/pom.xml
+++ b/dubbo-filter/dubbo-filter-validation/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-filter
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-filter-validation
 	jar
diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml
index 86e2ef12fbf7..c0982f3d1cbe 100644
--- a/dubbo-filter/pom.xml
+++ b/dubbo-filter/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-filter
 	pom
diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml
index e654f038a54f..4b3d3e45f23d 100644
--- a/dubbo-monitor/dubbo-monitor-api/pom.xml
+++ b/dubbo-monitor/dubbo-monitor-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-monitor
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-monitor-api
 	jar
diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml
index 957fda3e4228..1433da5869df 100644
--- a/dubbo-monitor/dubbo-monitor-default/pom.xml
+++ b/dubbo-monitor/dubbo-monitor-default/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-monitor
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-monitor-default
 	jar
diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml
index 5061c3f56065..5b2cece72b15 100644
--- a/dubbo-monitor/pom.xml
+++ b/dubbo-monitor/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-monitor
 	pom
diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml
index 25572a8b656d..1cea605a4e9e 100644
--- a/dubbo-registry/dubbo-registry-api/pom.xml
+++ b/dubbo-registry/dubbo-registry-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-registry
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-registry-api
 	jar
diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml
index 2ee2515bed91..235c45af39f0 100644
--- a/dubbo-registry/dubbo-registry-default/pom.xml
+++ b/dubbo-registry/dubbo-registry-default/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-registry
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-registry-default
 	jar
diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml
index 478d4fb67b7a..0bc0f87b49e2 100644
--- a/dubbo-registry/dubbo-registry-multicast/pom.xml
+++ b/dubbo-registry/dubbo-registry-multicast/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-registry
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-registry-multicast
 	jar
diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml
index 10c9fa26b499..0ed0659b28ac 100644
--- a/dubbo-registry/dubbo-registry-redis/pom.xml
+++ b/dubbo-registry/dubbo-registry-redis/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-registry
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-registry-redis
 	jar
diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml
index 774d0b73bda7..3596e23e191a 100644
--- a/dubbo-registry/dubbo-registry-zookeeper/pom.xml
+++ b/dubbo-registry/dubbo-registry-zookeeper/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-registry
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-registry-zookeeper
 	jar
diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml
index 4dedf4fc732e..012b3d7f2685 100644
--- a/dubbo-registry/pom.xml
+++ b/dubbo-registry/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-registry
 	pom
diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml
index c8fe1460033c..e900de8fd8bd 100644
--- a/dubbo-remoting/dubbo-remoting-api/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-remoting-api
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml
index ce4b65200722..8fd695c8ea2e 100644
--- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-remoting-grizzly
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml
index c08a31deb77c..a70c182b5793 100644
--- a/dubbo-remoting/dubbo-remoting-http/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-http/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-remoting-http
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml
index b3e36966f1a7..d6fd4b334d66 100644
--- a/dubbo-remoting/dubbo-remoting-mina/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-mina/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-remoting-mina
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml
index afe4f789749b..969652cc8893 100644
--- a/dubbo-remoting/dubbo-remoting-netty/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-netty/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-remoting-netty
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml
index 0dce25f736f3..752e8cec5bcf 100644
--- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-p2p/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-remoting-p2p
 	jar
diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml
index 47520dae0d85..7d890d4bbf9d 100644
--- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml
+++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-remoting
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-remoting-zookeeper
 	jar
diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml
index 0c7faf42bbc0..9d105595602e 100644
--- a/dubbo-remoting/pom.xml
+++ b/dubbo-remoting/pom.xml
@@ -18,7 +18,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-remoting
 	pom
diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml
index e713642d38e9..f99be2c33d87 100644
--- a/dubbo-rpc/dubbo-rpc-api/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc-api
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml
index a31250d37dbf..04e0f3f0db2d 100644
--- a/dubbo-rpc/dubbo-rpc-default/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-default/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc-default
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml
index bf5e50cb4c61..cd86aac2b7ac 100644
--- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-hessian/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc-hessian
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml
index a2ad7c134f39..e3d4114279a7 100644
--- a/dubbo-rpc/dubbo-rpc-http/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-http/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc-http
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml
index dcdda8d53454..d448c6810ade 100644
--- a/dubbo-rpc/dubbo-rpc-injvm/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-injvm/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc-injvm
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml
index 6a2af14c3c6b..5819d091e8a2 100644
--- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-memcached/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc-memcached
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml
index 9e39b9fa31f7..9b1004b3a332 100644
--- a/dubbo-rpc/dubbo-rpc-redis/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-redis/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc-redis
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml
index 11edf84ca91d..ce508b3639a5 100644
--- a/dubbo-rpc/dubbo-rpc-rest/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-rest/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc-rest
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml
index 84b76b9a0593..94650bdfddad 100644
--- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-rmi/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc-rmi
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml
index 3b8500aa105c..904ed0d470ef 100644
--- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-thrift/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc-thrift
 	jar
diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml
index 069d285b432d..e87a7a7a17a4 100644
--- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml
+++ b/dubbo-rpc/dubbo-rpc-webservice/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-rpc
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc-webservice
 	jar
diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml
index 4dd07112ac0f..b16152760e04 100644
--- a/dubbo-rpc/pom.xml
+++ b/dubbo-rpc/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-rpc
 	pom
diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml
index 4068dfc52faf..001762083ed2 100644
--- a/dubbo-simple/dubbo-monitor-simple/pom.xml
+++ b/dubbo-simple/dubbo-monitor-simple/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-simple
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-monitor-simple
 	jar
diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml
index 6c1912bee661..5dd8c0d2b338 100644
--- a/dubbo-simple/dubbo-registry-simple/pom.xml
+++ b/dubbo-simple/dubbo-registry-simple/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-simple
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-registry-simple
 	jar
diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml
index 5bb270f01792..c33499c1d8c3 100644
--- a/dubbo-simple/pom.xml
+++ b/dubbo-simple/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-simple
 	pom
diff --git a/dubbo-test/dubbo-test-benchmark-api/pom.xml b/dubbo-test/dubbo-test-benchmark-api/pom.xml
index 79f9a30036c2..1012772de5e7 100644
--- a/dubbo-test/dubbo-test-benchmark-api/pom.xml
+++ b/dubbo-test/dubbo-test-benchmark-api/pom.xml
@@ -4,7 +4,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-test-benchmark-api
 	jar
diff --git a/dubbo-test/dubbo-test-benchmark-client/pom.xml b/dubbo-test/dubbo-test-benchmark-client/pom.xml
index 09aded711066..32faa5476fba 100644
--- a/dubbo-test/dubbo-test-benchmark-client/pom.xml
+++ b/dubbo-test/dubbo-test-benchmark-client/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-test-benchmark-client
 	jar
diff --git a/dubbo-test/dubbo-test-benchmark-server/pom.xml b/dubbo-test/dubbo-test-benchmark-server/pom.xml
index 9a97c7df23f4..995211ec0c6d 100644
--- a/dubbo-test/dubbo-test-benchmark-server/pom.xml
+++ b/dubbo-test/dubbo-test-benchmark-server/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-test-benchmark-server
 	jar
diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml
index 2593c9e50547..ebd4404231d5 100644
--- a/dubbo-test/dubbo-test-benchmark/pom.xml
+++ b/dubbo-test/dubbo-test-benchmark/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-test-benchmark
 	jar
diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml
index d02370e64cc7..5cd9d6872a45 100644
--- a/dubbo-test/dubbo-test-compatibility/pom.xml
+++ b/dubbo-test/dubbo-test-compatibility/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-test-compatibility
 	jar
diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml
index 43b4b699291e..a19ea47ccbc6 100644
--- a/dubbo-test/dubbo-test-examples/pom.xml
+++ b/dubbo-test/dubbo-test-examples/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-test-examples
 	jar
diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml
index cbf43a6836a1..cb6136c5f97d 100644
--- a/dubbo-test/dubbo-test-integration/pom.xml
+++ b/dubbo-test/dubbo-test-integration/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-test
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-test-integration
 	jar
diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml
index 8ccfec26d319..4265dc1a8d8f 100644
--- a/dubbo-test/pom.xml
+++ b/dubbo-test/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-test
 	pom
diff --git a/dubbo-tool/dubbo-demo-lite-archetype/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/pom.xml
index 844d9844dbd3..314e37ae8bc7 100644
--- a/dubbo-tool/dubbo-demo-lite-archetype/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite-archetype/pom.xml
@@ -4,7 +4,7 @@
 
   com.alibaba
   dubbo-demo-lite-archetype
-  2.8.4
+  2.8.4-SNAPSHOT
   maven-archetype
 
   dubbo-demo-lite-archetype
diff --git a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml
index 561a683e509e..6bc59bb80255 100644
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml
@@ -18,7 +18,7 @@
     
         com.alibaba
         dubbo-parent
-        2.8.4
+        2.8.4-SNAPSHOT
     
     ${artifactId}
     ${groupId}
@@ -35,7 +35,7 @@
             
                 com.alibaba
                 dubbo
-                2.8.4
+                2.8.4-SNAPSHOT
             
         
     
diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml
index fb06b6404790..3e82534f43b0 100644
--- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-demo-lite
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-demo-lite-api
 	jar
diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
index e59c2df0903c..849e284c2244 100644
--- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-demo-lite
-        2.8.4
+        2.8.4-SNAPSHOT
     
     dubbo-demo-lite-consumer
     jar
diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
index ab2cead41cd3..f7b3757ec350 100644
--- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-demo-lite
-        2.8.4
+        2.8.4-SNAPSHOT
     
 	dubbo-demo-lite-provider
 	war
diff --git a/dubbo-tool/dubbo-demo-lite/pom.xml b/dubbo-tool/dubbo-demo-lite/pom.xml
index b43142ae691e..4b9977be0f5a 100644
--- a/dubbo-tool/dubbo-demo-lite/pom.xml
+++ b/dubbo-tool/dubbo-demo-lite/pom.xml
@@ -19,7 +19,7 @@
 	
 		com.alibaba
 		dubbo-parent
-		2.8.4
+		2.8.4-SNAPSHOT
 	
 	dubbo-demo-lite
 	pom
@@ -39,7 +39,7 @@
             
                 com.alibaba
                 dubbo
-                2.8.4
+                2.8.4-SNAPSHOT
             
         
     
diff --git a/dubbo/pom.xml b/dubbo/pom.xml
index 447be40bdd40..1a4042c1a4f2 100644
--- a/dubbo/pom.xml
+++ b/dubbo/pom.xml
@@ -19,7 +19,7 @@
     
         com.alibaba
         dubbo-parent
-        2.8.4
+        2.8.4-SNAPSHOT
     
     dubbo
     jar
diff --git a/hessian-lite/pom.xml b/hessian-lite/pom.xml
index c377884a45e9..e3836a82ba5d 100644
--- a/hessian-lite/pom.xml
+++ b/hessian-lite/pom.xml
@@ -6,7 +6,7 @@
     
         com.alibaba
         dubbo-parent
-        2.8.4
+        2.8.4-SNAPSHOT
     
     hessian-lite
     jar
diff --git a/pom.xml b/pom.xml
index 92096e7237dc..1446054a8655 100644
--- a/pom.xml
+++ b/pom.xml
@@ -20,7 +20,7 @@
 		2.0  -->
 	com.alibaba
 	dubbo-parent
-	2.8.4
+	2.8.4-SNAPSHOT
 	pom
 	${project.artifactId}
 	The parent project of dubbo

From abfd6fda8f8be8edb8fa9db0f677074ac5f01bd6 Mon Sep 17 00:00:00 2001
From: Li Shen 
Date: Tue, 13 Jan 2015 16:37:33 +0800
Subject: [PATCH 176/200] change  compiler settings

---
 pom.xml | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/pom.xml b/pom.xml
index 1446054a8655..c080d5eb8358 100644
--- a/pom.xml
+++ b/pom.xml
@@ -584,9 +584,13 @@
 					maven-compiler-plugin
 					${maven_compiler_plugin_version}
 					
+                        true
 						${java_source_version}
 						${java_target_version}
 						${file_encoding}
+                        
+                            -XX:MaxPermSize=512M
+                        
 					
 				
 				
 	com.alibaba
 	dubbo-parent
-	2.8.4-SNAPSHOT
+	2.8.4
 	pom
 	${project.artifactId}
 	The parent project of dubbo

From 7b1e69046a9ed043dfe733251e89d9d9a3b5aea8 Mon Sep 17 00:00:00 2001
From: fanlu 
Date: Tue, 31 Mar 2015 18:02:00 +0800
Subject: [PATCH 188/200] fix package phase attach sources

---
 dubbo/pom.xml |  5 ++++-
 pom.xml       | 12 ++++++++++++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/dubbo/pom.xml b/dubbo/pom.xml
index 447be40bdd40..1ff4074b8846 100644
--- a/dubbo/pom.xml
+++ b/dubbo/pom.xml
@@ -326,7 +326,10 @@
                 
                     
                         attach-sources
-                        none
+                        package
+                        
+                            jar-no-fork
+                        
                     
                 
             
diff --git a/pom.xml b/pom.xml
index f17499531d1e..f4e69f74a4bf 100644
--- a/pom.xml
+++ b/pom.xml
@@ -477,6 +477,18 @@
 					
 				
 			
+			
+				maven-source-plugin
+				
+					
+						attach-sources
+						package
+						
+							jar-no-fork
+						
+					
+				
+			
 			
 				org.apache.maven.plugins
 				maven-surefire-plugin

From 85b9ab1e3e209e5ee82b75a7d38a7a1bcee8b58b Mon Sep 17 00:00:00 2001
From: lishen 
Date: Sat, 31 Oct 2015 16:34:10 +0800
Subject: [PATCH 189/200] fix the decoding issue of kryo and fst

---
 .../rpc/protocol/dubbo/DecodeableRpcInvocation.java    |  6 +-----
 .../alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java   | 10 ++++------
 2 files changed, 5 insertions(+), 11 deletions(-)

diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java
index a1dbd660a664..8c1e46759c4c 100644
--- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java
+++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DecodeableRpcInvocation.java
@@ -103,11 +103,7 @@ public Object decode(Channel channel, InputStream input) throws IOException {
                 Class[] pts;
 
                 // NOTICE modified by lishen
-                int argNum = -1;
-
-                if (CodecSupport.getSerialization(channel.getUrl(), serializationType) instanceof OptimizedSerialization) {
-                    argNum = in.readInt();
-                }
+                int argNum = in.readInt();
                 if (argNum >= 0) {
                     if (argNum == 0) {
                         pts = DubboCodec.EMPTY_CLASS_ARRAY;
diff --git a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java
index 6b588190b60c..3e5fd8944f14 100644
--- a/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java
+++ b/dubbo-rpc/dubbo-rpc-default/src/main/java/com/alibaba/dubbo/rpc/protocol/dubbo/DubboCodec.java
@@ -181,15 +181,13 @@ protected void encodeRequestData(Channel channel, ObjectOutput out, Object data)
 
         // NOTICE modified by lishen
         // TODO
-        if (getSerialization(channel) instanceof OptimizedSerialization) {
-            if (!containComplexArguments(inv)) {
-                out.writeInt(inv.getParameterTypes().length);
-            } else {
-                out.writeInt(-1);
-            }
+        if (getSerialization(channel) instanceof OptimizedSerialization && !containComplexArguments(inv)) {
+            out.writeInt(inv.getParameterTypes().length);
         } else {
+            out.writeInt(-1);
             out.writeUTF(ReflectUtils.getDesc(inv.getParameterTypes()));
         }
+
         Object[] args = inv.getArguments();
         if (args != null)
             for (int i = 0; i < args.length; i++){

From 5d272cb052a3ffa4aa744173baf9f21ae68036eb Mon Sep 17 00:00:00 2001
From: haibao 
Date: Sat, 30 Apr 2016 15:09:49 +0800
Subject: [PATCH 190/200] =?UTF-8?q?=E4=BF=AE=E5=A4=8Ddubbo=E5=88=86?=
 =?UTF-8?q?=E7=BB=84=E6=A0=A1=E9=AA=8C=E5=A4=B1=E6=95=88=E7=9A=84=E9=97=AE?=
 =?UTF-8?q?=E9=A2=98?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../dubbo/validation/support/jvalidation/JValidator.java        | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/com/alibaba/dubbo/validation/support/jvalidation/JValidator.java b/dubbo-filter/dubbo-filter-validation/src/main/java/com/alibaba/dubbo/validation/support/jvalidation/JValidator.java
index d0ec6615d357..ab5a3cce3ab0 100644
--- a/dubbo-filter/dubbo-filter-validation/src/main/java/com/alibaba/dubbo/validation/support/jvalidation/JValidator.java
+++ b/dubbo-filter/dubbo-filter-validation/src/main/java/com/alibaba/dubbo/validation/support/jvalidation/JValidator.java
@@ -89,7 +89,7 @@ public JValidator(URL url) {
     }
 
     public void validate(String methodName, Class[] parameterTypes, Object[] arguments) throws Exception {
-        String methodClassName = clazz.getName() + "_" + toUpperMethoName(methodName);
+        String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName);
         Class methodClass = null;
         try {
             methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());

From 53cfc2895bde7103325a985593ae5d18a9f2e310 Mon Sep 17 00:00:00 2001
From: lele_wei 
Date: Fri, 27 May 2016 11:17:08 +0800
Subject: [PATCH 191/200] =?UTF-8?q?maczam=20=20=E5=90=8C=E5=AD=A6=E4=BF=AE?=
 =?UTF-8?q?=E5=A4=8D=E7=9A=84=20jedis=E6=96=AD=E7=82=B9=E9=87=8D=E8=BF=9E?=
 =?UTF-8?q?=E6=97=B6=E7=9A=84=E9=97=AE=E9=A2=98?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../dubbo/registry/redis/RedisRegistry.java   | 128 ++++++++++++------
 1 file changed, 84 insertions(+), 44 deletions(-)

diff --git a/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java b/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java
index b754d9533050..0442f003e6c8 100644
--- a/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java
+++ b/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java
@@ -48,10 +48,11 @@
 import com.alibaba.dubbo.registry.NotifyListener;
 import com.alibaba.dubbo.registry.support.FailbackRegistry;
 import com.alibaba.dubbo.rpc.RpcException;
+import redis.clients.jedis.exceptions.JedisConnectionException;
 
 /**
  * RedisRegistry
- * 
+ *
  * @author william.liangf
  */
 public class RedisRegistry extends FailbackRegistry {
@@ -65,26 +66,26 @@ public class RedisRegistry extends FailbackRegistry {
     private final ScheduledExecutorService expireExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboRegistryExpireTimer", true));
 
     private final ScheduledFuture expireFuture;
-    
+
     private final String root;
 
     private final Map jedisPools = new ConcurrentHashMap();
 
     private final ConcurrentMap notifiers = new ConcurrentHashMap();
-    
+
     private final int reconnectPeriod;
 
     private final int expirePeriod;
-    
+
     private volatile boolean admin = false;
-    
+
     private boolean replicate;
 
     public RedisRegistry(URL url) {
         super(url);
         if (url.isAnyHost()) {
-    		throw new IllegalStateException("registry address == null");
-    	}
+            throw new IllegalStateException("registry address == null");
+        }
         GenericObjectPool.Config config = new GenericObjectPool.Config();
         config.testOnBorrow = url.getParameter("test.on.borrow", true);
         config.testOnReturn = url.getParameter("test.on.return", false);
@@ -103,13 +104,13 @@ public RedisRegistry(URL url) {
             config.timeBetweenEvictionRunsMillis = url.getParameter("time.between.eviction.runs.millis", 0);
         if (url.getParameter("min.evictable.idle.time.millis", 0) > 0)
             config.minEvictableIdleTimeMillis = url.getParameter("min.evictable.idle.time.millis", 0);
-        
+
         String cluster = url.getParameter("cluster", "failover");
         if (! "failover".equals(cluster) && ! "replicate".equals(cluster)) {
-        	throw new IllegalArgumentException("Unsupported redis cluster: " + cluster + ". The redis cluster only supported failover or replicate.");
+            throw new IllegalArgumentException("Unsupported redis cluster: " + cluster + ". The redis cluster only supported failover or replicate.");
         }
         replicate = "replicate".equals(cluster);
-        
+
         List addresses = new ArrayList();
         addresses.add(url.getAddress());
         String[] backups = url.getParameter(Constants.BACKUP_KEY, new String[0]);
@@ -127,10 +128,10 @@ public RedisRegistry(URL url) {
                 host = address;
                 port = DEFAULT_REDIS_PORT;
             }
-            this.jedisPools.put(address, new JedisPool(config, host, port, 
+            this.jedisPools.put(address, new JedisPool(config, host, port,
                     url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)));
         }
-        
+
         this.reconnectPeriod = url.getParameter(Constants.REGISTRY_RECONNECT_PERIOD_KEY, Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD);
         String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT);
         if (! group.startsWith(Constants.PATH_SEPARATOR)) {
@@ -140,7 +141,7 @@ public RedisRegistry(URL url) {
             group = group + Constants.PATH_SEPARATOR;
         }
         this.root = group;
-        
+
         this.expirePeriod = url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT);
         this.expireFuture = expireExecutor.scheduleWithFixedDelay(new Runnable() {
             public void run() {
@@ -152,10 +153,11 @@ public void run() {
             }
         }, expirePeriod / 2, expirePeriod / 2, TimeUnit.MILLISECONDS);
     }
-    
+
     private void deferExpired() {
         for (Map.Entry entry : jedisPools.entrySet()) {
             JedisPool jedisPool = entry.getValue();
+            boolean isBroken = false;
             try {
                 Jedis jedis = jedisPool.getResource();
                 try {
@@ -170,18 +172,24 @@ private void deferExpired() {
                     if (admin) {
                         clean(jedis);
                     }
-                    if (! replicate) {
-                    	break;// 聽濡傛灉鏈嶅姟鍣ㄧ宸插悓姝ユ暟鎹紝鍙渶鍐欏叆鍗曞彴鏈哄櫒
+                    if (!replicate) {
+                        break;//  濡傛灉鏈嶅姟鍣ㄧ宸插悓姝ユ暟鎹紝鍙渶鍐欏叆鍗曞彴鏈哄櫒
                     }
+                } catch (JedisConnectionException e){
+                    isBroken = true;
                 } finally {
-                    jedisPool.returnResource(jedis);
+                    if(isBroken){
+                        jedisPool.returnBrokenResource(jedis);
+                    } else {
+                        jedisPool.returnResource(jedis);
+                    }
                 }
             } catch (Throwable t) {
                 logger.warn("Failed to write provider heartbeat to redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t);
             }
         }
     }
-    
+
     // 鐩戞帶涓績璐熻矗鍒犻櫎杩囨湡鑴忔暟鎹
     private void clean(Jedis jedis) {
         Set keys = jedis.keys(root + Constants.ANY_VALUE);
@@ -202,7 +210,7 @@ private void clean(Jedis jedis) {
                                     logger.warn("Delete expired key: " + key + " -> value: " + entry.getKey() + ", expire: " + new Date(expire) + ", now: " + new Date(now));
                                 }
                             }
-                            }
+                        }
                     }
                     if (delete) {
                         jedis.publish(key, Constants.UNREGISTER);
@@ -214,16 +222,20 @@ private void clean(Jedis jedis) {
 
     public boolean isAvailable() {
         for (JedisPool jedisPool : jedisPools.values()) {
+            Jedis jedis = jedisPool.getResource();
+            boolean isBroken = false;
             try {
-                Jedis jedis = jedisPool.getResource();
-                try {
-                	if (jedis.isConnected()) {
-                        return true; // 鑷冲皯闇鍗曞彴鏈哄櫒鍙敤
-                    }
-                } finally {
+                if (jedis.isConnected()) {
+                    return true; // 鑷冲皯闇鍗曞彴鏈哄櫒鍙敤
+                }
+            } catch (JedisConnectionException e) {
+                isBroken = true;
+            } finally {
+                if (isBroken) {
+                    jedisPool.returnBrokenResource(jedis);
+                } else {
                     jedisPool.returnResource(jedis);
                 }
-            } catch (Throwable t) {
             }
         }
         return false;
@@ -265,15 +277,22 @@ public void doRegister(URL url) {
             JedisPool jedisPool = entry.getValue();
             try {
                 Jedis jedis = jedisPool.getResource();
+                boolean isBroken = false;
                 try {
                     jedis.hset(key, value, expire);
                     jedis.publish(key, Constants.REGISTER);
                     success = true;
                     if (! replicate) {
-                    	break; // 聽濡傛灉鏈嶅姟鍣ㄧ宸插悓姝ユ暟鎹紝鍙渶鍐欏叆鍗曞彴鏈哄櫒
+                        break; //  濡傛灉鏈嶅姟鍣ㄧ宸插悓姝ユ暟鎹紝鍙渶鍐欏叆鍗曞彴鏈哄櫒
                     }
+                } catch (JedisConnectionException e){
+                    isBroken = true;
                 } finally {
-                    jedisPool.returnResource(jedis);
+                    if(isBroken){
+                        jedisPool.returnBrokenResource(jedis);
+                    } else {
+                        jedisPool.returnResource(jedis);
+                    }
                 }
             } catch (Throwable t) {
                 exception = new RpcException("Failed to register service to redis registry. registry: " + entry.getKey() + ", service: " + url + ", cause: " + t.getMessage(), t);
@@ -298,15 +317,22 @@ public void doUnregister(URL url) {
             JedisPool jedisPool = entry.getValue();
             try {
                 Jedis jedis = jedisPool.getResource();
+                boolean isBroken = false;
                 try {
                     jedis.hdel(key, value);
                     jedis.publish(key, Constants.UNREGISTER);
                     success = true;
                     if (! replicate) {
-                    	break; // 聽濡傛灉鏈嶅姟鍣ㄧ宸插悓姝ユ暟鎹紝鍙渶鍐欏叆鍗曞彴鏈哄櫒
+                        break; //  濡傛灉鏈嶅姟鍣ㄧ宸插悓姝ユ暟鎹紝鍙渶鍐欏叆鍗曞彴鏈哄櫒
                     }
+                } catch (JedisConnectionException e){
+                    isBroken = true;
                 } finally {
-                    jedisPool.returnResource(jedis);
+                    if(isBroken){
+                        jedisPool.returnBrokenResource(jedis);
+                    } else {
+                        jedisPool.returnResource(jedis);
+                    }
                 }
             } catch (Throwable t) {
                 exception = new RpcException("Failed to unregister service to redis registry. registry: " + entry.getKey() + ", service: " + url + ", cause: " + t.getMessage(), t);
@@ -320,7 +346,7 @@ public void doUnregister(URL url) {
             }
         }
     }
-    
+
     @Override
     public void doSubscribe(final URL url, final NotifyListener listener) {
         String service = toServicePath(url);
@@ -339,6 +365,7 @@ public void doSubscribe(final URL url, final NotifyListener listener) {
             JedisPool jedisPool = entry.getValue();
             try {
                 Jedis jedis = jedisPool.getResource();
+                boolean isBroken = false;
                 try {
                     if (service.endsWith(Constants.ANY_VALUE)) {
                         admin = true;
@@ -363,8 +390,14 @@ public void doSubscribe(final URL url, final NotifyListener listener) {
                     }
                     success = true;
                     break; // 鍙渶璇讳竴涓湇鍔″櫒鐨勬暟鎹
+                } catch (JedisConnectionException e){
+                    isBroken = true;
                 } finally {
-                    jedisPool.returnResource(jedis);
+                    if(isBroken){
+                        jedisPool.returnBrokenResource(jedis);
+                    } else {
+                        jedisPool.returnResource(jedis);
+                    }
                 }
             } catch(Throwable t) { // 灏濊瘯涓嬩竴涓湇鍔″櫒
                 exception = new RpcException("Failed to subscribe service from redis registry. registry: " + entry.getKey() + ", service: " + url + ", cause: " + t.getMessage(), t);
@@ -470,7 +503,7 @@ private String toCategoryPath(URL url) {
     }
 
     private class NotifySub extends JedisPubSub {
-        
+
         private final JedisPool jedisPool;
 
         public NotifySub(JedisPool jedisPool) {
@@ -482,14 +515,21 @@ public void onMessage(String key, String msg) {
             if (logger.isInfoEnabled()) {
                 logger.info("redis event: " + key + " = " + msg);
             }
-            if (msg.equals(Constants.REGISTER) 
+            if (msg.equals(Constants.REGISTER)
                     || msg.equals(Constants.UNREGISTER)) {
                 try {
                     Jedis jedis = jedisPool.getResource();
+                    boolean isBroken = false;
                     try {
                         doNotify(jedis, key);
+                    } catch (JedisConnectionException e){
+                        isBroken = true;
                     } finally {
-                        jedisPool.returnResource(jedis);
+                        if(isBroken){
+                            jedisPool.returnBrokenResource(jedis);
+                        } else {
+                            jedisPool.returnResource(jedis);
+                        }
                     }
                 } catch (Throwable t) { // TODO 閫氱煡澶辫触娌℃湁鎭㈠鏈哄埗淇濋殰
                     logger.error(t.getMessage(), t);
@@ -527,15 +567,15 @@ private class Notifier extends Thread {
         private volatile Jedis jedis;
 
         private volatile boolean first = true;
-        
+
         private volatile boolean running = true;
-        
+
         private final AtomicInteger connectSkip = new AtomicInteger();
 
         private final AtomicInteger connectSkiped = new AtomicInteger();
 
         private final Random random = new Random();
-        
+
         private volatile int connectRandom;
 
         private void resetSkip() {
@@ -543,7 +583,7 @@ private void resetSkip() {
             connectSkiped.set(0);
             connectRandom = 0;
         }
-        
+
         private boolean isSkip() {
             int skip = connectSkip.get(); // 璺宠繃娆℃暟澧為暱
             if (skip >= 10) { // 濡傛灉璺宠繃娆℃暟澧為暱瓒呰繃10锛屽彇闅忔満鏁
@@ -560,13 +600,13 @@ private boolean isSkip() {
             connectRandom = 0;
             return false;
         }
-        
+
         public Notifier(String service) {
             super.setDaemon(true);
             super.setName("DubboRedisSubscribe");
             this.service = service;
         }
-        
+
         @Override
         public void run() {
             while (running) {
@@ -618,7 +658,7 @@ public void run() {
                 }
             }
         }
-        
+
         public void shutdown() {
             try {
                 running = false;
@@ -627,7 +667,7 @@ public void shutdown() {
                 logger.warn(t.getMessage(), t);
             }
         }
-        
+
     }
 
-}
+}
\ No newline at end of file

From 26b6486819d9cfd23c35073151541e0ba1025da8 Mon Sep 17 00:00:00 2001
From: lele_wei 
Date: Fri, 27 May 2016 11:57:27 +0800
Subject: [PATCH 192/200] =?UTF-8?q?=E4=BD=BFredis=E6=94=AF=E6=8C=81passwor?=
 =?UTF-8?q?d=E3=80=82=20=20backup=E5=BF=85=E9=A1=BB=E4=BD=BF=E7=94=A8?=
 =?UTF-8?q?=E7=9B=B8=E5=90=8C=E7=9A=84password=EF=BC=8C=E5=90=A6=E5=88=99?=
 =?UTF-8?q?=E6=97=A0=E6=B3=95=E8=BF=9E=E6=8E=A5=E3=80=82?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../dubbo/registry/redis/RedisRegistry.java   | 14 +++++++++--
 .../registry/redis/RedisRegistryTest.java     | 24 +++++++++++--------
 2 files changed, 26 insertions(+), 12 deletions(-)

diff --git a/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java b/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java
index 0442f003e6c8..7ac9da8250fb 100644
--- a/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java
+++ b/dubbo-registry/dubbo-registry-redis/src/main/java/com/alibaba/dubbo/registry/redis/RedisRegistry.java
@@ -33,6 +33,7 @@
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
+import com.alibaba.dubbo.common.utils.StringUtils;
 import org.apache.commons.pool.impl.GenericObjectPool;
 
 import redis.clients.jedis.Jedis;
@@ -117,6 +118,9 @@ public RedisRegistry(URL url) {
         if (backups != null && backups.length > 0) {
             addresses.addAll(Arrays.asList(backups));
         }
+
+        // 澧炲姞Redis瀵嗙爜鏀寔
+        String password = url.getPassword();
         for (String address : addresses) {
             int i = address.indexOf(':');
             String host;
@@ -128,8 +132,14 @@ public RedisRegistry(URL url) {
                 host = address;
                 port = DEFAULT_REDIS_PORT;
             }
-            this.jedisPools.put(address, new JedisPool(config, host, port,
-                    url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)));
+            if (StringUtils.isEmpty(password)) {
+                this.jedisPools.put(address, new JedisPool(config, host, port,
+                        url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)));
+            } else {
+                // 浣跨敤瀵嗙爜杩炴帴銆  姝ゅ瑕佹眰澶囩敤redis涓庝富瑕乺edis浣跨敤鐩稿悓鐨勫瘑鐮
+                this.jedisPools.put(address, new JedisPool(config, host, port,
+                        url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT), password));
+            }
         }
 
         this.reconnectPeriod = url.getParameter(Constants.REGISTRY_RECONNECT_PERIOD_KEY, Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD);
diff --git a/dubbo-registry/dubbo-registry-redis/src/test/java/com/alibaba/dubbo/registry/redis/RedisRegistryTest.java b/dubbo-registry/dubbo-registry-redis/src/test/java/com/alibaba/dubbo/registry/redis/RedisRegistryTest.java
index 7b710dac6d4a..81c791daed74 100644
--- a/dubbo-registry/dubbo-registry-redis/src/test/java/com/alibaba/dubbo/registry/redis/RedisRegistryTest.java
+++ b/dubbo-registry/dubbo-registry-redis/src/test/java/com/alibaba/dubbo/registry/redis/RedisRegistryTest.java
@@ -20,7 +20,11 @@
 import org.junit.Test;
 
 import com.alibaba.dubbo.common.URL;
-import com.alibaba.dubbo.registry.NotifyListener;
+
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
 
 /**
  * RedisRegistryTest
@@ -30,11 +34,11 @@
 public class RedisRegistryTest {
 
     String            service     = "com.alibaba.dubbo.test.injvmServie";
-    URL               registryUrl = URL.valueOf("redis://239.255.255.255/");
+    URL               registryUrl = URL.valueOf("redis://a:testpass@127.0.0.1:6379/");
     URL               serviceUrl  = URL.valueOf("redis://redis/" + service
                                                 + "?notify=false&methods=test1,test2");
     URL               consumerUrl = URL.valueOf("redis://consumer/" + service + "?notify=false&methods=test1,test2");
-    // RedisRegistry registry    = new RedisRegistry(registryUrl);
+    RedisRegistry registry    = new RedisRegistry(registryUrl);
 
     /**
      * @throws java.lang.Exception
@@ -48,7 +52,7 @@ public static void setUpBeforeClass() throws Exception {
      */
     @Before
     public void setUp() throws Exception {
-        //registry.register(service, serviceUrl);
+        registry.register(serviceUrl);
     }
 
     /**
@@ -56,18 +60,18 @@ public void setUp() throws Exception {
      */
     @Test
     public void testRegister() {
-        /*List registered = null;
+        Set registered = null;
         // clear first
-        registered = registry.getRegistered(service);
+        //registered = registry.getRegistered();
 
         for (int i = 0; i < 2; i++) {
-            registry.register(service, serviceUrl);
-            registered = registry.getRegistered(service);
+            registry.register(serviceUrl);
+            registered = registry.getRegistered();
             assertTrue(registered.contains(serviceUrl));
         }
         // confirm only 1 regist success;
-        registered = registry.getRegistered(service);
-        assertEquals(1, registered.size());*/
+        registered = registry.getRegistered();
+        assertEquals(1, registered.size());
     }
 
     /**

From 4ac555b5ae821468c1d08eb569672bc53872a2fa Mon Sep 17 00:00:00 2001
From: yang qiju <362991493@qq.com>
Date: Fri, 8 Jul 2016 01:23:36 -0500
Subject: [PATCH 193/200] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=BB=98=E8=AE=A4?=
 =?UTF-8?q?=E6=A3=80=E6=9F=A5=E6=9C=8D=E5=8A=A1=E9=94=99=E8=AF=AF=E7=9A=84?=
 =?UTF-8?q?=E9=97=AE=E9=A2=98?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

妗嗘灦榛樿浼氭鏌ユ湇鍔℃槸鍚﹀瓨鍦紝ReferenceConfig 涓璫heck 鏃秐ull鏃跺垯鏄痶rue锛岃屾敞瑙d腑鐨勯粯璁ゅ间负false锛屽鑷村悜spring瑙f瀽鏃讹紝瀵筊eferenceBean 鐨刢heck鍊兼病鏈夌粰鍊硷紝榛樿涓哄鐞嗕负true锛屽鑷存爣绛綾heck鍔熻兘澶辨晥
---
 .../java/com/alibaba/dubbo/config/annotation/Reference.java     | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java
index 6d403362837c..d058ff375614 100644
--- a/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java
+++ b/dubbo-config/dubbo-config-api/src/main/java/com/alibaba/dubbo/config/annotation/Reference.java
@@ -48,7 +48,7 @@
 
     boolean injvm() default false;
 
-    boolean check() default false;
+    boolean check() default true;
 
     boolean init() default false;
 

From cd719a09c15b0ebfd47e8d51f13c2b9a97b55f85 Mon Sep 17 00:00:00 2001
From: Ian Hu 
Date: Fri, 26 Aug 2016 14:32:25 +0800
Subject: [PATCH 194/200] feat(ci): upgrade javassit to make it compatible with
 java 8

---
 pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/pom.xml b/pom.xml
index f4e69f74a4bf..2f1517bd3c93 100644
--- a/pom.xml
+++ b/pom.xml
@@ -85,7 +85,7 @@
 	
 		
 		3.2.9.RELEASE
-		3.15.0-GA
+		3.20.0-GA
 		3.7.0.Final
 		1.1.7
 		2.1.4

From 428065704f91afee3b347dc2f041b088bf09e98d Mon Sep 17 00:00:00 2001
From: li-shen 
Date: Wed, 7 Sep 2016 16:42:11 +0800
Subject: [PATCH 195/200] update doc

---
 README.md | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/README.md b/README.md
index 8be6642a82d8..6db79dc0f92e 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,6 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p
 * Dylan 鐙珛寮鍙戣 dinguangx@163.com
 * Kangfoo 鐙珛寮鍙戣
 
-**璁ㄨQQ缇**锛258792161  锛堜笉闄愪簬dubbox锛屽寘鎷琒OA璁捐銆佷簰鑱旂綉鎶鏈瓑绛夊叴瓒d氦娴侊級
 
 ## Dubbox褰撳墠鐨勪富瑕佸姛鑳
 
@@ -199,4 +198,4 @@ http://stackoverflow.com/questions/17196766/can-resteasy-choose-method-based-on-
 
 ### JAX-RS涓綔POST鐨勬柟娉曡兘澶熸帴鏀跺涓弬鏁板悧锛
 
-http://stackoverflow.com/questions/5553218/jax-rs-post-multiple-objects
\ No newline at end of file
+http://stackoverflow.com/questions/5553218/jax-rs-post-multiple-objects

From 4a16059e7cf1bd40d51875534b04c1dc9394b83c Mon Sep 17 00:00:00 2001
From: li-shen 
Date: Thu, 8 Sep 2016 15:33:18 +0800
Subject: [PATCH 196/200] update

---
 README.md | 1 +
 1 file changed, 1 insertion(+)

diff --git a/README.md b/README.md
index 6db79dc0f92e..888c4848ef74 100644
--- a/README.md
+++ b/README.md
@@ -10,6 +10,7 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p
 * Dylan 鐙珛寮鍙戣 dinguangx@163.com
 * Kangfoo 鐙珛寮鍙戣
 
+鏈夋妧鏈棶棰樿绉绘姝ゅ璁ㄨ https://github.com/dangdangdotcom/dubbox/issues
 
 ## Dubbox褰撳墠鐨勪富瑕佸姛鑳
 

From d7b5bafa7dabcd4c899e90553eedc0deaa8b7f48 Mon Sep 17 00:00:00 2001
From: Renjie Xu 
Date: Sun, 18 Dec 2016 00:14:53 +0800
Subject: [PATCH 197/200] throw right exception literals when generating
 adaptive class method signature

---
 .../com/alibaba/dubbo/common/extension/ExtensionLoader.java     | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java
index 89080bf64fca..982ab819eba5 100644
--- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java
+++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/extension/ExtensionLoader.java
@@ -931,7 +931,7 @@ private String createAdaptiveExtensionClassCode() {
                     if (i > 0) {
                         codeBuidler.append(", ");
                     }
-                    codeBuidler.append(pts[i].getCanonicalName());
+                    codeBuidler.append(ets[i].getCanonicalName());
                 }
             }
             codeBuidler.append(" {");

From 508eaad3dfb423fd3d68a066e00ab9450151cf44 Mon Sep 17 00:00:00 2001
From: Chenpz 
Date: Fri, 23 Dec 2016 09:33:13 +0800
Subject: [PATCH 198/200] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=96=87=E6=A1=A3?=
 =?UTF-8?q?=E8=AE=BF=E9=97=AE=E9=93=BE=E6=8E=A5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 README.md | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/README.md b/README.md
index 888c4848ef74..74856b9e19bc 100644
--- a/README.md
+++ b/README.md
@@ -36,15 +36,15 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p
 
 ## 鏂囨。璧勬枡
 
-[鍦―ubbo涓紑鍙慠EST椋庢牸鐨勮繙绋嬭皟鐢紙RESTful Remoting锛塢(http://dangdangdotcom.github.io/dubbox/rest.html)
+[鍦―ubbo涓紑鍙慠EST椋庢牸鐨勮繙绋嬭皟鐢紙RESTful Remoting锛塢(https://dangdangdotcom.github.io/dubbox/rest.html)
 
-[鍦―ubbo涓娇鐢ㄩ珮鏁堢殑Java搴忓垪鍖栵紙Kryo鍜孎ST锛塢(http://dangdangdotcom.github.io/dubbox/serialization.html)
+[鍦―ubbo涓娇鐢ㄩ珮鏁堢殑Java搴忓垪鍖栵紙Kryo鍜孎ST锛塢(https://dangdangdotcom.github.io/dubbox/serialization.html)
 
-[浣跨敤JavaConfig鏂瑰紡閰嶇疆dubbox](http://dangdangdotcom.github.io/dubbox/java-config.html)
+[浣跨敤JavaConfig鏂瑰紡閰嶇疆dubbox](https://dangdangdotcom.github.io/dubbox/java-config.html)
 
-[Dubbo Jackson搴忓垪鍖栦娇鐢ㄨ鏄嶿(http://dangdangdotcom.github.io/dubbox/jackson.html)
+[Dubbo Jackson搴忓垪鍖栦娇鐢ㄨ鏄嶿(https://dangdangdotcom.github.io/dubbox/jackson.html)
 
-[Demo搴旂敤绠鍗曡繍琛屾寚鍗梋(http://dangdangdotcom.github.io/dubbox/demo.html)
+[Demo搴旂敤绠鍗曡繍琛屾寚鍗梋(https://dangdangdotcom.github.io/dubbox/demo.html)
 
 [Dubbox@InfoQ](http://www.infoq.com/cn/news/2014/10/dubbox-open-source) 
 

From 378e36bc9c23a7573ed0c30aeb2fee95e9e1c22e Mon Sep 17 00:00:00 2001
From: donhui <977675308@qq.com>
Date: Thu, 19 Jan 2017 14:51:21 +0800
Subject: [PATCH 199/200] modify helpUrl
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

淇敼甯姪URL锛屽師鏉ョ殑宸插け鏁
---
 .../alibaba/dubbo/governance/web/home/module/control/Menu.java  | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/control/Menu.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/control/Menu.java
index 9961e0e27019..92408bc53bd0 100644
--- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/control/Menu.java
+++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/home/module/control/Menu.java
@@ -49,7 +49,7 @@ public void execute(HttpSession session, Context context, CookieParser parser) {
         	context.put("bucLogoutAddress", rootContextPath.getURI("logout"));
         }
         if (! context.containsKey("helpUrl")) {
-        	context.put("helpUrl", "http://code.alibabatech.com/wiki/display/dubbo");
+        	context.put("helpUrl", "https://github.com/dangdangdotcom/dubbox/wiki");
         }
         context.put(WebConstants.CURRENT_USER_KEY, user);
         context.put("language", parser.getString("locale"));

From 902ed2b401d27d8054b8e67324ddfc2df4ec9f79 Mon Sep 17 00:00:00 2001
From: liuwei 
Date: Fri, 17 Mar 2017 11:14:54 +0800
Subject: [PATCH 200/200] High-risk: update fastjson to 1.2.28

---
 pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/pom.xml b/pom.xml
index 2f1517bd3c93..cb07bff9a292 100644
--- a/pom.xml
+++ b/pom.xml
@@ -92,7 +92,7 @@
 		4.2.1
 		3.2.1-fixed-2
 		1.4.1
-		1.1.39
+		1.2.28
 		3.1
 		0.8
 		3.4.6