diff --git a/.gitignore b/.gitignore index af3d4f9128b..3b9e19e1c5b 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ target/ *.iws # temp ignore +log.* *.log *.cache *.diff diff --git a/README.md b/README.md index 8be6642a82d..cb9cf50c15f 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,8 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p * **修正了dubbo的bug** 包括配置、序列化、管理界面等等的bug。 +* **支持原生thrift、avro等跨语言的rpc框架**(2.8.4a版开始支持),只是非java语言的client调用dubbo的thrift/avro服务时,consumer无法享受dubbo的治理功能 + **注:dubbox和dubbo 2.x是兼容的,没有改变dubbo的任何已有的功能和配置方式(除了升级了spring之类的版本)** ## 文档资料 @@ -70,6 +72,16 @@ Dubbox adds features like RESTful remoting, Kyro/FST serialization, etc to the p * 修正Dubbo管理界面中没有consumer时出现空指针异常(马金凯) * 修正@Reference annotation中protocol设置不起作用的bug(沈理) * 修正@Reference annotation放在setter方法上即会出错的bug(Dylan) +* **dubbox-2.8.4a**: + * 升级spring到4.x,其它一些依赖组件也一并进行了版本升级(杨俊明) + * 增加log4j2支持,原来一些硬编码依赖log4j的代码,改为依赖slf4j,以便兼容其它一些主流日志组件(杨俊明) + * 增加原生thrift支持,升级thrift到0.9.3,为避免与dubbo原来的thrift实现命名冲突,新增的原生thrift协议,协议名称改为thrift2(杨俊明) + * 增加hadoop avro支持(杨俊明) +* **dubbox-2.8.5**: + * 编译时去掉了一些不常用的模块,以加快项目整体的编译速度(杨俊明) + * 增加了google-gRPC-1.0.1的支持,目前仅处于“玩票”阶段,生产环境请慎用(杨俊明) + * 重写了dubbo-demo模块,提供了rest/dubbo/avro/thrift/grpc五种协议的基本示例(杨俊明) + * 将zkclient 0.8.1加入项目中,避免大家编译时,要先去pull另一个项目(杨俊明) ## 依赖 diff --git a/dubbo-admin/pom.xml b/dubbo-admin/pom.xml index ec2a30be84a..7336b3616c9 100644 --- a/dubbo-admin/pom.xml +++ b/dubbo-admin/pom.xml @@ -1,12 +1,12 @@ - 4.0.0 - - com.alibaba - dubbo-parent - 2.8.4 - - dubbo-admin - war - ${project.artifactId} - The admin module of dubbo project - - 1.5 - / - false - false - - - - com.alibaba - dubbo - ${project.parent.version} - - - com.alibaba.citrus - citrus-webx-all - - - org.javassist - javassist - - - io.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.thrift - libthrift - - - com.caucho - hessian - - - javax.servlet - javax.servlet-api - provided - - - log4j - log4j - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - redis.clients - jedis - - - javax.validation - validation-api - - - org.hibernate - hibernate-validator - - - javax.cache - cache-api - - - - - - org.mortbay.jetty - maven-jetty-plugin - ${jetty_version} - - / - 10 - - - 8080 - 60000 - - - - - - + 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.4a + + dubbo-admin + war + ${project.artifactId} + The admin module of dubbo project + + 1.5 + / + false + false + 8.1.15.v20140411 + 3.2.16.RELEASE + + + + com.alibaba + dubbo + ${project.parent.version} + + + com.alibaba.citrus + citrus-webx-all + + + org.javassist + javassist + + + io.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.alibaba + zkclient + + + org.apache.curator + curator-framework + + + com.googlecode.xmemcached + xmemcached + + + org.apache.thrift + libthrift + + + com.caucho + hessian + + + javax.servlet + javax.servlet-api + provided + + + log4j + log4j + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + redis.clients + jedis + + + javax.validation + validation-api + + + org.hibernate + hibernate-validator + + + javax.cache + cache-api + + + org.apache.velocity + velocity + + + + + + + org.apache.tomcat.maven + tomcat7-maven-plugin + 2.2 + + 8080 + / + + + + org.mortbay.jetty + jetty-maven-plugin + ${maven-jetty-plugin_version} + + + + 8080 + + + exit + 9090 + 10 + + /${project.artifactId} + + + + + + + diff --git a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Restful.java b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Restful.java index f5d385dbaf0..cb7ad262424 100644 --- a/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Restful.java +++ b/dubbo-admin/src/main/java/com/alibaba/dubbo/governance/web/common/module/screen/Restful.java @@ -7,6 +7,14 @@ */ package com.alibaba.dubbo.governance.web.common.module.screen; +import com.alibaba.dubbo.common.utils.CompatibleTypeUtils; +import com.alibaba.dubbo.governance.biz.common.i18n.MessageResourceService; +import com.alibaba.dubbo.governance.web.common.pulltool.RootContextPath; +import com.alibaba.dubbo.governance.web.util.WebConstants; +import com.alibaba.dubbo.registry.common.domain.User; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -14,89 +22,79 @@ import java.util.Map; import java.util.regex.Pattern; -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; - -import com.alibaba.dubbo.common.utils.CompatibleTypeUtils; -import com.alibaba.dubbo.governance.biz.common.i18n.MessageResourceService; -import com.alibaba.dubbo.governance.web.common.pulltool.RootContextPath; -import com.alibaba.dubbo.governance.web.util.WebConstants; -import com.alibaba.dubbo.registry.common.domain.User; - /** * BaseScreen - * + * * @author william.liangf */ public abstract class Restful { - - protected static final Logger logger = Logger.getLogger(Restful.class); - - protected static final Pattern SPACE_SPLIT_PATTERN = Pattern.compile("\\s+"); - - @Autowired - private MessageResourceService messageResourceService; - - public String getMessage(String key, Object... args) { - return messageResourceService.getMessage(key, args); - } - - //FIXME 把这些辅助方法提取出去 - protected String role = null; - protected String operator = null; - protected User currentUser = null; - protected String operatorAddress = null; - protected String currentRegistry = null; - + + protected static final Logger logger = LoggerFactory.getLogger(Restful.class); + + protected static final Pattern SPACE_SPLIT_PATTERN = Pattern.compile("\\s+"); + + @Autowired + private MessageResourceService messageResourceService; + + public String getMessage(String key, Object... args) { + return messageResourceService.getMessage(key, args); + } + + //FIXME 把这些辅助方法提取出去 + protected String role = null; + protected String operator = null; + protected User currentUser = null; + protected String operatorAddress = null; + protected String currentRegistry = null; + public void execute(Map context) throws Throwable { - if(context.get(WebConstants.CURRENT_USER_KEY)!=null){ - User user = (User) context.get(WebConstants.CURRENT_USER_KEY); - currentUser = user; - operator = user.getUsername(); - role = user.getRole(); - context.put(WebConstants.CURRENT_USER_KEY, user); + if (context.get(WebConstants.CURRENT_USER_KEY) != null) { + User user = (User) context.get(WebConstants.CURRENT_USER_KEY); + currentUser = user; + operator = user.getUsername(); + role = user.getRole(); + context.put(WebConstants.CURRENT_USER_KEY, user); } - operatorAddress = (String)context.get("request.remoteHost"); + operatorAddress = (String) context.get("request.remoteHost"); context.put("operator", operator); - context.put("operatorAddress", operatorAddress); - + context.put("operatorAddress", operatorAddress); + context.put("currentRegistry", currentRegistry); - + String httpMethod = (String) context.get("request.method"); String method = (String) context.get("_method"); String contextPath = (String) context.get("request.contextPath"); context.put("rootContextPath", new RootContextPath(contextPath)); - + // 分析Method if (method == null || method.length() == 0) { String id = (String) context.get("id"); - if(id == null || id.length() == 0) { + if (id == null || id.length() == 0) { method = "index"; - } - else { + } else { method = "show"; } } if ("index".equals(method)) { - if("post".equalsIgnoreCase(httpMethod)) { + if ("post".equalsIgnoreCase(httpMethod)) { method = "create"; } } else if ("show".equals(method)) { - if("put".equalsIgnoreCase(httpMethod) || "post".equalsIgnoreCase(httpMethod)) { // 因表单不能提交PUT请求,用POST代替 + if ("put".equalsIgnoreCase(httpMethod) || "post".equalsIgnoreCase(httpMethod)) { // 因表单不能提交PUT请求,用POST代替 method = "update"; } else if ("delete".equalsIgnoreCase(httpMethod)) { // 因表单不能提交DELETE请求,用参数代替 method = "delete"; } } context.put("_method", method); - + try { Method m = null; try { m = getClass().getMethod(method, new Class[]{Map.class}); } catch (NoSuchMethodException e) { for (Method mtd : getClass().getMethods()) { - if (Modifier.isPublic(mtd.getModifiers()) + if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().equals(method)) { m = mtd; break; @@ -109,8 +107,8 @@ public void execute(Map context) throws Throwable { if (m.getParameterTypes().length > 2) { throw new IllegalStateException("Unsupport restful method " + m); } else if (m.getParameterTypes().length == 2 - && (m.getParameterTypes()[0].equals(Map.class) - || ! m.getParameterTypes()[1].equals(Map.class))) { + && (m.getParameterTypes()[0].equals(Map.class) + || !m.getParameterTypes()[1].equals(Map.class))) { throw new IllegalStateException("Unsupport restful method " + m); } Object r; @@ -128,13 +126,13 @@ public void execute(Map context) throws Throwable { String id = (String) context.get("id"); String[] ids = id == null ? new String[0] : id.split("[.+]+"); value = Array.newInstance(t.getComponentType(), ids.length); - for (int i = 0; i < ids.length; i ++) { + for (int i = 0; i < ids.length; i++) { Array.set(value, i, convertPrimitive(t.getComponentType(), ids[i])); } } else { value = t.newInstance(); for (Method mtd : t.getMethods()) { - if (Modifier.isPublic(mtd.getModifiers()) + if (Modifier.isPublic(mtd.getModifiers()) && mtd.getName().startsWith("set") && mtd.getParameterTypes().length == 1) { String p = mtd.getName().substring(3, 4).toLowerCase() + mtd.getName().substring(4); @@ -147,39 +145,39 @@ public void execute(Map context) throws Throwable { } } if (v != null) { - try { - mtd.invoke(value, new Object[] { CompatibleTypeUtils.compatibleTypeConvert(v, mtd.getParameterTypes()[0]) }); - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - } + try { + mtd.invoke(value, new Object[]{CompatibleTypeUtils.compatibleTypeConvert(v, mtd.getParameterTypes()[0])}); + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + } } } } } if (m.getParameterTypes().length == 1) { - r = m.invoke(this, new Object[] {value}); + r = m.invoke(this, new Object[]{value}); } else { - r = m.invoke(this, new Object[] {value, context}); + r = m.invoke(this, new Object[]{value, context}); } } if (m.getReturnType() == boolean.class || m.getReturnType() == Boolean.class) { context.put("rundata.layout", "redirect"); context.put("rundata.target", "redirect"); context.put("success", r == null || ((Boolean) r).booleanValue()); - if(context.get("redirect")==null){ - context.put("redirect", getDefaultRedirect(context, method)); + if (context.get("redirect") == null) { + context.put("redirect", getDefaultRedirect(context, method)); } } else if (m.getReturnType() == String.class) { String redirect = (String) r; if (redirect == null) { redirect = getDefaultRedirect(context, method); } - - if(context.get("chain")!=null){ - context.put("rundata.layout", "home"); + + if (context.get("chain") != null) { + context.put("rundata.layout", "home"); context.put("rundata.target", "home"); - }else{ - context.put("rundata.redirect", redirect); + } else { + context.put("rundata.redirect", redirect); } } else { context.put("rundata.layout", method); @@ -200,14 +198,14 @@ public void execute(Map context) throws Throwable { // context.put("redirect", getDefaultRedirect(context, method)); } } - - private static boolean isPrimitive(Class cls) { - return cls.isPrimitive()|| cls == Boolean.class || cls == Byte.class + + private static boolean isPrimitive(Class cls) { + return cls.isPrimitive() || cls == Boolean.class || cls == Byte.class || cls == Character.class || cls == Short.class || cls == Integer.class || cls == Long.class || cls == Float.class || cls == Double.class || cls == String.class; } - + private static Object convertPrimitive(Class cls, String value) { if (cls == boolean.class || cls == Boolean.class) { return value == null || value.length() == 0 ? false : Boolean.valueOf(value); @@ -228,10 +226,10 @@ private static Object convertPrimitive(Class cls, String value) { } return value; } - + private String getDefaultRedirect(Map context, String operate) { String defaultRedirect = (String) context.get("defaultRedirect"); - return defaultRedirect; + return defaultRedirect; } - + } diff --git a/dubbo-admin/src/main/webapp/WEB-INF/applicationContext.xml b/dubbo-admin/src/main/webapp/WEB-INF/applicationContext.xml new file mode 100644 index 00000000000..142def25af2 --- /dev/null +++ b/dubbo-admin/src/main/webapp/WEB-INF/applicationContext.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/dubbo.properties b/dubbo-admin/src/main/webapp/WEB-INF/dubbo.properties index c1ec1b3bc23..5b2d27c643e 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/dubbo.properties +++ b/dubbo-admin/src/main/webapp/WEB-INF/dubbo.properties @@ -1,3 +1,3 @@ -dubbo.registry.address=zookeeper://127.0.0.1:2181 +dubbo.registry.address=zookeeper://127.0.0.1:2181?backup=127.0.0.1:2182,127.0.0.1:2183 dubbo.admin.root.password=root dubbo.admin.guest.password=guest \ No newline at end of file diff --git a/dubbo-admin/src/main/webapp/WEB-INF/log4j.xml b/dubbo-admin/src/main/webapp/WEB-INF/log4j.xml index e0f2f4404a0..71b1b9b9109 100644 --- a/dubbo-admin/src/main/webapp/WEB-INF/log4j.xml +++ b/dubbo-admin/src/main/webapp/WEB-INF/log4j.xml @@ -1,29 +1,16 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-cluster/pom.xml b/dubbo-cluster/pom.xml index ec6af560cb0..20e2db2570b 100644 --- a/dubbo-cluster/pom.xml +++ b/dubbo-cluster/pom.xml @@ -19,7 +19,8 @@ com.alibaba dubbo-parent - 2.8.4 + + 2.8.5-SNAPSHOT dubbo-cluster jar diff --git a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/condition/ConditionRouter.java b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/condition/ConditionRouter.java index d9bca59ef20..1e0e34120e8 100644 --- a/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/condition/ConditionRouter.java +++ b/dubbo-cluster/src/main/java/com/alibaba/dubbo/rpc/cluster/router/condition/ConditionRouter.java @@ -52,9 +52,9 @@ public class ConditionRouter implements Router, Comparable { private final boolean force; - private final Map whenCondition; + private final Map whenCondition; //消费端匹配 - private final Map thenCondition; + private final Map thenCondition; //提供端过滤 public ConditionRouter(URL url) { this.url = url; @@ -79,18 +79,39 @@ public ConditionRouter(URL url) { } } + public boolean hasWhenCondition() { + return whenCondition != null && whenCondition.size() > 0; + } + + public boolean hasThenCondition() { + return thenCondition != null && thenCondition.size() > 0; + } + + /** + * 路由规则逻辑 + * 1. 必须同时配置 消费端匹配 和 提供端过滤 + * 2. 消费端不匹配 返回所有 invoker + * + * @param invokers + * @param url refer url + * @param invocation + * @param + * @return + * @throws RpcException + */ public List> route(List> invokers, URL url, Invocation invocation) throws RpcException { if (invokers == null || invokers.size() == 0) { return invokers; } try { - if (! matchWhen(url)) { + //消费端匹配 如果不匹配 直接返回所有invoker + if (!matchWhen(url)) { return invokers; } List> result = new ArrayList>(); - if (thenCondition == null) { - logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey()); + if (!hasThenCondition()) { + logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey()); return result; } for (Invoker invoker : invokers) { @@ -101,8 +122,8 @@ public List> route(List> invokers, URL url, Invocation if (result.size() > 0) { return result; } else if (force) { - logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY)); - return result; + logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY)); + return result; } } catch (Throwable t) { logger.error("Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(), t); @@ -135,8 +156,14 @@ private boolean matchCondition(Map condition, URL url, URL pa for (Map.Entry entry : sample.entrySet()) { String key = entry.getKey(); MatchPair pair = condition.get(key); - if (pair != null && ! pair.isMatch(entry.getValue(), param)) { - return false; + if (param == null) { + if (pair != null && !pair.isMatch(entry.getValue())) { + return false; + } + } else { + if (pair != null && !pair.isMatch(entry.getValue(), param)) { + return false; + } } } return true; @@ -214,6 +241,7 @@ else if (",".equals(separator)) { // 如果为逗号表示 private static final class MatchPair { final Set matches = new HashSet(); final Set mismatches = new HashSet(); + public boolean isMatch(String value, URL param) { for (String match : matches) { if (! UrlUtils.isMatchGlobPattern(match, value, param)) { @@ -227,5 +255,20 @@ public boolean isMatch(String value, URL param) { } return true; } + + + public boolean isMatch(String value) { + for (String match : matches) { + if (!UrlUtils.isMatchGlobPattern(match, value)) { + return false; + } + } + for (String mismatch : mismatches) { + if (UrlUtils.isMatchGlobPattern(mismatch, value)) { + return false; + } + } + return true; + } } } \ No newline at end of file diff --git a/dubbo-common/pom.xml b/dubbo-common/pom.xml index 0d5e9f761de..d156d50b4d8 100644 --- a/dubbo-common/pom.xml +++ b/dubbo-common/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 2.8.5-SNAPSHOT dubbo-common jar @@ -43,6 +43,10 @@ log4j log4j + + org.apache.logging.log4j + log4j-core + org.javassist javassist diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/URL.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/URL.java index 6a275e314c8..cdacfa06a75 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/URL.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/URL.java @@ -235,6 +235,7 @@ public static URL valueOf(String url) { url = url.substring(i + 1); } i = url.indexOf(":"); + //fe80:0:0:0:fc83:51ff:fe41:9c76%9:20880 此处有bug,如果是ipv6就挂了 if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/LoggerFactory.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/LoggerFactory.java index 3bb6addc10e..509e2d1be71 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/LoggerFactory.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/LoggerFactory.java @@ -1,154 +1,154 @@ -/* - * 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.logger; -import java.io.File; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.common.logger.jcl.JclLoggerAdapter; -import com.alibaba.dubbo.common.logger.jdk.JdkLoggerAdapter; -import com.alibaba.dubbo.common.logger.log4j.Log4jLoggerAdapter; -import com.alibaba.dubbo.common.logger.slf4j.Slf4jLoggerAdapter; -import com.alibaba.dubbo.common.logger.support.FailsafeLogger; +import com.alibaba.dubbo.common.extension.ExtensionLoader; +import com.alibaba.dubbo.common.logger.jcl.JclLoggerAdapter; +import com.alibaba.dubbo.common.logger.jdk.JdkLoggerAdapter; +import com.alibaba.dubbo.common.logger.log4j.Log4jLoggerAdapter; +import com.alibaba.dubbo.common.logger.log4j2.Log4j2LoggerAdapter; +import com.alibaba.dubbo.common.logger.slf4j.Slf4jLoggerAdapter; +import com.alibaba.dubbo.common.logger.support.FailsafeLogger; + +import java.io.File; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; /** * 日志输出器工厂 - * + * * @author william.liangf */ public class LoggerFactory { - private LoggerFactory() { - } + private LoggerFactory() { + } + + private static volatile LoggerAdapter LOGGER_ADAPTER; + + private static final ConcurrentMap LOGGERS = new ConcurrentHashMap(); + + // 查找常用的日志框架 + static { + String logger = System.getProperty("dubbo.application.logger"); + if ("slf4j".equals(logger)) { + setLoggerAdapter(new Slf4jLoggerAdapter()); + } else if ("jcl".equals(logger)) { + setLoggerAdapter(new JclLoggerAdapter()); + } else if ("log4j".equals(logger)) { + setLoggerAdapter(new Log4jLoggerAdapter()); + } else if ("log4j2".equals(logger)) { + setLoggerAdapter(new Log4j2LoggerAdapter()); + } else if ("jdk".equals(logger)) { + setLoggerAdapter(new JdkLoggerAdapter()); + } else { + try { + setLoggerAdapter(new Log4j2LoggerAdapter());//默认日志类改成log4j2(杨俊明) + } catch (Throwable e1) { + try { + setLoggerAdapter(new Slf4jLoggerAdapter()); + } catch (Throwable e2) { + try { + setLoggerAdapter(new JclLoggerAdapter()); + } catch (Throwable e3) { + setLoggerAdapter(new JdkLoggerAdapter()); + } + } + } + } + } + + public static void setLoggerAdapter(String loggerAdapter) { + if (loggerAdapter != null && loggerAdapter.length() > 0) { + setLoggerAdapter(ExtensionLoader.getExtensionLoader(LoggerAdapter.class).getExtension(loggerAdapter)); + } + } - private static volatile LoggerAdapter LOGGER_ADAPTER; - - private static final ConcurrentMap LOGGERS = new ConcurrentHashMap(); + /** + * 设置日志输出器供给器 + * + * @param loggerAdapter 日志输出器供给器 + */ + public static void setLoggerAdapter(LoggerAdapter loggerAdapter) { + if (loggerAdapter != null) { + Logger logger = loggerAdapter.getLogger(LoggerFactory.class.getName()); + logger.info("using logger: " + loggerAdapter.getClass().getName()); + LoggerFactory.LOGGER_ADAPTER = loggerAdapter; + for (Map.Entry entry : LOGGERS.entrySet()) { + entry.getValue().setLogger(LOGGER_ADAPTER.getLogger(entry.getKey())); + } + } + } - // 查找常用的日志框架 - static { - String logger = System.getProperty("dubbo.application.logger"); - if ("slf4j".equals(logger)) { - setLoggerAdapter(new Slf4jLoggerAdapter()); - } else if ("jcl".equals(logger)) { - setLoggerAdapter(new JclLoggerAdapter()); - } else if ("log4j".equals(logger)) { - setLoggerAdapter(new Log4jLoggerAdapter()); - } else if ("jdk".equals(logger)) { - setLoggerAdapter(new JdkLoggerAdapter()); - } else { - try { - setLoggerAdapter(new Log4jLoggerAdapter()); - } catch (Throwable e1) { - try { - setLoggerAdapter(new Slf4jLoggerAdapter()); - } catch (Throwable e2) { - try { - setLoggerAdapter(new JclLoggerAdapter()); - } catch (Throwable e3) { - setLoggerAdapter(new JdkLoggerAdapter()); - } - } - } - } - } - - public static void setLoggerAdapter(String loggerAdapter) { - if (loggerAdapter != null && loggerAdapter.length() > 0) { - setLoggerAdapter(ExtensionLoader.getExtensionLoader(LoggerAdapter.class).getExtension(loggerAdapter)); - } - } + /** + * 获取日志输出器 + * + * @param key 分类键 + * @return 日志输出器, 后验条件: 不返回null. + */ + public static Logger getLogger(Class key) { + FailsafeLogger logger = LOGGERS.get(key.getName()); + if (logger == null) { + LOGGERS.putIfAbsent(key.getName(), new FailsafeLogger(LOGGER_ADAPTER.getLogger(key))); + logger = LOGGERS.get(key.getName()); + } + return logger; + } - /** - * 设置日志输出器供给器 - * - * @param loggerAdapter - * 日志输出器供给器 - */ - public static void setLoggerAdapter(LoggerAdapter loggerAdapter) { - if (loggerAdapter != null) { - Logger logger = loggerAdapter.getLogger(LoggerFactory.class.getName()); - logger.info("using logger: " + loggerAdapter.getClass().getName()); - LoggerFactory.LOGGER_ADAPTER = loggerAdapter; - for (Map.Entry entry : LOGGERS.entrySet()) { - entry.getValue().setLogger(LOGGER_ADAPTER.getLogger(entry.getKey())); - } - } - } + /** + * 获取日志输出器 + * + * @param key 分类键 + * @return 日志输出器, 后验条件: 不返回null. + */ + public static Logger getLogger(String key) { + FailsafeLogger logger = LOGGERS.get(key); + if (logger == null) { + LOGGERS.putIfAbsent(key, new FailsafeLogger(LOGGER_ADAPTER.getLogger(key))); + logger = LOGGERS.get(key); + } + return logger; + } - /** - * 获取日志输出器 - * - * @param key - * 分类键 - * @return 日志输出器, 后验条件: 不返回null. - */ - public static Logger getLogger(Class key) { - FailsafeLogger logger = LOGGERS.get(key.getName()); - if (logger == null) { - LOGGERS.putIfAbsent(key.getName(), new FailsafeLogger(LOGGER_ADAPTER.getLogger(key))); - logger = LOGGERS.get(key.getName()); - } - return logger; - } + /** + * 动态设置输出日志级别 + * + * @param level 日志级别 + */ + public static void setLevel(Level level) { + LOGGER_ADAPTER.setLevel(level); + } - /** - * 获取日志输出器 - * - * @param key - * 分类键 - * @return 日志输出器, 后验条件: 不返回null. - */ - public static Logger getLogger(String key) { - FailsafeLogger logger = LOGGERS.get(key); - if (logger == null) { - LOGGERS.putIfAbsent(key, new FailsafeLogger(LOGGER_ADAPTER.getLogger(key))); - logger = LOGGERS.get(key); - } - return logger; - } - - /** - * 动态设置输出日志级别 - * - * @param level 日志级别 - */ - public static void setLevel(Level level) { - LOGGER_ADAPTER.setLevel(level); - } + /** + * 获取日志级别 + * + * @return 日志级别 + */ + public static Level getLevel() { + return LOGGER_ADAPTER.getLevel(); + } - /** - * 获取日志级别 - * - * @return 日志级别 - */ - public static Level getLevel() { - return LOGGER_ADAPTER.getLevel(); - } - - /** - * 获取日志文件 - * - * @return 日志文件 - */ - public static File getFile() { - return LOGGER_ADAPTER.getFile(); - } + /** + * 获取日志文件 + * + * @return 日志文件 + */ + public static File getFile() { + return LOGGER_ADAPTER.getFile(); + } } \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/log4j2/Log4j2Logger.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/log4j2/Log4j2Logger.java new file mode 100644 index 00000000000..636e4f684ef --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/log4j2/Log4j2Logger.java @@ -0,0 +1,100 @@ + +package com.alibaba.dubbo.common.logger.log4j2; + +import com.alibaba.dubbo.common.logger.Logger; + +/** + * author: yangjunming (http://yjmyzz.cnblogs.com/) + * since: 2016-02-24 + */ +public class Log4j2Logger implements Logger { + + //private static final String FQCN = FailsafeLogger.class.getName(); + + private final org.slf4j.Logger logger; + + public Log4j2Logger(org.slf4j.Logger logger) { + this.logger = logger; + } + + public void trace(String msg) { + logger.trace(msg); + } + + public void trace(Throwable e) { + logger.trace(e == null ? null : e.getMessage()); + } + + public void trace(String msg, Throwable e) { + logger.trace(msg, e); + } + + public void debug(String msg) { + logger.debug(msg); + } + + public void debug(Throwable e) { + logger.debug(e == null ? null : e.getMessage()); + } + + public void debug(String msg, Throwable e) { + logger.debug(msg, e); + } + + public void info(String msg) { + logger.info(msg); + } + + public void info(Throwable e) { + logger.info(e == null ? null : e.getMessage()); + } + + public void info(String msg, Throwable e) { + logger.info(msg, e); + } + + public void warn(String msg) { + logger.warn(msg); + } + + public void warn(Throwable e) { + logger.warn(e == null ? null : e.getMessage()); + } + + public void warn(String msg, Throwable e) { + logger.warn(msg, e); + } + + public void error(String msg) { + logger.error(msg); + } + + public void error(Throwable e) { + logger.error(e == null ? null : e.getMessage()); + } + + public void error(String msg, Throwable e) { + logger.error(msg, e); + } + + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } + + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } + + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } + + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } + + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } + +} \ No newline at end of file diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/log4j2/Log4j2LoggerAdapter.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/log4j2/Log4j2LoggerAdapter.java new file mode 100644 index 00000000000..2d1a014d1c1 --- /dev/null +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/logger/log4j2/Log4j2LoggerAdapter.java @@ -0,0 +1,105 @@ +package com.alibaba.dubbo.common.logger.log4j2; + +import com.alibaba.dubbo.common.logger.Level; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerAdapter; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.appender.FileAppender; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.LoggerConfig; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.Map; + +public class Log4j2LoggerAdapter implements LoggerAdapter { + + @SuppressWarnings("unchecked") + public Log4j2LoggerAdapter() { + try { + org.apache.logging.log4j.Logger logger = LogManager.getLogger(); + if (logger != null) { + Map appenderMap = + ((org.apache.logging.log4j.core.Logger) logger).getAppenders(); + for (Map.Entry entry : appenderMap.entrySet()) { + if (entry.getValue() instanceof FileAppender) { + String filename = ((FileAppender) entry.getValue()).getFileName(); + file = new File(filename); + break; + } + } + } + } catch (Throwable t) { + } + } + + public Logger getLogger(String key) { + return new Log4j2Logger(LoggerFactory.getLogger(key)); + } + + public Logger getLogger(Class key) { + return new Log4j2Logger(LoggerFactory.getLogger(key)); + } + + private File file; + + public void setLevel(Level level) { + LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + Configuration config = ctx.getConfiguration(); + LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); + loggerConfig.setLevel(toLog4jLevel(level)); + ctx.updateLoggers(); + } + + public Level getLevel() { + LoggerContext ctx = (LoggerContext) LogManager.getContext(false); + Configuration config = ctx.getConfiguration(); + LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); + return fromLog4jLevel(loggerConfig.getLevel()); + } + + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + + public static org.apache.logging.log4j.Level toLog4jLevel(Level level) { + if (level == Level.ALL) + return org.apache.logging.log4j.Level.ALL; + if (level == Level.TRACE) + return org.apache.logging.log4j.Level.TRACE; + if (level == Level.DEBUG) + return org.apache.logging.log4j.Level.DEBUG; + if (level == Level.INFO) + return org.apache.logging.log4j.Level.INFO; + if (level == Level.WARN) + return org.apache.logging.log4j.Level.WARN; + if (level == Level.ERROR) + return org.apache.logging.log4j.Level.ERROR; + return org.apache.logging.log4j.Level.OFF; + } + + public static Level fromLog4jLevel(org.apache.logging.log4j.Level level) { + if (level == org.apache.logging.log4j.Level.ALL) + return Level.ALL; + if (level == org.apache.logging.log4j.Level.TRACE) + return Level.TRACE; + if (level == org.apache.logging.log4j.Level.DEBUG) + return Level.DEBUG; + if (level == org.apache.logging.log4j.Level.INFO) + return Level.INFO; + if (level == org.apache.logging.log4j.Level.WARN) + return Level.WARN; + if (level == org.apache.logging.log4j.Level.ERROR) + return Level.ERROR; + return Level.OFF; + } + +} 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 index 38b531eadb3..c48ed27d92d 100644 --- 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 @@ -16,9 +16,9 @@ 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 org.nustaq.serialization.FSTConfiguration; +import org.nustaq.serialization.FSTObjectInput; +import org.nustaq.serialization.FSTObjectOutput; import java.io.InputStream; import java.io.OutputStream; 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 index 01fd6ea8dee..fbbcecce612 100644 --- 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 @@ -16,8 +16,7 @@ package com.alibaba.dubbo.common.serialize.support.fst; import com.alibaba.dubbo.common.serialize.ObjectInput; -import de.ruedigermoeller.serialization.FSTObjectInput; - +import org.nustaq.serialization.FSTObjectInput; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; 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 index ba14f041bbd..fadb903135a 100644 --- 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 @@ -16,11 +16,13 @@ package com.alibaba.dubbo.common.serialize.support.fst; import com.alibaba.dubbo.common.serialize.ObjectOutput; -import de.ruedigermoeller.serialization.FSTObjectOutput; +import org.nustaq.serialization.FSTObjectOutput; import java.io.IOException; import java.io.OutputStream; +//import de.ruedigermoeller.serialization.FSTObjectOutput; + /** * @author lishen */ diff --git a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NetUtils.java b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NetUtils.java index a037544e5ab..cb45dc022c1 100644 --- a/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NetUtils.java +++ b/dubbo-common/src/main/java/com/alibaba/dubbo/common/utils/NetUtils.java @@ -15,21 +15,17 @@ */ package com.alibaba.dubbo.common.utils; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; + import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.NetworkInterface; -import java.net.ServerSocket; -import java.net.UnknownHostException; +import java.net.*; import java.util.Enumeration; import java.util.Map; import java.util.Random; import java.util.regex.Pattern; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; - /** * IP and Port Helper for RPC, * @@ -133,6 +129,19 @@ public static boolean isValidLocalHost(String host) { return ! isInvalidLocalHost(host); } + + public static boolean isMulticastAddress(String ip) { + int i = ip.indexOf('.'); + if (i > 0) { + String prefix = ip.substring(0, i); + if (StringUtils.isInteger(prefix)) { + int p = Integer.parseInt(prefix); + return p >= 224 && p <= 239; + } + } + return false; + } + public static InetSocketAddress getLocalSocketAddress(String host, int port) { return isInvalidLocalHost(host) ? new InetSocketAddress(port) : new InetSocketAddress(host, port); diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index d1f6a82c9c8..9ee78f72559 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.5-SNAPSHOT dubbo-config-api jar @@ -72,12 +72,12 @@ ${project.parent.version} test - - com.alibaba - dubbo-rpc-rmi - ${project.parent.version} - test - + + + + + + com.alibaba dubbo-rpc-injvm diff --git a/dubbo-config/dubbo-config-spring/pom.xml b/dubbo-config/dubbo-config-spring/pom.xml index 9732dff29d6..44c5d6f05ee 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.5-SNAPSHOT dubbo-config-spring jar @@ -60,12 +60,12 @@ ${project.parent.version} test - - com.alibaba - dubbo-rpc-rmi - ${project.parent.version} - test - + + + + + + com.alibaba dubbo-rpc-injvm diff --git a/dubbo-config/pom.xml b/dubbo-config/pom.xml index 925195632b1..3cc99c10435 100644 --- a/dubbo-config/pom.xml +++ b/dubbo-config/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 2.8.5-SNAPSHOT dubbo-config pom diff --git a/dubbo-container/dubbo-container-api/pom.xml b/dubbo-container/dubbo-container-api/pom.xml index 3cb4bda94c4..7ae694e8ad7 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.5-SNAPSHOT dubbo-container-api jar diff --git a/dubbo-container/dubbo-container-javaconfig/pom.xml b/dubbo-container/dubbo-container-javaconfig/pom.xml index 3cc3985b60e..9ae9c5c804e 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.5-SNAPSHOT dubbo-container-javaconfig jar diff --git a/dubbo-container/dubbo-container-jetty/pom.xml b/dubbo-container/dubbo-container-jetty/pom.xml index 3fd180fb91a..570d00d2644 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.5-SNAPSHOT dubbo-container-jetty jar diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml index be4637f3263..942f25c9ff9 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.5-SNAPSHOT dubbo-container-log4j jar diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml index a123294937e..f5e7ca2bbcb 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.5-SNAPSHOT dubbo-container-logback jar diff --git a/dubbo-container/dubbo-container-spring/pom.xml b/dubbo-container/dubbo-container-spring/pom.xml index 9564561a899..6ede6fc1a7b 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.5-SNAPSHOT dubbo-container-spring jar diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index b277ac00762..0d30fe7b21e 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 2.8.5-SNAPSHOT dubbo-container pom diff --git a/dubbo-demo/dubbo-demo-api/pom.xml b/dubbo-demo/dubbo-demo-api/pom.xml index a311efe313b..f22c3f5969b 100644 --- a/dubbo-demo/dubbo-demo-api/pom.xml +++ b/dubbo-demo/dubbo-demo-api/pom.xml @@ -19,42 +19,83 @@ com.alibaba dubbo-demo - 2.8.4 + 2.8.5-SNAPSHOT dubbo-demo-api jar ${project.artifactId} The demo module of dubbo project - - true - - - - com.alibaba - dubbo - ${project.parent.version} - - - javax.servlet - javax.servlet-api - - - 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 - - + + + + + kr.motd.maven + os-maven-plugin + 1.4.1.Final + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + 0.5.0 + + com.google.protobuf:protoc:3.0.0:exe:${os.detected.classifier} + grpc-java + io.grpc:protoc-gen-grpc-java:1.0.1:exe:${os.detected.classifier} + + + + + compile + compile-custom + + + + + + + org.apache.thrift.tools + maven-thrift-plugin + 0.1.11 + + /usr/local/bin/thrift + + + + thrift-sources + generate-sources + + compile + + + + thrift-test-sources + generate-test-sources + + testCompile + + + + + + + org.apache.avro + avro-maven-plugin + 1.8.1 + + + schemas + generate-sources + + schema + protocol + idl-protocol + + + + + + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-api/src/main/avro/hello.avdl b/dubbo-demo/dubbo-demo-api/src/main/avro/hello.avdl new file mode 100644 index 00000000000..bf433cf77af --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/avro/hello.avdl @@ -0,0 +1,5 @@ +@namespace ("com.cnblogs.yjmyzz.demo.service.api.avro") +protocol AvroHelloService +{ + string ping(); +} \ No newline at end of file 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 deleted file mode 100644 index 881ba9b49b4..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/SerializationOptimizerImpl.java +++ /dev/null @@ -1,49 +0,0 @@ -/** - * 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 deleted file mode 100644 index 905be3e4cf8..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidRequest.java +++ /dev/null @@ -1,55 +0,0 @@ -/** - * 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 deleted file mode 100644 index e5b26b425de..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidResponse.java +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 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 deleted file mode 100644 index 31ed65d0ad4..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/BidService.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 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 deleted file mode 100644 index 81dcab6960f..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Device.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * 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 deleted file mode 100644 index ddbe6b2e547..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Geo.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * 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/extension/ClientTraceFilter.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/ClientTraceFilter.java deleted file mode 100644 index 8796e71b880..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/ClientTraceFilter.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 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/CustomExceptionMapper.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/CustomExceptionMapper.java deleted file mode 100644 index 82397901ab9..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/CustomExceptionMapper.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 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-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 deleted file mode 100644 index 27e6521bd80..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/DynamicTraceBinding.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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 deleted file mode 100644 index f8b8203e01c..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/DynamicTraceInterceptor.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 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 deleted file mode 100644 index 91277002837..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/TraceFilter.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 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 deleted file mode 100644 index f8c25fc585b..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/extension/TraceInterceptor.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 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 deleted file mode 100644 index 297e7915e21..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/hello/HelloService.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * 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 deleted file mode 100644 index eb5a3b86f3c..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/User.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * 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.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/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 deleted file mode 100644 index 74782f25c6e..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/UserService.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 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 deleted file mode 100644 index 91ab166133e..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestService.java +++ /dev/null @@ -1,30 +0,0 @@ -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.validation.constraints.Min; -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({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) -public interface AnotherUserRestService { - - @GET - @Path("{id : \\d+}") - User getUser(@PathParam("id") @Min(1L) 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 deleted file mode 100644 index 1924ed0c805..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/RegistrationResult.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 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 deleted file mode 100644 index 87f28fcd982..00000000000 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestService.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 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.validation.constraints.Min; - -/** - * 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(@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-api/src/main/java/com/cnblogs/yjmyzz/demo/service/api/dubbo/DubboHelloService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/cnblogs/yjmyzz/demo/service/api/dubbo/DubboHelloService.java new file mode 100644 index 00000000000..6f03196df81 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/cnblogs/yjmyzz/demo/service/api/dubbo/DubboHelloService.java @@ -0,0 +1,11 @@ +package com.cnblogs.yjmyzz.demo.service.api.dubbo; + +/** + * Created by yangjunming on 2016/11/2. + */ +public interface DubboHelloService { + + String ping(); + + String register(User user); +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/cnblogs/yjmyzz/demo/service/api/dubbo/User.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/cnblogs/yjmyzz/demo/service/api/dubbo/User.java new file mode 100644 index 00000000000..f6996a30e5d --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/cnblogs/yjmyzz/demo/service/api/dubbo/User.java @@ -0,0 +1,37 @@ +package com.cnblogs.yjmyzz.demo.service.api.dubbo; + +import java.io.Serializable; + +/** + * Created by yangjunming on 2016/11/2. + */ +public class User implements Serializable { + + private int userId; + + private String userName; + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + @Override + public String toString() { + return "User{" + + "userId=" + userId + + ", userName='" + userName + '\'' + + '}'; + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/cnblogs/yjmyzz/demo/service/api/rest/RestHelloService.java b/dubbo-demo/dubbo-demo-api/src/main/java/com/cnblogs/yjmyzz/demo/service/api/rest/RestHelloService.java new file mode 100644 index 00000000000..b99991365d6 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/java/com/cnblogs/yjmyzz/demo/service/api/rest/RestHelloService.java @@ -0,0 +1,24 @@ +package com.cnblogs.yjmyzz.demo.service.api.rest; + +import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType; +import com.cnblogs.yjmyzz.demo.service.api.dubbo.User; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + +/** + * Created by yangjunming on 2016/11/2. + */ +@Path("demo") +@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) +@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) +public interface RestHelloService { + + @GET + @Path("/ping") + String ping(); + + @POST + @Path("/reg") + String register(User user); +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/proto/hello.proto b/dubbo-demo/dubbo-demo-api/src/main/proto/hello.proto new file mode 100644 index 00000000000..061ff48b34d --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/proto/hello.proto @@ -0,0 +1,17 @@ +syntax = "proto3"; + +option java_multiple_files = true; +option java_package = "com.cnblogs.yjmyzz.demo.service.api.grpc"; +option java_outer_classname = "GrpcHelloServiceProto"; + +package hello; + +service GrpcHelloService { + rpc ping (PingRequest) returns (PingResponse) {} +} + +message PingRequest{} + +message PingResponse { + string message = 1; +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/thrift/hello.thrift b/dubbo-demo/dubbo-demo-api/src/main/thrift/hello.thrift new file mode 100644 index 00000000000..57b66b20735 --- /dev/null +++ b/dubbo-demo/dubbo-demo-api/src/main/thrift/hello.thrift @@ -0,0 +1,5 @@ +namespace java com.cnblogs.yjmyzz.demo.service.api.thrift + +service ThriftHelloService{ + string ping() +} \ 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 3e2427967bb..3ad4a1c899e 100644 --- a/dubbo-demo/dubbo-demo-consumer/pom.xml +++ b/dubbo-demo/dubbo-demo-consumer/pom.xml @@ -1,25 +1,10 @@ - 4.0.0 com.alibaba dubbo-demo - 2.8.4 + 2.8.5-SNAPSHOT dubbo-demo-consumer jar @@ -34,200 +19,7 @@ dubbo-demo-api ${project.parent.version} - - com.alibaba - dubbo - ${project.parent.version} - - - org.javassist - javassist - - - io.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 - - - 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 - - - - - 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-consumer/src/main/assembly/assembly.xml b/dubbo-demo/dubbo-demo-consumer/src/main/assembly/assembly.xml deleted file mode 100644 index 25235d9064e..00000000000 --- a/dubbo-demo/dubbo-demo-consumer/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-consumer/src/main/assembly/conf/dubbo.properties b/dubbo-demo/dubbo-demo-consumer/src/main/assembly/conf/dubbo.properties deleted file mode 100644 index d3cc21f6af0..00000000000 --- a/dubbo-demo/dubbo-demo-consumer/src/main/assembly/conf/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-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 deleted file mode 100644 index b6138e729ad..00000000000 --- a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoAction.java +++ /dev/null @@ -1,89 +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.consumer; - -import java.util.ArrayList; -import java.util.List; - -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 { - - 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 { - 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("SUCCESS: 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, "larrypage"); - System.out.println("SUCCESS: registered user with id " + anotherUserRestService.registerUser(user).getId()); - - 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-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 deleted file mode 100644 index 636aba17426..00000000000 --- a/dubbo-demo/dubbo-demo-consumer/src/main/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigAction.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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, "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/cnblogs/yjmyzz/demo/service/consumer/DubboDemoConsumer.java b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/cnblogs/yjmyzz/demo/service/consumer/DubboDemoConsumer.java new file mode 100644 index 00000000000..ac642b412c8 --- /dev/null +++ b/dubbo-demo/dubbo-demo-consumer/src/main/java/com/cnblogs/yjmyzz/demo/service/consumer/DubboDemoConsumer.java @@ -0,0 +1,87 @@ +package com.cnblogs.yjmyzz.demo.service.consumer; + +import com.alibaba.dubbo.rpc.protocol.grpc.GrpcBindableService; +import com.cnblogs.yjmyzz.demo.service.api.avro.AvroHelloService; +import com.cnblogs.yjmyzz.demo.service.api.dubbo.DubboHelloService; +import com.cnblogs.yjmyzz.demo.service.api.dubbo.User; +import com.cnblogs.yjmyzz.demo.service.api.grpc.GrpcHelloServiceGrpc; +import com.cnblogs.yjmyzz.demo.service.api.grpc.PingRequest; +import com.cnblogs.yjmyzz.demo.service.api.grpc.PingResponse; +import com.cnblogs.yjmyzz.demo.service.api.rest.RestHelloService; +import com.cnblogs.yjmyzz.demo.service.api.thrift.ThriftHelloService; +import io.grpc.ManagedChannel; +import io.grpc.stub.AbstractStub; +import org.apache.avro.AvroRemoteException; +import org.apache.thrift.TException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +import java.util.concurrent.TimeUnit; + +/** + * Created by yangjunming on 2016/12/25. + */ +public class DubboDemoConsumer { + + private static Logger logger = LoggerFactory.getLogger(DubboDemoConsumer.class); + + public static void main(String[] args) throws TException, InterruptedException, AvroRemoteException { + + ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml"); + + testRest(ctx); + testDubbo(ctx); + testThrift(ctx); + testAvro(ctx); + testGrpc(ctx); + } + + private static void testRest(ConfigurableApplicationContext ctx) { + RestHelloService service = ctx.getBean(RestHelloService.class); + logger.info("\n---------restful服务测试开始---------"); + logger.info("\tping=>" + service.ping()); + logger.info("\tregister=>" + service.register(mockUser())); + } + + + private static void testDubbo(ConfigurableApplicationContext ctx) { + DubboHelloService service = ctx.getBean(DubboHelloService.class); + logger.info("\n---------dubbo协议测试开始---------"); + logger.info("\tping=>" + service.ping()); + logger.info("\tregister=>" + service.register(mockUser())); + } + + + private static void testThrift(ConfigurableApplicationContext ctx) throws TException { + ThriftHelloService.Iface service = ctx.getBean(ThriftHelloService.Iface.class); + logger.info("\n---------thrift协议测试开始---------"); + logger.info("\tping=>" + service.ping()); + } + + private static void testAvro(ConfigurableApplicationContext ctx) throws AvroRemoteException { + AvroHelloService service = ctx.getBean(AvroHelloService.class); + logger.info("\n---------avro协议测试开始---------"); + logger.info("\tping=>" + service.ping()); + } + + private static void testGrpc(ConfigurableApplicationContext ctx) throws InterruptedException { + GrpcBindableService service = ctx.getBean(GrpcBindableService.class, "grpcService"); + AbstractStub stub = GrpcHelloServiceGrpc.newBlockingStub(service.getChannel()); + PingRequest request = PingRequest.newBuilder().build(); + logger.info("\n---------gprc协议测试开始---------"); + logger.info(stub.getClass().toString()); + PingResponse response = ((GrpcHelloServiceGrpc.GrpcHelloServiceBlockingStub) stub).ping(request); + logger.info("\tping=>" + response.getMessage()); + ((ManagedChannel) stub.getChannel()).shutdown().awaitTermination(5, TimeUnit.SECONDS); + } + + + private static User mockUser() { + User u = new User(); + u.setUserId(1); + u.setUserName("菩提树下的杨过"); + return u; + } +} 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 deleted file mode 100644 index ea27c403923..00000000000 --- a/dubbo-demo/dubbo-demo-consumer/src/main/java/dubbo/spring/javaconfig/DubboDemoActionConfig.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 deleted file mode 100644 index 2052150a92f..00000000000 --- a/dubbo-demo/dubbo-demo-consumer/src/main/java/dubbo/spring/javaconfig/DubboDemoConsumerConfig.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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/main/resouces/dubbo/com.alibaba.dubbo.rpc.Protocol b/dubbo-demo/dubbo-demo-consumer/src/main/resouces/dubbo/com.alibaba.dubbo.rpc.Protocol new file mode 100644 index 00000000000..ea30049702a --- /dev/null +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resouces/dubbo/com.alibaba.dubbo.rpc.Protocol @@ -0,0 +1,3 @@ +grpc=com.alibaba.dubbo.rpc.protocol.grpc.GrpcProtocol +thrift2=com.alibaba.dubbo.rpc.protocol.thrift2.Thrift2Protocol +avro=com.alibaba.dubbo.rpc.protocol.avro.AvroProtocol \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resouces/log4j2.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resouces/log4j2.xml new file mode 100644 index 00000000000..ccf6466706c --- /dev/null +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resouces/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resouces/spring-context.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resouces/spring-context.xml new file mode 100644 index 00000000000..0565da72053 --- /dev/null +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resouces/spring-context.xml @@ -0,0 +1,15 @@ + + + + + + + + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/main/resouces/spring-dubbo-consumer.xml b/dubbo-demo/dubbo-demo-consumer/src/main/resouces/spring-dubbo-consumer.xml new file mode 100644 index 00000000000..4f4a57aa973 --- /dev/null +++ b/dubbo-demo/dubbo-demo-consumer/src/main/resouces/spring-dubbo-consumer.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + \ 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 deleted file mode 100644 index fb7662ca000..00000000000 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-action.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - \ 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 deleted file mode 100644 index 6dd555c68f9..00000000000 --- a/dubbo-demo/dubbo-demo-consumer/src/main/resources/META-INF/spring/dubbo-demo-consumer.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/DemoConsumer.java b/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/DemoConsumer.java deleted file mode 100644 index 3e414ff36c1..00000000000 --- a/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/DemoConsumer.java +++ /dev/null @@ -1,24 +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.consumer; - -public class DemoConsumer { - - public static void main(String[] args) { - com.alibaba.dubbo.container.Main.main(args); - } - -} \ No newline at end of file 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 deleted file mode 100644 index b8fd5fddba8..00000000000 --- a/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/RestClient.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * 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, "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/dubbo-demo/dubbo-demo-consumer/src/test/resources/log4j.xml b/dubbo-demo/dubbo-demo-consumer/src/test/resources/log4j.xml deleted file mode 100644 index 7d716346409..00000000000 --- a/dubbo-demo/dubbo-demo-consumer/src/test/resources/log4j.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - \ 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 1d6192f7aec..ce10b482e82 100644 --- a/dubbo-demo/dubbo-demo-provider/pom.xml +++ b/dubbo-demo/dubbo-demo-provider/pom.xml @@ -1,28 +1,13 @@ - 4.0.0 com.alibaba dubbo-demo - 2.8.4 + 2.8.5-SNAPSHOT dubbo-demo-provider - war + jar ${project.artifactId} The demo provider module of dubbo project @@ -34,206 +19,5 @@ dubbo-demo-api ${project.parent.version} - - com.alibaba - dubbo - ${project.parent.version} - - - org.javassist - javassist - - - io.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 - - - - 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/bid/BidServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/bid/BidServiceImpl.java deleted file mode 100644 index 391ffbc3a81..00000000000 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/bid/BidServiceImpl.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 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/user/UserServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/UserServiceImpl.java deleted file mode 100644 index e722a01573f..00000000000 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/UserServiceImpl.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 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, "username" + 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 deleted file mode 100644 index e7dd278dacd..00000000000 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnnotationDrivenUserRestServiceImpl.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 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 com.alibaba.dubbo.rpc.protocol.rest.support.ContentType; -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", "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}) -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 deleted file mode 100644 index 23a1ba282e2..00000000000 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/AnotherUserRestServiceImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 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.rpc.RpcContext; - -/** - * @author lishen - */ -public class AnotherUserRestServiceImpl implements AnotherUserRestService { - - private UserService userService; - - public void setUserService(UserService userService) { - this.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); - } - - 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 deleted file mode 100644 index 659a8203510..00000000000 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/user/facade/UserRestServiceImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 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 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; -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({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) -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()); - 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); - } - - @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/cnblogs/yjmyzz/demo/service/impl/DubboDemoProvider.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/DubboDemoProvider.java new file mode 100644 index 00000000000..65e38969561 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/DubboDemoProvider.java @@ -0,0 +1,25 @@ +package com.cnblogs.yjmyzz.demo.service.impl; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +/** + * Created by yangjunming on 2016/11/3. + */ +public class DubboDemoProvider { + + private static Logger logger = LoggerFactory.getLogger(DubboDemoProvider.class); + + public static void main(String[] args) throws InterruptedException { + + ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml"); + + logger.info("server started ..."); + + while (true) { + Thread.sleep(100); + } + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/avro/HelloServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/avro/HelloServiceImpl.java new file mode 100644 index 00000000000..9ebcaa37428 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/avro/HelloServiceImpl.java @@ -0,0 +1,17 @@ +package com.cnblogs.yjmyzz.demo.service.impl.avro; + +import com.cnblogs.yjmyzz.demo.service.api.avro.AvroHelloService; +import org.apache.avro.AvroRemoteException; +import org.springframework.stereotype.Service; + +/** + * Created by yangjunming on 2016/11/3. + */ +@Service("avroService") +public class HelloServiceImpl implements AvroHelloService { + + @Override + public CharSequence ping() throws AvroRemoteException { + return "avro service is running..."; + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/dubbo/HelloServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/dubbo/HelloServiceImpl.java new file mode 100644 index 00000000000..5906d679467 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/dubbo/HelloServiceImpl.java @@ -0,0 +1,23 @@ +package com.cnblogs.yjmyzz.demo.service.impl.dubbo; + + +import com.cnblogs.yjmyzz.demo.service.api.dubbo.DubboHelloService; +import com.cnblogs.yjmyzz.demo.service.api.dubbo.User; +import org.springframework.stereotype.Service; + +/** + * Created by yangjunming on 2016/11/3. + */ +@Service("dubboService") +public class HelloServiceImpl implements DubboHelloService { + + @Override + public String ping() { + return "dubbo service is running..."; + } + + @Override + public String register(User user) { + return String.format("%s register ok!", user.getUserName()); + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/grpc/HelloServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/grpc/HelloServiceImpl.java new file mode 100644 index 00000000000..eb45084c55d --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/grpc/HelloServiceImpl.java @@ -0,0 +1,34 @@ +package com.cnblogs.yjmyzz.demo.service.impl.grpc; + +import com.alibaba.dubbo.rpc.protocol.grpc.GrpcBindableService; +import com.cnblogs.yjmyzz.demo.service.api.grpc.GrpcHelloServiceGrpc; +import com.cnblogs.yjmyzz.demo.service.api.grpc.PingRequest; +import com.cnblogs.yjmyzz.demo.service.api.grpc.PingResponse; +import io.grpc.Channel; +import io.grpc.stub.StreamObserver; +import org.springframework.stereotype.Service; + +/** + * Created by yangjunming on 2016/11/3. + */ +@Service("grpcService") +public class HelloServiceImpl extends GrpcHelloServiceGrpc.GrpcHelloServiceImplBase implements GrpcBindableService { + + private Channel channel; + + public Channel getChannel() { + return channel; + } + + public void setChannel(Channel channel) { + this.channel = channel; + } + + @Override + public void ping(PingRequest request, + StreamObserver responseObserver) { + PingResponse reply = PingResponse.newBuilder().setMessage("grpc is running").build(); + responseObserver.onNext(reply); + responseObserver.onCompleted(); + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/rest/HelloServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/rest/HelloServiceImpl.java new file mode 100644 index 00000000000..4356887237c --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/rest/HelloServiceImpl.java @@ -0,0 +1,27 @@ +package com.cnblogs.yjmyzz.demo.service.impl.rest; + +import com.cnblogs.yjmyzz.demo.service.api.dubbo.DubboHelloService; +import com.cnblogs.yjmyzz.demo.service.api.dubbo.User; +import com.cnblogs.yjmyzz.demo.service.api.rest.RestHelloService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * Created by yangjunming on 2016/11/3. + */ +@Service("restService") +public class HelloServiceImpl implements RestHelloService { + + @Autowired + DubboHelloService dubboHelloService; + + @Override + public String ping() { + return dubboHelloService.ping(); + } + + @Override + public String register(User user) { + return dubboHelloService.register(user); + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/thrift/HelloServiceImpl.java b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/thrift/HelloServiceImpl.java new file mode 100644 index 00000000000..b9351c0b52c --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/java/com/cnblogs/yjmyzz/demo/service/impl/thrift/HelloServiceImpl.java @@ -0,0 +1,17 @@ +package com.cnblogs.yjmyzz.demo.service.impl.thrift; + +import com.cnblogs.yjmyzz.demo.service.api.thrift.ThriftHelloService; +import org.apache.thrift.TException; +import org.springframework.stereotype.Service; + +/** + * Created by yangjunming on 2016/11/3. + */ +@Service("thriftService") +public class HelloServiceImpl implements ThriftHelloService.Iface { + + @Override + public String ping() throws TException { + return "thrift service is running..."; + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.rpc.Protocol b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.rpc.Protocol new file mode 100644 index 00000000000..ea30049702a --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.rpc.Protocol @@ -0,0 +1,3 @@ +grpc=com.alibaba.dubbo.rpc.protocol.grpc.GrpcProtocol +thrift2=com.alibaba.dubbo.rpc.protocol.thrift2.Thrift2Protocol +avro=com.alibaba.dubbo.rpc.protocol.avro.AvroProtocol \ 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 deleted file mode 100644 index 265645ab00b..00000000000 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/META-INF/spring/dubbo-demo-provider.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/log4j.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/log4j.xml deleted file mode 100644 index ae988c35f13..00000000000 --- a/dubbo-demo/dubbo-demo-provider/src/main/resources/log4j.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/log4j2.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/log4j2.xml new file mode 100644 index 00000000000..ccf6466706c --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/spring-context.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/spring-context.xml new file mode 100644 index 00000000000..e59a14c1c71 --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/spring-context.xml @@ -0,0 +1,15 @@ + + + + + + + + + \ No newline at end of file diff --git a/dubbo-demo/dubbo-demo-provider/src/main/resources/spring-dubbo-provider.xml b/dubbo-demo/dubbo-demo-provider/src/main/resources/spring-dubbo-provider.xml new file mode 100644 index 00000000000..4decb31aa9b --- /dev/null +++ b/dubbo-demo/dubbo-demo-provider/src/main/resources/spring-dubbo-provider.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ 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 deleted file mode 100644 index 9a355c15ffc..00000000000 --- a/dubbo-demo/dubbo-demo-provider/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - 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-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 deleted file mode 100644 index b00688c9efc..00000000000 --- a/dubbo-demo/dubbo-demo-provider/src/test/java/com/alibaba/dubbo/demo/provider/DemoProvider.java +++ /dev/null @@ -1,36 +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 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 4d77e14ec9a..a805cec8f76 100644 --- a/dubbo-demo/pom.xml +++ b/dubbo-demo/pom.xml @@ -1,5 +1,5 @@ - 4.0.0 - - com.alibaba - dubbo-parent - 2.8.4 - - dubbo-demo - pom - ${project.artifactId} - The demo module of dubbo project - - true - - - dubbo-demo-api - dubbo-demo-provider - dubbo-demo-consumer - + 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.5-SNAPSHOT + + dubbo-demo + pom + ${project.artifactId} + The demo module of dubbo project + + true + + + dubbo-demo-api + dubbo-demo-provider + dubbo-demo-consumer + + + + + + + org.springframework + spring-core + 4.2.5.RELEASE + + + + org.springframework + spring-beans + 4.2.5.RELEASE + + + + org.springframework + spring-context + 4.2.5.RELEASE + + + + org.springframework + spring-context-support + 4.2.5.RELEASE + + + + + com.alibaba + dubbo + 2.8.5-SNAPSHOT + + + log4j + log4j + + + org.slf4j + slf4j-log4j12 + + + + + + + org.jboss.resteasy + resteasy-client + 3.0.9.Final + + + + org.jboss.resteasy + resteasy-jaxrs + 3.0.9.Final + + + + org.jboss.resteasy + resteasy-netty + 3.0.14.Final + + + + org.jboss.resteasy + resteasy-multipart-provider + 3.0.14.Final + + + + + org.apache.tomcat.embed + tomcat-embed-core + 8.0.11 + + + + org.apache.tomcat.embed + tomcat-embed-logging-juli + 8.0.11 + + + + + javax.servlet + javax.servlet-api + 3.1.0 + + + + javax.validation + validation-api + 1.1.0.Final + + + + + org.apache.zookeeper + zookeeper + 3.4.8 + + + org.slf4j + slf4j-log4j12 + + + log4j + log4j + + + + + + com.alibaba + zkclient + 0.8.1 + + + + + org.jboss.resteasy + resteasy-jackson-provider + 3.0.14.Final + + + + org.jboss.resteasy + resteasy-jaxb-provider + 3.0.16.Final + + + + + org.apache.thrift + libthrift + 0.9.3 + + + + + io.grpc + grpc-netty + 1.0.1 + + + io.grpc + grpc-protobuf + 1.0.1 + + + io.grpc + grpc-stub + 1.0.1 + + + com.google.protobuf + protobuf-java + 3.1.0 + + + com.google.guava + guava + 19.0 + + + + + org.apache.avro + avro + 1.8.1 + + + org.apache.avro + avro-ipc + 1.8.1 + + + + + org.apache.logging.log4j + log4j-core + 2.7 + + + + org.apache.logging.log4j + log4j-slf4j-impl + 2.7 + + + diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 8431bef623d..9932dea7d68 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.5-SNAPSHOT dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index d3d9cc12134..402d6306f5c 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.5-SNAPSHOT dubbo-filter-validation jar diff --git a/dubbo-filter/pom.xml b/dubbo-filter/pom.xml index 86e2ef12fbf..7debf871ee3 100644 --- a/dubbo-filter/pom.xml +++ b/dubbo-filter/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 2.8.5-SNAPSHOT dubbo-filter pom diff --git a/dubbo-maven/pom.xml b/dubbo-maven/pom.xml deleted file mode 100644 index 68893fdf6c6..00000000000 --- a/dubbo-maven/pom.xml +++ /dev/null @@ -1,354 +0,0 @@ - - - 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 - - - io.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 - javax.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 - provided - - - - - - 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 - - - diff --git a/dubbo-monitor/dubbo-monitor-api/pom.xml b/dubbo-monitor/dubbo-monitor-api/pom.xml index e654f038a54..5d6dcadb9e5 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.5-SNAPSHOT dubbo-monitor-api jar diff --git a/dubbo-monitor/dubbo-monitor-default/pom.xml b/dubbo-monitor/dubbo-monitor-default/pom.xml index 957fda3e422..2668f833804 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.5-SNAPSHOT dubbo-monitor-default jar diff --git a/dubbo-monitor/pom.xml b/dubbo-monitor/pom.xml index 5061c3f5606..217c71764a3 100644 --- a/dubbo-monitor/pom.xml +++ b/dubbo-monitor/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 2.8.5-SNAPSHOT dubbo-monitor pom diff --git a/dubbo-registry/dubbo-registry-api/pom.xml b/dubbo-registry/dubbo-registry-api/pom.xml index 25572a8b656..9342cdcb250 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.5-SNAPSHOT dubbo-registry-api jar diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml index 2ee2515bed9..c8db6ea851d 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.5-SNAPSHOT dubbo-registry-default jar @@ -40,12 +40,12 @@ ${project.parent.version} test - - com.alibaba - dubbo-rpc-injvm - ${project.parent.version} - test - + + + + + + com.alibaba dubbo-remoting-netty diff --git a/dubbo-registry/dubbo-registry-multicast/pom.xml b/dubbo-registry/dubbo-registry-multicast/pom.xml index 478d4fb67b7..e51af12fdf1 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.5-SNAPSHOT dubbo-registry-multicast jar diff --git a/dubbo-registry/dubbo-registry-multicast/src/main/java/com/alibaba/dubbo/registry/multicast/MulticastRegistry.java b/dubbo-registry/dubbo-registry-multicast/src/main/java/com/alibaba/dubbo/registry/multicast/MulticastRegistry.java index 5575e84e4f9..0fd8a3f8ac0 100644 --- a/dubbo-registry/dubbo-registry-multicast/src/main/java/com/alibaba/dubbo/registry/multicast/MulticastRegistry.java +++ b/dubbo-registry/dubbo-registry-multicast/src/main/java/com/alibaba/dubbo/registry/multicast/MulticastRegistry.java @@ -15,25 +15,6 @@ */ package com.alibaba.dubbo.registry.multicast; -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.MulticastSocket; -import java.net.Socket; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -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.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -41,11 +22,15 @@ import com.alibaba.dubbo.common.utils.ConcurrentHashSet; import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.common.utils.StringUtils; import com.alibaba.dubbo.common.utils.UrlUtils; import com.alibaba.dubbo.registry.NotifyListener; import com.alibaba.dubbo.registry.support.FailbackRegistry; +import java.io.IOException; +import java.net.*; +import java.util.*; +import java.util.concurrent.*; + /** * MulticastRegistry * @@ -79,7 +64,7 @@ public MulticastRegistry(URL url) { if (url.isAnyHost()) { throw new IllegalStateException("registry address == null"); } - if (! isMulticastAddress(url.getHost())) { + if (! NetUtils.isMulticastAddress(url.getHost())) { throw new IllegalArgumentException("Invalid multicast address " + url.getHost() + ", scope: 224.0.0.0 - 239.255.255.255"); } try { @@ -131,17 +116,17 @@ public void run() { } } - private static boolean isMulticastAddress(String ip) { - int i = ip.indexOf('.'); - if (i > 0) { - String prefix = ip.substring(0, i); - if (StringUtils.isInteger(prefix)) { - int p = Integer.parseInt(prefix); - return p >= 224 && p <= 239; - } - } - return false; - } +// private static boolean isMulticastAddress(String ip) { +// int i = ip.indexOf('.'); +// if (i > 0) { +// String prefix = ip.substring(0, i); +// if (StringUtils.isInteger(prefix)) { +// int p = Integer.parseInt(prefix); +// return p >= 224 && p <= 239; +// } +// } +// return false; +// } private void clean() { if (admin) { diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml index 10c9fa26b49..fe3ddf6cd33 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.5-SNAPSHOT dubbo-registry-redis jar diff --git a/dubbo-registry/dubbo-registry-zookeeper/pom.xml b/dubbo-registry/dubbo-registry-zookeeper/pom.xml index 774d0b73bda..3ddc7e5b9f0 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.5-SNAPSHOT dubbo-registry-zookeeper jar 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 1a39435f964..ecf42042c65 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 @@ -15,12 +15,6 @@ */ package com.alibaba.dubbo.registry.zookeeper; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.common.logger.Logger; @@ -30,14 +24,20 @@ import com.alibaba.dubbo.registry.NotifyListener; import com.alibaba.dubbo.registry.support.FailbackRegistry; import com.alibaba.dubbo.remoting.zookeeper.ChildListener; -import com.alibaba.dubbo.remoting.zookeeper.ZookeeperClient; import com.alibaba.dubbo.remoting.zookeeper.StateListener; +import com.alibaba.dubbo.remoting.zookeeper.ZookeeperClient; import com.alibaba.dubbo.remoting.zookeeper.ZookeeperTransporter; import com.alibaba.dubbo.rpc.RpcException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + /** * ZookeeperRegistry - * + * * @author william.liangf */ public class ZookeeperRegistry extends FailbackRegistry { @@ -45,37 +45,37 @@ public class ZookeeperRegistry extends FailbackRegistry { private final static Logger logger = LoggerFactory.getLogger(ZookeeperRegistry.class); private final static int DEFAULT_ZOOKEEPER_PORT = 2181; - + private final static String DEFAULT_ROOT = "dubbo"; - private final String root; - + private final String root; + private final Set anyServices = new ConcurrentHashSet(); private final ConcurrentMap> zkListeners = new ConcurrentHashMap>(); - + private final ZookeeperClient zkClient; - + public ZookeeperRegistry(URL url, ZookeeperTransporter zookeeperTransporter) { super(url); if (url.isAnyHost()) { - throw new IllegalStateException("registry address == null"); - } + throw new IllegalStateException("registry address == null"); + } String group = url.getParameter(Constants.GROUP_KEY, DEFAULT_ROOT); - if (! group.startsWith(Constants.PATH_SEPARATOR)) { + if (!group.startsWith(Constants.PATH_SEPARATOR)) { group = Constants.PATH_SEPARATOR + group; } this.root = group; zkClient = zookeeperTransporter.connect(url); zkClient.addStateListener(new StateListener() { public void stateChanged(int state) { - if (state == RECONNECTED) { - try { - recover(); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - } + if (state == RECONNECTED) { + try { + recover(); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } } }); } @@ -95,7 +95,7 @@ public void destroy() { protected void doRegister(URL url) { try { - zkClient.create(toUrlPath(url), url.getParameter(Constants.DYNAMIC_KEY, true)); + zkClient.create(toUrlPath(url), url.getParameter(Constants.DYNAMIC_KEY, true)); } catch (Throwable e) { throw new RpcException("Failed to register " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } @@ -123,10 +123,10 @@ 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)) { + child = URL.decode(child); + if (!anyServices.contains(child)) { anyServices.add(child); - subscribe(url.setPath(child).addParameters(Constants.INTERFACE_KEY, child, + subscribe(url.setPath(child).addParameters(Constants.INTERFACE_KEY, child, Constants.CHECK_KEY, String.valueOf(false)), listener); } } @@ -138,9 +138,9 @@ public void childChanged(String parentPath, List currentChilds) { List services = zkClient.addChildListener(root, zkListener); if (services != null && services.size() > 0) { for (String service : services) { - service = URL.decode(service); - anyServices.add(service); - subscribe(url.setPath(service).addParameters(Constants.INTERFACE_KEY, service, + service = URL.decode(service); + anyServices.add(service); + subscribe(url.setPath(service).addParameters(Constants.INTERFACE_KEY, service, Constants.CHECK_KEY, String.valueOf(false)), listener); } } @@ -156,7 +156,7 @@ public void childChanged(String parentPath, List currentChilds) { if (zkListener == null) { listeners.putIfAbsent(listener, new ChildListener() { public void childChanged(String parentPath, List currentChilds) { - ZookeeperRegistry.this.notify(url, listener, toUrlsWithEmpty(url, parentPath, currentChilds)); + ZookeeperRegistry.this.notify(url, listener, toUrlsWithEmpty(url, parentPath, currentChilds)); } }); zkListener = listeners.get(listener); @@ -164,7 +164,7 @@ public void childChanged(String parentPath, List currentChilds) { zkClient.create(path, false); List children = zkClient.addChildListener(path, zkListener); if (children != null) { - urls.addAll(toUrlsWithEmpty(url, path, children)); + urls.addAll(toUrlsWithEmpty(url, path, children)); } } notify(url, listener, urls); @@ -191,28 +191,28 @@ public List lookup(URL url) { try { List providers = new ArrayList(); for (String path : toCategoriesPath(url)) { - List children = zkClient.getChildren(path); - if (children != null) { - providers.addAll(children); - } + List children = zkClient.getChildren(path); + if (children != null) { + providers.addAll(children); + } } return toUrlsWithoutEmpty(url, providers); } catch (Throwable e) { throw new RpcException("Failed to lookup " + url + " from zookeeper " + getUrl() + ", cause: " + e.getMessage(), e); } } - + private String toRootDir() { if (root.equals(Constants.PATH_SEPARATOR)) { return root; } return root + Constants.PATH_SEPARATOR; } - + private String toRootPath() { return root; } - + private String toServicePath(URL url) { String name = url.getServiceInterface(); if (Constants.ANY_VALUE.equals(name)) { @@ -224,13 +224,13 @@ private String toServicePath(URL url) { private String[] toCategoriesPath(URL url) { String[] categroies; if (Constants.ANY_VALUE.equals(url.getParameter(Constants.CATEGORY_KEY))) { - categroies = new String[] {Constants.PROVIDERS_CATEGORY, Constants.CONSUMERS_CATEGORY, + categroies = new String[]{Constants.PROVIDERS_CATEGORY, Constants.CONSUMERS_CATEGORY, Constants.ROUTERS_CATEGORY, Constants.CONFIGURATORS_CATEGORY}; } else { - categroies = url.getParameter(Constants.CATEGORY_KEY, new String[] {Constants.DEFAULT_CATEGORY}); + categroies = url.getParameter(Constants.CATEGORY_KEY, new String[]{Constants.DEFAULT_CATEGORY}); } String[] paths = new String[categroies.length]; - for (int i = 0; i < categroies.length; i ++) { + for (int i = 0; i < categroies.length; i++) { paths[i] = toServicePath(url) + Constants.PATH_SEPARATOR + categroies[i]; } return paths; @@ -243,9 +243,9 @@ private String toCategoryPath(URL url) { private String toUrlPath(URL url) { return toCategoryPath(url) + Constants.PATH_SEPARATOR + URL.encode(url.toFullString()); } - + private List toUrlsWithoutEmpty(URL consumer, List providers) { - List urls = new ArrayList(); + List urls = new ArrayList(); if (providers != null && providers.size() > 0) { for (String provider : providers) { provider = URL.decode(provider); @@ -263,9 +263,9 @@ private List toUrlsWithoutEmpty(URL consumer, List providers) { private List toUrlsWithEmpty(URL consumer, String path, List providers) { List urls = toUrlsWithoutEmpty(consumer, providers); if (urls.isEmpty()) { - int i = path.lastIndexOf('/'); - String category = i < 0 ? path : path.substring(i + 1); - URL empty = consumer.setProtocol(Constants.EMPTY_PROTOCOL).addParameter(Constants.CATEGORY_KEY, category); + int i = path.lastIndexOf('/'); + String category = i < 0 ? path : path.substring(i + 1); + URL empty = consumer.setProtocol(Constants.EMPTY_PROTOCOL).addParameter(Constants.CATEGORY_KEY, category); urls.add(empty); } return urls; diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index 4dedf4fc732..2c87426e5c2 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 2.8.5-SNAPSHOT dubbo-registry pom diff --git a/dubbo-remoting/dubbo-remoting-api/pom.xml b/dubbo-remoting/dubbo-remoting-api/pom.xml index c8fe1460033..12b78d799cb 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.5-SNAPSHOT dubbo-remoting-api jar diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml index ce4b6520072..60e1d4b501a 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.5-SNAPSHOT dubbo-remoting-grizzly jar diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml index c08a31deb77..69cdabc07a9 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.5-SNAPSHOT dubbo-remoting-http jar diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml index b3e36966f1a..df1bbad852e 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.5-SNAPSHOT dubbo-remoting-mina jar diff --git a/dubbo-remoting/dubbo-remoting-netty/pom.xml b/dubbo-remoting/dubbo-remoting-netty/pom.xml index afe4f789749..34328a4568d 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.5-SNAPSHOT dubbo-remoting-netty jar diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml index 0dce25f736f..3ee39816e5f 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.5-SNAPSHOT dubbo-remoting-p2p jar diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastGroup.java index beca3ba9c96..d249ec49fe1 100644 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastGroup.java +++ b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/com/alibaba/dubbo/remoting/p2p/support/MulticastGroup.java @@ -15,18 +15,18 @@ */ package com.alibaba.dubbo.remoting.p2p.support; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.utils.NetUtils; +import com.alibaba.dubbo.remoting.ChannelHandler; +import com.alibaba.dubbo.remoting.RemotingException; +import com.alibaba.dubbo.remoting.p2p.Peer; + import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.StringUtils; -import com.alibaba.dubbo.remoting.ChannelHandler; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.p2p.Peer; - /** * MulticastGroup * @@ -44,7 +44,7 @@ public class MulticastGroup extends AbstractGroup { public MulticastGroup(URL url) { super(url); - if (! isMulticastAddress(url.getHost())) { + if (!NetUtils.isMulticastAddress(url.getHost())) { throw new IllegalArgumentException("Invalid multicast address " + url.getHost() + ", scope: 224.0.0.0 - 239.255.255.255"); } try { @@ -73,17 +73,17 @@ public void run() { } } - private static boolean isMulticastAddress(String ip) { - int i = ip.indexOf('.'); - if (i > 0) { - String prefix = ip.substring(0, i); - if (StringUtils.isInteger(prefix)) { - int p = Integer.parseInt(prefix); - return p >= 224 && p <= 239; - } - } - return false; - } +// private static boolean isMulticastAddress(String ip) { +// int i = ip.indexOf('.'); +// if (i > 0) { +// String prefix = ip.substring(0, i); +// if (StringUtils.isInteger(prefix)) { +// int p = Integer.parseInt(prefix); +// return p >= 224 && p <= 239; +// } +// } +// return false; +// } private void send(String msg) throws RemotingException { DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), mutilcastAddress, mutilcastSocket.getLocalPort()); diff --git a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml index 47520dae0d8..0b9af3fc718 100644 --- a/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml +++ b/dubbo-remoting/dubbo-remoting-zookeeper/pom.xml @@ -14,37 +14,38 @@ - limitations under the License. --> - 4.0.0 - - com.alibaba - dubbo-remoting - 2.8.4 - - dubbo-remoting-zookeeper - jar - ${project.artifactId} - The zookeeper remoting module of dubbo project - - true - - - - com.alibaba - dubbo-common - ${project.parent.version} - - - org.apache.zookeeper - zookeeper - - - com.github.sgroschupf - zkclient - - - org.apache.curator - curator-framework - - + 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-remoting + 2.8.5-SNAPSHOT + + dubbo-remoting-zookeeper + jar + ${project.artifactId} + The zookeeper remoting module of dubbo project + + true + + + + com.alibaba + dubbo-common + ${project.parent.version} + + + org.apache.zookeeper + zookeeper + + + com.alibaba + zkclient + 0.8.1 + + + org.apache.curator + curator-framework + + \ No newline at end of file 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 f1f43e6ba68..d025ae6e45d 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 @@ -1,8 +1,10 @@ package com.alibaba.dubbo.remoting.zookeeper.zkclient; -import java.util.List; - import com.alibaba.dubbo.common.Constants; +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.remoting.zookeeper.ChildListener; +import com.alibaba.dubbo.remoting.zookeeper.StateListener; +import com.alibaba.dubbo.remoting.zookeeper.support.AbstractZookeeperClient; import org.I0Itec.zkclient.IZkChildListener; import org.I0Itec.zkclient.IZkStateListener; import org.I0Itec.zkclient.ZkClient; @@ -10,90 +12,95 @@ import org.I0Itec.zkclient.exception.ZkNodeExistsException; import org.apache.zookeeper.Watcher.Event.KeeperState; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.zookeeper.ChildListener; -import com.alibaba.dubbo.remoting.zookeeper.StateListener; -import com.alibaba.dubbo.remoting.zookeeper.support.AbstractZookeeperClient; +import java.util.List; public class ZkclientZookeeperClient extends AbstractZookeeperClient { - private final ZkClient client; + private final ZkClient client; - private volatile KeeperState state = KeeperState.SyncConnected; + private volatile KeeperState state = KeeperState.SyncConnected; - public ZkclientZookeeperClient(URL url) { - super(url); - client = new ZkClient( + public ZkclientZookeeperClient(URL url) { + super(url); + client = new ZkClient( url.getBackupAddress(), url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT), url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_REGISTRY_CONNECT_TIMEOUT)); - client.subscribeStateChanges(new IZkStateListener() { - public void handleStateChanged(KeeperState state) throws Exception { - ZkclientZookeeperClient.this.state = state; - if (state == KeeperState.Disconnected) { - stateChanged(StateListener.DISCONNECTED); - } else if (state == KeeperState.SyncConnected) { - stateChanged(StateListener.CONNECTED); - } - } - public void handleNewSession() throws Exception { - stateChanged(StateListener.RECONNECTED); - } - }); - } - - public void createPersistent(String path) { - try { - client.createPersistent(path, true); - } catch (ZkNodeExistsException e) { - } - } - - public void createEphemeral(String path) { - try { - client.createEphemeral(path); - } catch (ZkNodeExistsException e) { - } - } - - public void delete(String path) { - try { - client.delete(path); - } catch (ZkNoNodeException e) { - } - } - - public List getChildren(String path) { - try { - return client.getChildren(path); + client.subscribeStateChanges(new IZkStateListener() { + public void handleStateChanged(KeeperState state) throws Exception { + ZkclientZookeeperClient.this.state = state; + if (state == KeeperState.Disconnected) { + stateChanged(StateListener.DISCONNECTED); + } else if (state == KeeperState.SyncConnected) { + stateChanged(StateListener.CONNECTED); + } + } + + public void handleNewSession() throws Exception { + stateChanged(StateListener.RECONNECTED); + } + + //@Override + public void handleSessionEstablishmentError(Throwable error) throws Exception { + //TODO list... + logger.error("zookeeper connection error!", error); + throw new Exception(error); + } + }); + } + + public void createPersistent(String path) { + try { + client.createPersistent(path, true); + } catch (ZkNodeExistsException e) { + } + } + + public void createEphemeral(String path) { + try { + client.createEphemeral(path); + } catch (ZkNodeExistsException e) { + } + } + + public void delete(String path) { + try { + client.delete(path); + } catch (ZkNoNodeException e) { + } + } + + public List getChildren(String path) { + try { + return client.getChildren(path); } catch (ZkNoNodeException e) { return null; } - } - - public boolean isConnected() { - return state == KeeperState.SyncConnected; - } - - public void doClose() { - client.close(); - } - - public IZkChildListener createTargetChildListener(String path, final ChildListener listener) { - return new IZkChildListener() { - public void handleChildChange(String parentPath, List currentChilds) - throws Exception { - listener.childChanged(parentPath, currentChilds); - } - }; - } - - public List addTargetChildListener(String path, final IZkChildListener listener) { - return client.subscribeChildChanges(path, listener); - } - - public void removeTargetChildListener(String path, IZkChildListener listener) { - client.unsubscribeChildChanges(path, listener); - } + } + + public boolean isConnected() { + return state == KeeperState.SyncConnected; + } + + public void doClose() { + client.close(); + } + + public IZkChildListener createTargetChildListener(String path, final ChildListener listener) { + return new IZkChildListener() { + public void handleChildChange(String parentPath, List currentChilds) + throws Exception { + listener.childChanged(parentPath, currentChilds); + } + }; + } + + public List addTargetChildListener(String path, final IZkChildListener listener) { + return client.subscribeChildChanges(path, listener); + } + + public void removeTargetChildListener(String path, IZkChildListener listener) { + client.unsubscribeChildChanges(path, listener); + } } diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 0c7faf42bbc..55d2313c6bc 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -18,7 +18,7 @@ com.alibaba dubbo-parent - 2.8.4 + 2.8.5-SNAPSHOT dubbo-remoting pom diff --git a/dubbo-rpc/dubbo-rpc-api/pom.xml b/dubbo-rpc/dubbo-rpc-api/pom.xml index e713642d38e..1aacb4f94d3 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.5-SNAPSHOT dubbo-rpc-api jar diff --git a/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/utils/ErrorCodeUtils.java b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/utils/ErrorCodeUtils.java new file mode 100644 index 00000000000..edd6035f614 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-api/src/main/java/com/alibaba/dubbo/rpc/utils/ErrorCodeUtils.java @@ -0,0 +1,25 @@ +package com.alibaba.dubbo.rpc.utils; + +import com.alibaba.dubbo.rpc.RpcException; + +import java.io.IOException; +import java.net.SocketTimeoutException; + +/** + * Created by yangjunming on 2/24/16. + * author: yangjunming@huijiame.com + */ +public class ErrorCodeUtils { + + public static int getErrorCode(Throwable e, Class cls) { + // 是根据测试Case发现的问题,对RpcException.setCode进行设置 + if (SocketTimeoutException.class.equals(cls)) { + return RpcException.TIMEOUT_EXCEPTION; + } else if (IOException.class.isAssignableFrom(cls)) { + return RpcException.NETWORK_EXCEPTION; + } else if (ClassNotFoundException.class.isAssignableFrom(cls)) { + return RpcException.SERIALIZATION_EXCEPTION; + } + return 0; + } +} diff --git a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml b/dubbo-rpc/dubbo-rpc-avro/pom.xml similarity index 57% rename from dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml rename to dubbo-rpc/dubbo-rpc-avro/pom.xml index 0e6f85553e4..0b1eb507cf3 100644 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/pom.xml +++ b/dubbo-rpc/dubbo-rpc-avro/pom.xml @@ -1,44 +1,47 @@ - +--> + 4.0.0 - ${groupId} - ${rootArtifactId} - ${version} + com.alibaba + dubbo-rpc + 2.8.5-SNAPSHOT - ${artifactId} + dubbo-rpc-avro jar ${project.artifactId} - The demo module of dubbo project + The avro-rpc module of dubbo project true + com.alibaba - dubbo + dubbo-rpc-api + ${project.parent.version} - javax.servlet - javax.servlet-api + org.apache.avro + avro - javax.validation - validation-api + org.apache.avro + avro-ipc - + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-avro/src/main/java/com/alibaba/dubbo/rpc/protocol/avro/AvroProtocol.java b/dubbo-rpc/dubbo-rpc-avro/src/main/java/com/alibaba/dubbo/rpc/protocol/avro/AvroProtocol.java new file mode 100644 index 00000000000..4adabc44a74 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-avro/src/main/java/com/alibaba/dubbo/rpc/protocol/avro/AvroProtocol.java @@ -0,0 +1,76 @@ +package com.alibaba.dubbo.rpc.protocol.avro; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import org.apache.avro.ipc.NettyServer; +import org.apache.avro.ipc.NettyTransceiver; +import org.apache.avro.ipc.Server; +import org.apache.avro.ipc.reflect.ReflectRequestor; +import org.apache.avro.ipc.reflect.ReflectResponder; + +import java.io.IOException; +import java.net.InetSocketAddress; + +/** + * 为dubbo-rpc添加avro支持 + * by 杨俊明(http://yjmyzz.cnblogs.com/) + */ +public class AvroProtocol extends AbstractProxyProtocol { + public static final int DEFAULT_PORT = 40881; + private static final Logger logger = LoggerFactory.getLogger(AvroProtocol.class); + + public AvroProtocol() { + super(IOException.class, RpcException.class); + } + + public int getDefaultPort() { + return DEFAULT_PORT; + } + + @Override + protected Runnable doExport(T impl, Class type, URL url) + throws RpcException { + + logger.info("impl => " + impl.getClass()); + logger.info("type => " + type.getName()); + logger.info("url => " + url); + + final Server server = new NettyServer(new ReflectResponder(type, impl), + new InetSocketAddress(url.getHost(), url.getPort())); + server.start(); + + logger.info("Start Avro Server"); + + return new Runnable() { + public void run() { + try { + logger.info("Close Avro Server"); + server.close(); + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + } + } + }; + } + + @Override + protected T doRefer(Class type, URL url) throws RpcException { + + logger.info("type => " + type.getName()); + logger.info("url => " + url); + + try { + NettyTransceiver client = new NettyTransceiver(new InetSocketAddress(url.getHost(), url.getPort())); + T ref = ReflectRequestor.getClient(type, client); + logger.info("Create Avro Client"); + return ref; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create remoting client for service(" + url + "): " + e.getMessage(), e); + } + } + +} diff --git a/dubbo-rpc/dubbo-rpc-avro/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-avro/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol new file mode 100644 index 00000000000..eb16dd7df50 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-avro/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol @@ -0,0 +1 @@ +avro=com.alibaba.dubbo.rpc.protocol.avro.AvroProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-default/pom.xml b/dubbo-rpc/dubbo-rpc-default/pom.xml index a31250d37db..f8d8aa2739f 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.5-SNAPSHOT dubbo-rpc-default jar @@ -56,16 +56,16 @@ ${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-grpc/pom.xml b/dubbo-rpc/dubbo-rpc-grpc/pom.xml new file mode 100644 index 00000000000..b88c2167274 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-grpc/pom.xml @@ -0,0 +1,58 @@ + + + 4.0.0 + + com.alibaba + dubbo-rpc + 2.8.5-SNAPSHOT + + dubbo-rpc-grpc + jar + ${project.artifactId} + The grpc module of dubbo project + + true + + + + + com.alibaba + dubbo-rpc-api + ${project.parent.version} + + + + + io.grpc + grpc-netty + 1.0.1 + + + io.grpc + grpc-protobuf + 1.0.1 + + + io.grpc + grpc-stub + 1.0.1 + + + + + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-grpc/src/main/java/com/alibaba/dubbo/rpc/protocol/grpc/DefaultBindableService.java b/dubbo-rpc/dubbo-rpc-grpc/src/main/java/com/alibaba/dubbo/rpc/protocol/grpc/DefaultBindableService.java new file mode 100644 index 00000000000..a722e87c8f2 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-grpc/src/main/java/com/alibaba/dubbo/rpc/protocol/grpc/DefaultBindableService.java @@ -0,0 +1,27 @@ +package com.alibaba.dubbo.rpc.protocol.grpc; + +import io.grpc.Channel; +import io.grpc.ServerServiceDefinition; + +/** + * Created by yangjunming on 16/10/7. + */ +public class DefaultBindableService implements GrpcBindableService { + + private Channel channel; + + @Override + public Channel getChannel() { + return channel; + } + + @Override + public void setChannel(Channel channel) { + this.channel = channel; + } + + @Override + public ServerServiceDefinition bindService() { + return null; + } +} diff --git a/dubbo-rpc/dubbo-rpc-grpc/src/main/java/com/alibaba/dubbo/rpc/protocol/grpc/GrpcBindableService.java b/dubbo-rpc/dubbo-rpc-grpc/src/main/java/com/alibaba/dubbo/rpc/protocol/grpc/GrpcBindableService.java new file mode 100644 index 00000000000..c1c57750c29 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-grpc/src/main/java/com/alibaba/dubbo/rpc/protocol/grpc/GrpcBindableService.java @@ -0,0 +1,14 @@ +package com.alibaba.dubbo.rpc.protocol.grpc; + +import io.grpc.BindableService; +import io.grpc.Channel; + +/** + * Created by yangjunming on 16/10/7. + */ +public interface GrpcBindableService extends BindableService { + + Channel getChannel(); + + void setChannel(Channel channel); +} diff --git a/dubbo-rpc/dubbo-rpc-grpc/src/main/java/com/alibaba/dubbo/rpc/protocol/grpc/GrpcProtocol.java b/dubbo-rpc/dubbo-rpc-grpc/src/main/java/com/alibaba/dubbo/rpc/protocol/grpc/GrpcProtocol.java new file mode 100644 index 00000000000..85dc8a21dce --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-grpc/src/main/java/com/alibaba/dubbo/rpc/protocol/grpc/GrpcProtocol.java @@ -0,0 +1,81 @@ +package com.alibaba.dubbo.rpc.protocol.grpc; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.Server; +import io.grpc.ServerBuilder; + +import java.io.IOException; + +/** + * 为dubbo-rpc添加"google-gRPC"支持 + * by 杨俊明(http://yjmyzz.cnblogs.com/) + */ +public class GrpcProtocol extends AbstractProxyProtocol { + public static final int DEFAULT_PORT = 50051; + private static final Logger logger = LoggerFactory.getLogger(GrpcProtocol.class); + + public int getDefaultPort() { + return DEFAULT_PORT; + } + + public GrpcProtocol() { + super(IOException.class, RpcException.class); + } + + @Override + protected Runnable doExport(T impl, Class type, URL url) + throws RpcException { + + logger.info("impl => " + impl.getClass()); + logger.info("type => " + type.getName()); + logger.info("url => " + url); + + try { + String clsName = url.getParameter("class"); + Class cls = Class.forName(clsName); + GrpcBindableService service = (GrpcBindableService) cls.newInstance(); + final Server grpcServer = ServerBuilder.forPort(url.getPort()) + .addService(service) + .build() + .start(); + logger.info("grpc server started !"); + return new Runnable() { + public void run() { + try { + logger.info("Close gRPC Server"); + grpcServer.shutdown(); + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + } + } + }; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException(e.getMessage(), e); + } + } + + @Override + protected T doRefer(Class type, URL url) throws RpcException { + logger.info("type => " + type.getName()); + logger.info("url => " + url); + final ManagedChannel channel = ManagedChannelBuilder.forAddress(url.getHost(), url.getPort()) + .usePlaintext(true) + .build(); + try { + DefaultBindableService service = new DefaultBindableService(); + service.setChannel(channel); + return (T) service; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException(e.getMessage(), e); + } + } + +} diff --git a/dubbo-rpc/dubbo-rpc-grpc/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-grpc/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol new file mode 100644 index 00000000000..e09695d55ef --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-grpc/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol @@ -0,0 +1 @@ +grpc=com.alibaba.dubbo.rpc.protocol.grpc.GrpcProtocol diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml index bf5e50cb4c6..c1b8394ac84 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.5-SNAPSHOT dubbo-rpc-hessian jar diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml index a2ad7c134f3..3687a9bd311 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.5-SNAPSHOT dubbo-rpc-http jar diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java index 84bc398a3fb..3b7c9504073 100644 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java +++ b/dubbo-rpc/dubbo-rpc-http/src/main/java/com/alibaba/dubbo/rpc/protocol/http/HttpProtocol.java @@ -15,22 +15,6 @@ */ package com.alibaba.dubbo.rpc.protocol.http; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.SocketTimeoutException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.remoting.RemoteAccessException; -import org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor; -import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean; -import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter; -import org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor; - import com.alibaba.dubbo.common.Constants; import com.alibaba.dubbo.common.URL; import com.alibaba.dubbo.remoting.http.HttpBinder; @@ -39,22 +23,39 @@ import com.alibaba.dubbo.rpc.RpcContext; import com.alibaba.dubbo.rpc.RpcException; import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import com.alibaba.dubbo.rpc.utils.ErrorCodeUtils; +import org.springframework.remoting.RemoteAccessException; +import org.springframework.remoting.httpinvoker.HttpComponentsHttpInvokerRequestExecutor; +import org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean; +import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter; +import org.springframework.remoting.httpinvoker.SimpleHttpInvokerRequestExecutor; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +//import org.springframework.remoting.httpinvoker.CommonsHttpInvokerRequestExecutor; +//http://forum.spring.io/forum/spring-projects/web/744585-commonshttpinvokerrequestexecutor-in-spring-4-0 /** * HttpProtocol - * + * * @author william.liangf */ public class HttpProtocol extends AbstractProxyProtocol { - public static final int DEFAULT_PORT = 80; + public static final int DEFAULT_PORT = 80; private final Map serverMap = new ConcurrentHashMap(); private final Map skeletonMap = new ConcurrentHashMap(); private HttpBinder httpBinder; - + public HttpProtocol() { super(RemoteAccessException.class); } @@ -68,12 +69,12 @@ public int getDefaultPort() { } private class InternalHandler implements HttpHandler { - + public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String uri = request.getRequestURI(); HttpInvokerServiceExporter skeleton = skeletonMap.get(uri); - if (! request.getMethod().equalsIgnoreCase("POST")) { + if (!request.getMethod().equalsIgnoreCase("POST")) { response.setStatus(500); } else { RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); @@ -84,7 +85,7 @@ public void handle(HttpServletRequest request, HttpServletResponse response) } } } - + } protected Runnable doExport(final T impl, Class type, URL url) throws RpcException { @@ -118,21 +119,22 @@ protected T doRefer(final Class serviceType, final URL url) throws RpcExc httpProxyFactoryBean.setServiceInterface(serviceType); String client = url.getParameter(Constants.CLIENT_KEY); if (client == null || client.length() == 0 || "simple".equals(client)) { - SimpleHttpInvokerRequestExecutor httpInvokerRequestExecutor = new SimpleHttpInvokerRequestExecutor() { - protected void prepareConnection(HttpURLConnection con, - int contentLength) throws IOException { - super.prepareConnection(con, contentLength); - con.setReadTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); - con.setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); - } - }; - httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); + SimpleHttpInvokerRequestExecutor httpInvokerRequestExecutor = new SimpleHttpInvokerRequestExecutor() { + protected void prepareConnection(HttpURLConnection con, + int contentLength) throws IOException { + super.prepareConnection(con, contentLength); + con.setReadTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + con.setConnectTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); + } + }; + httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); } else if ("commons".equals(client)) { - CommonsHttpInvokerRequestExecutor httpInvokerRequestExecutor = new CommonsHttpInvokerRequestExecutor(); - httpInvokerRequestExecutor.setReadTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); - httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); + HttpComponentsHttpInvokerRequestExecutor httpInvokerRequestExecutor = new HttpComponentsHttpInvokerRequestExecutor(); + //CommonsHttpInvokerRequestExecutor httpInvokerRequestExecutor = new CommonsHttpInvokerRequestExecutor(); + httpInvokerRequestExecutor.setReadTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); + httpProxyFactoryBean.setHttpInvokerRequestExecutor(httpInvokerRequestExecutor); } else if (client != null && client.length() > 0) { - throw new IllegalStateException("Unsupported http protocol client " + client + ", only supported: simple, commons"); + throw new IllegalStateException("Unsupported http protocol client " + client + ", only supported: simple, commons"); } httpProxyFactoryBean.afterPropertiesSet(); return (T) httpProxyFactoryBean.getObject(); @@ -144,16 +146,19 @@ protected int getErrorCode(Throwable e) { } if (e != null) { Class cls = e.getClass(); - // 是根据测试Case发现的问题,对RpcException.setCode进行设置 - if (SocketTimeoutException.class.equals(cls)) { - return RpcException.TIMEOUT_EXCEPTION; - } else if (IOException.class.isAssignableFrom(cls)) { - return RpcException.NETWORK_EXCEPTION; - } else if (ClassNotFoundException.class.isAssignableFrom(cls)) { - return RpcException.SERIALIZATION_EXCEPTION; - } +// // 是根据测试Case发现的问题,对RpcException.setCode进行设置 +// if (SocketTimeoutException.class.equals(cls)) { +// return RpcException.TIMEOUT_EXCEPTION; +// } else if (IOException.class.isAssignableFrom(cls)) { +// return RpcException.NETWORK_EXCEPTION; +// } else if (ClassNotFoundException.class.isAssignableFrom(cls)) { +// return RpcException.SERIALIZATION_EXCEPTION; +// } + return ErrorCodeUtils.getErrorCode(e, cls); + } return super.getErrorCode(e); } + } \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-injvm/pom.xml b/dubbo-rpc/dubbo-rpc-injvm/pom.xml index dcdda8d5345..d4f7a02a77a 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.5-SNAPSHOT dubbo-rpc-injvm jar diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml index 6a2af14c3c6..81878594349 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.5-SNAPSHOT dubbo-rpc-memcached jar diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml index 9e39b9fa31f..4fb7ad1000b 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.5-SNAPSHOT dubbo-rpc-redis jar diff --git a/dubbo-rpc/dubbo-rpc-rest/pom.xml b/dubbo-rpc/dubbo-rpc-rest/pom.xml index 11edf84ca91..a470ea54957 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.5-SNAPSHOT dubbo-rpc-rest jar diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml index 84b76b9a059..d430231e558 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.5-SNAPSHOT dubbo-rpc-rmi jar diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiProtocol.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiProtocol.java index 79c8a834172..ef83b9ad5fc 100644 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiProtocol.java +++ b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiProtocol.java @@ -15,26 +15,24 @@ */ package com.alibaba.dubbo.rpc.protocol.rmi; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.rmi.RemoteException; - +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import com.alibaba.dubbo.rpc.utils.ErrorCodeUtils; import org.springframework.remoting.RemoteAccessException; import org.springframework.remoting.rmi.RmiProxyFactoryBean; import org.springframework.remoting.rmi.RmiServiceExporter; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import java.rmi.RemoteException; /** * RmiProtocol. - * + * * @author qian.lei */ public class RmiProtocol extends AbstractProxyProtocol { - public static final int DEFAULT_PORT = 1099; + public static final int DEFAULT_PORT = 1099; public RmiProtocol() { super(RemoteAccessException.class, RemoteException.class); @@ -84,14 +82,15 @@ protected int getErrorCode(Throwable e) { } if (e != null && e.getCause() != null) { Class cls = e.getCause().getClass(); - // 是根据测试Case发现的问题,对RpcException.setCode进行设置 - if (SocketTimeoutException.class.equals(cls)) { - return RpcException.TIMEOUT_EXCEPTION; - } else if (IOException.class.isAssignableFrom(cls)) { - return RpcException.NETWORK_EXCEPTION; - } else if (ClassNotFoundException.class.isAssignableFrom(cls)) { - return RpcException.SERIALIZATION_EXCEPTION; - } +// // 是根据测试Case发现的问题,对RpcException.setCode进行设置 +// if (SocketTimeoutException.class.equals(cls)) { +// return RpcException.TIMEOUT_EXCEPTION; +// } else if (IOException.class.isAssignableFrom(cls)) { +// return RpcException.NETWORK_EXCEPTION; +// } else if (ClassNotFoundException.class.isAssignableFrom(cls)) { +// return RpcException.SERIALIZATION_EXCEPTION; +// } + return ErrorCodeUtils.getErrorCode(e, cls); } return super.getErrorCode(e); } diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml deleted file mode 100644 index 4b5d5d075ec..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ /dev/null @@ -1,79 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-rpc - 2.8.4 - - dubbo-rpc-thrift - jar - ${project.artifactId} - The thrift rpc module of dubbo project - - true - - - - com.alibaba - dubbo-rpc-api - ${project.parent.version} - - - com.alibaba - dubbo-rpc-default - ${project.parent.version} - - - com.alibaba - dubbo-remoting-api - ${project.parent.version} - - - com.alibaba - dubbo-remoting-netty - ${project.parent.version} - - - org.apache.thrift - libthrift - - - org.apache.httpcomponents - httpcore - - - - - org.apache.httpcomponents - httpclient - - - com.alibaba - dubbo-config-spring - ${project.parent.version} - test - - - com.alibaba - dubbo-registry-multicast - ${project.parent.version} - test - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ClassNameGenerator.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ClassNameGenerator.java deleted file mode 100644 index 36e5eda2821..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ClassNameGenerator.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * File Created at 2012-02-02 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.extension.SPI; - -/** - * @author kimi - */ -@SPI( DubboClassNameGenerator.NAME ) -public interface ClassNameGenerator { - - public String generateArgsClassName( String serviceName, String methodName ); - - public String generateResultClassName( String serviceName, String methodName ); - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboClassNameGenerator.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboClassNameGenerator.java deleted file mode 100644 index ab9d70832bc..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboClassNameGenerator.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * File Created at 2012-02-02 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -/** - * @author kimi - */ -public class DubboClassNameGenerator implements ClassNameGenerator { - - public static final String NAME = "dubbo"; - - public String generateArgsClassName( String serviceName, String methodName ) { - return ThriftUtils.generateMethodArgsClassName( serviceName, methodName ); - } - - public String generateResultClassName( String serviceName, String methodName ) { - return ThriftUtils.generateMethodResultClassName( serviceName, methodName ); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftClassNameGenerator.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftClassNameGenerator.java deleted file mode 100644 index 5c34c222f25..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftClassNameGenerator.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * File Created at 2012-02-02 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -/** - * @author kimi - */ -public class ThriftClassNameGenerator implements ClassNameGenerator { - - public static final String NAME = "thrift"; - - public String generateArgsClassName( String serviceName, String methodName ) { - return ThriftUtils.generateMethodArgsClassNameThrift( serviceName, methodName ); - } - - public String generateResultClassName( String serviceName, String methodName ) { - return ThriftUtils.generateMethodResultClassNameThrift( serviceName, methodName ); - } - -} 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 deleted file mode 100644 index 6c4dee9837f..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ /dev/null @@ -1,719 +0,0 @@ -/** - * File Created at 2011-12-05 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - - -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; -import org.apache.thrift.TException; -import org.apache.thrift.TFieldIdEnum; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TIOStreamTransport; - -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.Codec2; -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. - * - *
- * |<-                                  message header                                  ->|<- message body ->|
- * +----------------+----------------------+------------------+---------------------------+------------------+
- * | magic (2 bytes)|message size (4 bytes)|head size(2 bytes)| version (1 byte) | header |   message body   |
- * +----------------+----------------------+------------------+---------------------------+------------------+
- * |<-                                               message size                                          ->|
- * 
- * - *

- * header fields in version 1 - *

    - *
  1. string - service name
  2. - *
  3. long - dubbo request id
  4. - *
- *

- * - * @author gang.lvg - */ -public class ThriftCodec implements Codec2 { - - private static final AtomicInteger THRIFT_SEQ_ID = new AtomicInteger( 0 ); - - private static final ConcurrentMap> cachedClass = - new ConcurrentHashMap>(); - - static final ConcurrentMap cachedRequest = - new ConcurrentHashMap(); - - public static final int MESSAGE_LENGTH_INDEX = 2; - - public static final int MESSAGE_HEADER_LENGTH_INDEX = 6; - - public static final int MESSAGE_SHORTEST_LENGTH = 10; - - public static final String NAME = "thrift"; - - public static final String PARAMETER_CLASS_NAME_GENERATOR = "class.name.generator"; - - public static final byte VERSION = (byte)1; - - public static final short MAGIC = (short) 0xdabc; - - public void encode( Channel channel, ChannelBuffer buffer, Object message ) - throws IOException { - - if ( message instanceof Request ) { - encodeRequest( channel, buffer, ( Request ) message ); - } - else if ( message instanceof Response ) { - encodeResponse( channel, buffer, ( Response ) message ); - } else { - throw new UnsupportedOperationException( - new StringBuilder( 32 ) - .append( "Thrift codec only support encode " ) - .append( Request.class.getName() ) - .append( " and " ) - .append( Response.class.getName() ) - .toString() ); - } - - } - - public Object decode( Channel channel, ChannelBuffer buffer ) throws IOException { - - int available = buffer.readableBytes(); - - if ( available < MESSAGE_SHORTEST_LENGTH ) { - - return DecodeResult.NEED_MORE_INPUT; - - } else { - - TIOStreamTransport transport = new TIOStreamTransport( new ChannelBufferInputStream(buffer)); - - TBinaryProtocol protocol = new TBinaryProtocol( transport ); - - short magic; - int messageLength; - - try{ -// protocol.readI32(); // skip the first message length - byte[] bytes = new byte[4]; - transport.read( bytes, 0, 4 ); - magic = protocol.readI16(); - messageLength = protocol.readI32(); - - } catch ( TException e ) { - throw new IOException( e.getMessage(), e ); - } - - if ( MAGIC != magic ) { - throw new IOException( - new StringBuilder( 32 ) - .append( "Unknown magic code " ) - .append( magic ) - .toString() ); - } - - if ( available < messageLength ) { return DecodeResult.NEED_MORE_INPUT; } - - return decode( protocol ); - - } - - } - - private Object decode( TProtocol protocol ) - throws IOException { - - // version - String serviceName; - long id; - - TMessage message; - - try { - protocol.readI16(); - protocol.readByte(); - serviceName = protocol.readString(); - id = protocol.readI64(); - message = protocol.readMessageBegin(); - } catch ( TException e ) { - throw new IOException( e.getMessage(), e ); - } - - if ( message.type == TMessageType.CALL ) { - - RpcInvocation result = new RpcInvocation(); - result.setAttachment(Constants.INTERFACE_KEY, serviceName ); - result.setMethodName( message.name ); - - String argsClassName = ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) - .getExtension(ThriftClassNameGenerator.NAME).generateArgsClassName( serviceName, message.name ); - - if ( StringUtils.isEmpty( argsClassName ) ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, - "The specified interface name incorrect." ); - } - - Class clazz = cachedClass.get( argsClassName ); - - if ( clazz == null ) { - try { - - clazz = ClassHelper.forNameWithThreadContextClassLoader( argsClassName ); - - cachedClass.putIfAbsent( argsClassName, clazz ); - - } catch ( ClassNotFoundException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - } - - TBase args; - - try { - args = ( TBase ) clazz.newInstance(); - } catch ( InstantiationException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - try{ - args.read( protocol ); - protocol.readMessageEnd(); - } catch ( TException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - List parameters = new ArrayList(); - List> parameterTypes =new ArrayList>(); - int index = 1; - - while ( true ) { - - TFieldIdEnum fieldIdEnum = args.fieldForId( index++ ); - - if ( fieldIdEnum == null ) { break; } - - String fieldName = fieldIdEnum.getFieldName(); - - String getMethodName = ThriftUtils.generateGetMethodName( fieldName ); - - Method getMethod; - - try { - getMethod = clazz.getMethod( getMethodName ); - } catch ( NoSuchMethodException e ) { - throw new RpcException( - RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - parameterTypes.add( getMethod.getReturnType() ); - try { - parameters.add( getMethod.invoke( args ) ); - } catch ( IllegalAccessException e ) { - throw new RpcException( - RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( InvocationTargetException e ) { - throw new RpcException( - RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - } - - result.setArguments( parameters.toArray() ); - result.setParameterTypes(parameterTypes.toArray(new Class[parameterTypes.size()])); - - Request request = new Request( id ); - request.setData( result ); - - cachedRequest.putIfAbsent( id, - RequestData.create( message.seqid, serviceName, message.name ) ); - - return request; - - } else if ( message.type == TMessageType.EXCEPTION ) { - - TApplicationException exception; - - try { - exception = TApplicationException.read( protocol ); - protocol.readMessageEnd(); - } catch ( TException e ) { - throw new IOException( e.getMessage(), e ); - } - - RpcResult result = new RpcResult(); - - result.setException( new RpcException( exception.getMessage() ) ); - - Response response = new Response(); - - response.setResult( result ); - - response.setId( id ); - - return response; - - } else if ( message.type == TMessageType.REPLY ) { - - String resultClassName = ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ) - .getExtension(ThriftClassNameGenerator.NAME).generateResultClassName( serviceName, message.name ); - - if ( StringUtils.isEmpty( resultClassName ) ) { - throw new IllegalArgumentException( - new StringBuilder( 32 ) - .append( "Could not infer service result class name from service name " ) - .append( serviceName ) - .append( ", the service name you specified may not generated by thrift idl compiler" ) - .toString() ); - } - - Class clazz = cachedClass.get( resultClassName ); - - if ( clazz == null ) { - - try { - - clazz = ClassHelper.forNameWithThreadContextClassLoader( resultClassName ); - - cachedClass.putIfAbsent( resultClassName, clazz ); - - } catch ( ClassNotFoundException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - } - - TBase result; - try { - result = ( TBase ) clazz.newInstance(); - } catch ( InstantiationException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - try { - result.read( protocol ); - protocol.readMessageEnd(); - } catch ( TException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - Object realResult = null; - - int index = 0; - - while ( true ) { - - TFieldIdEnum fieldIdEnum = result.fieldForId( index++ ); - - if ( fieldIdEnum == null ) { break ; } - - Field field; - - try { - field = clazz.getDeclaredField( fieldIdEnum.getFieldName() ); - field.setAccessible( true ); - } catch ( NoSuchFieldException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - try { - realResult = field.get( result ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - if ( realResult != null ) { break ; } - - } - - Response response = new Response(); - - response.setId( id ); - - RpcResult rpcResult = new RpcResult(); - - if ( realResult instanceof Throwable ) { - rpcResult.setException( ( Throwable ) realResult ); - } else { - rpcResult.setValue(realResult); - } - - response.setResult( rpcResult ); - - return response; - - } else { - // Impossible - throw new IOException( ); - } - - } - - private void encodeRequest( Channel channel, ChannelBuffer buffer, Request request ) - throws IOException { - - RpcInvocation inv = ( RpcInvocation ) request.getData(); - - int seqId = nextSeqId(); - - String serviceName = inv.getAttachment(Constants.INTERFACE_KEY); - - if ( StringUtils.isEmpty( serviceName ) ) { - throw new IllegalArgumentException( - new StringBuilder( 32 ) - .append( "Could not find service name in attachment with key " ) - .append(Constants.INTERFACE_KEY) - .toString() ); - } - - TMessage message = new TMessage( - inv.getMethodName(), - TMessageType.CALL, - seqId ); - - String methodArgs = ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ) - .getExtension(channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME)) - .generateArgsClassName(serviceName, inv.getMethodName()); - - if ( StringUtils.isEmpty( methodArgs ) ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, - new StringBuilder(32).append( - "Could not encode request, the specified interface may be incorrect." ).toString() ); - } - - Class clazz = cachedClass.get( methodArgs ); - - if ( clazz == null ) { - - try { - - clazz = ClassHelper.forNameWithThreadContextClassLoader( methodArgs ); - - cachedClass.putIfAbsent( methodArgs, clazz ); - - } catch ( ClassNotFoundException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - } - - TBase args; - - try { - args = (TBase) clazz.newInstance(); - } catch ( InstantiationException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - for( int i = 0; i < inv.getArguments().length; i++ ) { - - Object obj = inv.getArguments()[i]; - - if ( obj == null ) { continue; } - - TFieldIdEnum field = args.fieldForId( i + 1 ); - - String setMethodName = ThriftUtils.generateSetMethodName( field.getFieldName() ); - - Method method; - - try { - method = clazz.getMethod( setMethodName, inv.getParameterTypes()[i] ); - } catch ( NoSuchMethodException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - try { - method.invoke( args, obj ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( InvocationTargetException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - } - - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 1024 ); - - TIOStreamTransport transport = new TIOStreamTransport( bos ); - - TBinaryProtocol protocol = new TBinaryProtocol( transport ); - - int headerLength, messageLength; - - byte[] bytes = new byte[4]; - try { - // magic - protocol.writeI16( MAGIC ); - // message length placeholder - protocol.writeI32( Integer.MAX_VALUE ); - // message header length placeholder - protocol.writeI16( Short.MAX_VALUE ); - // version - protocol.writeByte( VERSION ); - // service name - protocol.writeString( serviceName ); - // dubbo request id - protocol.writeI64( request.getId() ); - protocol.getTransport().flush(); - // header size - headerLength = bos.size(); - - // message body - protocol.writeMessageBegin( message ); - args.write( protocol ); - protocol.writeMessageEnd(); - protocol.getTransport().flush(); - int oldIndex = messageLength = bos.size(); - - // fill in message length and header length - try { - TFramedTransport.encodeFrameSize( messageLength, bytes ); - bos.setWriteIndex( MESSAGE_LENGTH_INDEX ); - protocol.writeI32( messageLength ); - bos.setWriteIndex( MESSAGE_HEADER_LENGTH_INDEX ); - protocol.writeI16( ( short )( 0xffff & headerLength ) ); - } finally { - bos.setWriteIndex( oldIndex ); - } - - } catch ( TException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - buffer.writeBytes(bytes); - buffer.writeBytes(bos.toByteArray()); - - } - - private void encodeResponse( Channel channel, ChannelBuffer buffer, Response response ) - throws IOException { - - RpcResult result = ( RpcResult ) response.getResult(); - - RequestData rd = cachedRequest.get( response.getId() ); - - String resultClassName = ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ).getExtension( - channel.getUrl().getParameter(ThriftConstants.CLASS_NAME_GENERATOR_KEY, ThriftClassNameGenerator.NAME)) - .generateResultClassName(rd.serviceName, rd.methodName); - - if ( StringUtils.isEmpty( resultClassName ) ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, - new StringBuilder( 32 ).append( - "Could not encode response, the specified interface may be incorrect." ).toString() ); - } - - Class clazz = cachedClass.get( resultClassName ); - - if ( clazz == null ) { - - try { - clazz = ClassHelper.forNameWithThreadContextClassLoader(resultClassName); - cachedClass.putIfAbsent( resultClassName, clazz ); - } catch ( ClassNotFoundException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - } - - TBase resultObj; - - try { - resultObj = ( TBase ) clazz.newInstance(); - } catch ( InstantiationException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - TApplicationException applicationException = null; - TMessage message; - - if ( result.hasException() ) { - Throwable throwable = result.getException(); - int index = 1; - boolean found = false; - while ( true ) { - TFieldIdEnum fieldIdEnum = resultObj.fieldForId( index++ ); - if ( fieldIdEnum == null ) { break; } - String fieldName = fieldIdEnum.getFieldName(); - String getMethodName = ThriftUtils.generateGetMethodName( fieldName ); - String setMethodName = ThriftUtils.generateSetMethodName( fieldName ); - Method getMethod; - Method setMethod; - try { - getMethod = clazz.getMethod( getMethodName ); - if ( getMethod.getReturnType().equals( throwable.getClass() ) ) { - found = true; - setMethod = clazz.getMethod( setMethodName, throwable.getClass() ); - setMethod.invoke( resultObj, throwable ); - } - } catch ( NoSuchMethodException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( InvocationTargetException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - } - - if ( !found ) { - applicationException = new TApplicationException( throwable.getMessage() ); - } - - } else { - Object realResult = result.getResult(); - // result field id is 0 - String fieldName = resultObj.fieldForId( 0 ).getFieldName(); - String setMethodName = ThriftUtils.generateSetMethodName( fieldName ); - String getMethodName = ThriftUtils.generateGetMethodName( fieldName ); - Method getMethod; - Method setMethod; - try { - getMethod = clazz.getMethod( getMethodName ); - setMethod = clazz.getMethod( setMethodName, getMethod.getReturnType() ); - setMethod.invoke( resultObj, realResult ); - } catch ( NoSuchMethodException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( InvocationTargetException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } catch ( IllegalAccessException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - } - - if ( applicationException != null ) { - message = new TMessage( rd.methodName, TMessageType.EXCEPTION, rd.id ); - } else { - message = new TMessage( rd.methodName, TMessageType.REPLY, rd.id ); - } - - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 1024 ); - - TIOStreamTransport transport = new TIOStreamTransport( bos ); - - TBinaryProtocol protocol = new TBinaryProtocol( transport ); - - int messageLength; - int headerLength; - - byte[] bytes = new byte[4]; - try { - // magic - protocol.writeI16( MAGIC ); - // message length - protocol.writeI32( Integer.MAX_VALUE ); - // message header length - protocol.writeI16( Short.MAX_VALUE ); - // version - protocol.writeByte( VERSION ); - // service name - protocol.writeString( rd.serviceName ); - // id - protocol.writeI64( response.getId() ); - protocol.getTransport().flush(); - headerLength = bos.size(); - - // message - protocol.writeMessageBegin( message ); - switch ( message.type ) { - case TMessageType.EXCEPTION: - applicationException.write( protocol ); - break; - case TMessageType.REPLY: - resultObj.write( protocol ); - break; - } - protocol.writeMessageEnd(); - protocol.getTransport().flush(); - int oldIndex = messageLength = bos.size(); - - try{ - TFramedTransport.encodeFrameSize( messageLength, bytes ); - bos.setWriteIndex( MESSAGE_LENGTH_INDEX ); - protocol.writeI32( messageLength ); - bos.setWriteIndex( MESSAGE_HEADER_LENGTH_INDEX ); - protocol.writeI16( ( short ) ( 0xffff & headerLength ) ); - } finally { - bos.setWriteIndex( oldIndex ); - } - - } catch ( TException e ) { - throw new RpcException( RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e ); - } - - buffer.writeBytes(bytes); - buffer.writeBytes(bos.toByteArray()); - - } - - private static int nextSeqId() { - return THRIFT_SEQ_ID.incrementAndGet(); - } - - // just for test - static int getSeqId() { - return THRIFT_SEQ_ID.get(); - } - - static class RequestData { - int id; - String serviceName; - String methodName; - - static RequestData create( int id, String sn, String mn ) { - RequestData result = new RequestData(); - result.id = id; - result.serviceName = sn; - result.methodName = mn; - return result; - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftConstants.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftConstants.java deleted file mode 100644 index 7bf67ad04ae..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftConstants.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift; - -/** - * @author kimi - */ -public final class ThriftConstants { - - public static final String THRIFT_PROTOCOL_KEY = "thrift.protocol"; - public static final String BINARY_THRIFT_PROTOCOL = "binary"; - public static final String CLASS_NAME_GENERATOR_KEY = "class.name.generator"; - public static final String DEFAULT_PROTOCOL = BINARY_THRIFT_PROTOCOL; - - private ThriftConstants() {} - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java deleted file mode 100644 index d893fcdb106..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftInvoker.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * File Created at 2011-12-06 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.AtomicPositiveInteger; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.TimeoutException; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -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 com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.protocol.AbstractInvoker; - -import java.util.Set; -import java.util.concurrent.locks.ReentrantLock; - - -/** - * @author gang.lvg - */ -public class ThriftInvoker extends AbstractInvoker { - - private final ExchangeClient[] clients; - - private final AtomicPositiveInteger index = new AtomicPositiveInteger(); - - private final ReentrantLock destroyLock = new ReentrantLock(); - - private final Set> invokers; - - public ThriftInvoker( Class service, URL url, ExchangeClient[] clients ) { - this(service, url, clients, null); - } - - public ThriftInvoker(Class type, URL url, ExchangeClient[] clients, Set> invokers) { - super(type, url, - new String[]{Constants.INTERFACE_KEY, Constants.GROUP_KEY, - Constants.TOKEN_KEY, Constants.TIMEOUT_KEY}); - this.clients = clients; - this.invokers = invokers; - } - - @Override - protected Result doInvoke( Invocation invocation ) throws Throwable { - - RpcInvocation inv = (RpcInvocation) invocation; - - final String methodName; - - methodName = invocation.getMethodName(); - - inv.setAttachment( Constants.PATH_KEY, getUrl().getPath() ); - - // for thrift codec - inv.setAttachment( ThriftCodec.PARAMETER_CLASS_NAME_GENERATOR, getUrl().getParameter( - ThriftCodec.PARAMETER_CLASS_NAME_GENERATOR, DubboClassNameGenerator.NAME ) ); - - ExchangeClient currentClient; - - if (clients.length == 1) { - currentClient = clients[0]; - } else { - currentClient = clients[index.getAndIncrement() % clients.length]; - } - - try { - int timeout = getUrl().getMethodParameter( - methodName, Constants.TIMEOUT_KEY,Constants.DEFAULT_TIMEOUT); - - RpcContext.getContext().setFuture(null); - - return (Result) currentClient.request(inv, timeout).get(); - - } catch (TimeoutException e) { - throw new RpcException(RpcException.TIMEOUT_EXCEPTION, e.getMessage(), e); - } catch (RemotingException e) { - throw new RpcException(RpcException.NETWORK_EXCEPTION, e.getMessage(), e); - } - - } - - @Override - public boolean isAvailable() { - - if (!super.isAvailable()) { - return false; - } - - for (ExchangeClient client : clients){ - if (client.isConnected() - && !client.hasAttribute(Constants.CHANNEL_ATTRIBUTE_READONLY_KEY)){ - //cannot write == not Available ? - return true ; - } - } - return false; - } - - public void destroy() { - //防止client被关闭多次.在connect per jvm的情况下,client.close方法会调用计数器-1,当计数器小于等于0的情况下,才真正关闭 - if (super.isDestroyed()){ - return ; - } else { - //dubbo check ,避免多次关闭 - destroyLock.lock(); - - try{ - - if (super.isDestroyed()){ - return ; - } - - super.destroy(); - - if(invokers != null) { - invokers.remove(this); - } - - for (ExchangeClient client : clients) { - - try { - client.close(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - - } - - }finally { - destroyLock.unlock(); - } - - } - - } - -} 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 deleted file mode 100644 index a02180e09f5..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import java.io.IOException; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.thrift.TException; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.protocol.TStruct; -import org.apache.thrift.transport.TIOStreamTransport; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.remoting.Channel; -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; -import com.alibaba.dubbo.remoting.exchange.Response; -import com.alibaba.dubbo.rpc.Invocation; - -/** - * @author kimi - */ -public class ThriftNativeCodec implements Codec2 { - - private final AtomicInteger thriftSeq = new AtomicInteger(0); - - public void encode(Channel channel, ChannelBuffer buffer, Object message) - throws IOException { - if (message instanceof Request) { - encodeRequest(channel, buffer, (Request)message); - } else if (message instanceof Response) { - encodeResponse(channel, buffer, (Response)message); - } else { - throw new IOException("Unsupported message type " - + message.getClass().getName()); - } - } - - protected void encodeRequest(Channel channel, ChannelBuffer buffer, Request request) - throws IOException { - Invocation invocation = (Invocation) request.getData(); - TProtocol protocol = newProtocol(channel.getUrl(), buffer); - try { - protocol.writeMessageBegin(new TMessage( - invocation.getMethodName(), TMessageType.CALL, - thriftSeq.getAndIncrement())); - protocol.writeStructBegin(new TStruct(invocation.getMethodName() + "_args")); - for(int i = 0; i < invocation.getParameterTypes().length; i++) { - Class type = invocation.getParameterTypes()[i]; - - } - } catch (TException e) { - throw new IOException(e.getMessage(), e); - } - - } - - protected void encodeResponse(Channel channel, ChannelBuffer buffer, Response response) - throws IOException { - - } - - public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { - return null; - } - - 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(new ChannelBufferOutputStream(buffer))); - } - throw new IOException("Unsupported protocol type " + protocol); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocol.java deleted file mode 100644 index e5ce6205c42..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocol.java +++ /dev/null @@ -1,213 +0,0 @@ -/** - * File Created at 2011-12-06 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -import java.util.ArrayList; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.Transporter; -import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -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.exchange.support.ExchangeHandlerAdapter; -import com.alibaba.dubbo.rpc.Exporter; -import com.alibaba.dubbo.rpc.Invocation; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.protocol.AbstractProtocol; -import com.alibaba.dubbo.rpc.protocol.dubbo.DubboExporter; - -/** - * @author gang.lvg - */ -public class ThriftProtocol extends AbstractProtocol { - - public static final int DEFAULT_PORT = 40880; - - public static final String NAME = "thrift"; - - // ip:port -> ExchangeServer - private final ConcurrentMap serverMap = - new ConcurrentHashMap(); - - private ExchangeHandler handler = new ExchangeHandlerAdapter() { - - @Override - public Object reply( ExchangeChannel channel, Object msg ) throws RemotingException { - - if ( msg instanceof Invocation ) { - Invocation inv = ( Invocation ) msg; - String serviceName = inv.getAttachments().get(Constants.INTERFACE_KEY); - String serviceKey = serviceKey( channel.getLocalAddress().getPort(), - serviceName, null, null ); - 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:"+ msg); - } - - RpcContext.getContext().setRemoteAddress(channel.getRemoteAddress()); - return exporter.getInvoker().invoke( inv ); - - } - - throw new RemotingException(channel, - "Unsupported request: " - + (msg.getClass().getName() + ": " + msg) - + ", channel: consumer: " - + channel.getRemoteAddress() - + " --> provider: " - + channel.getLocalAddress()); - } - - @Override - public void received( Channel channel, Object message ) throws RemotingException { - if ( message instanceof Invocation ) { - reply( ( ExchangeChannel ) channel, message ); - } else { - super.received( channel, message ); - } - } - - }; - - public int getDefaultPort() { - return DEFAULT_PORT; - } - - public Exporter export( Invoker invoker ) throws RpcException { - - // 只能使用 thrift codec - URL url = invoker.getUrl().addParameter(Constants.CODEC_KEY, ThriftCodec.NAME); - // find server. - String key = url.getAddress(); - //client 也可以暴露一个只有server可以调用的服务。 - boolean isServer = url.getParameter(Constants.IS_SERVER_KEY,true); - if (isServer && ! serverMap.containsKey(key)) { - serverMap.put(key, getServer(url)); - } - // export service. - key = serviceKey(url); - DubboExporter exporter = new DubboExporter(invoker, key, exporterMap); - exporterMap.put(key, exporter); - - return exporter; - } - - public void destroy() { - - super.destroy(); - - for (String key : new ArrayList(serverMap.keySet())) { - - ExchangeServer server = serverMap.remove(key); - - if (server != null) { - try { - if (logger.isInfoEnabled()) { - logger.info("Close dubbo server: " + server.getLocalAddress()); - } - server.close(getServerShutdownTimeout()); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } // ~ end of if ( server != null ) - - } // ~ end of loop serverMap - - } // ~ end of method destroy - - public Invoker refer( Class type, URL url ) throws RpcException { - - ThriftInvoker invoker = new ThriftInvoker(type, url, getClients(url), invokers); - - invokers.add(invoker); - - return invoker; - - } - - private ExchangeClient[] getClients(URL url){ - - int connections = url.getParameter(Constants.CONNECTIONS_KEY, 1); - - ExchangeClient[] clients = new ExchangeClient[connections]; - - for (int i = 0; i < clients.length; i++) { - clients[i] = initClient(url); - } - return clients; - } - - private ExchangeClient initClient(URL url) { - - ExchangeClient client ; - - url = url.addParameter( Constants.CODEC_KEY, ThriftCodec.NAME ); - - try { - client = Exchangers.connect( url ); - } catch ( RemotingException e ) { - throw new RpcException( "Fail to create remoting client for service(" + url - + "): " + e.getMessage(), e ); - } - - return client; - - } - - private ExchangeServer getServer(URL url) { - //默认开启server关闭时发送readonly事件 - url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); - String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER); - - if (str != null && str.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) - throw new RpcException("Unsupported server type: " + str + ", url: " + url); - - ExchangeServer server; - try { - server = Exchangers.bind(url, handler); - } catch (RemotingException e) { - throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e); - } - str = url.getParameter(Constants.CLIENT_KEY); - if (str != null && str.length() > 0) { - Set supportedTypes = ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions(); - if (!supportedTypes.contains(str)) { - throw new RpcException("Unsupported client type: " + str); - } - } - return server; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftType.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftType.java deleted file mode 100644 index f8a44e04794..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftType.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author kimi - */ -public enum ThriftType { - - BOOL, BYTE, I16, I32, I64, DOUBLE, STRING; - - public static ThriftType get(Class key) { - if (key != null) { - return types.get(key); - } - throw new NullPointerException("key == null"); - } - - private static final Map, ThriftType> types = - new HashMap, ThriftType>(); - - private static void put(Class key, ThriftType value) { - types.put(key, value); - } - static { - put(boolean.class, BOOL); - put(Boolean.class, BOOL); - put(byte.class, BYTE); - put(Byte.class, BYTE); - put(short.class, I16); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtils.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtils.java deleted file mode 100644 index 15f3f622ca0..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtils.java +++ /dev/null @@ -1,132 +0,0 @@ -/** - * File Created at 2011-12-05 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -/** - * @author gang.lvg - */ -public class ThriftUtils { - - /** - * Generate class name which represents service arguments. - * - * @param serviceName service name - * @param methodName method name - * @return method args class name or null - */ - public static String generateMethodArgsClassName( String serviceName, String methodName ) { - - int index = serviceName.lastIndexOf( "." ); - - if ( index > 0 ) { - - return new StringBuilder( 32 ) - .append( serviceName.substring( 0, index + 1 ) ) - .append( "$__" ) - .append( serviceName.substring( index + 1 ) ) - .append( "Stub$" ) - .append( methodName ) - .append( "_args" ) - .toString(); - - } else { - return new StringBuffer( 32 ) - .append( "$__" ) - .append( serviceName ) - .append( "Stub$" ) - .append( methodName ) - .append( "_args" ) - .toString(); - } - - } - - public static String generateMethodResultClassName( String serviceName, String method ) { - - int index = serviceName.lastIndexOf( "." ); - - if ( index > 0 ) { - - return new StringBuilder( 32 ) - .append( serviceName.substring( 0, index + 1 ) ) - .append( "$__" ) - .append( serviceName.substring( index + 1 ) ) - .append( "Stub$" ) - .append( method ) - .append( "_result" ) - .toString(); - - } else { - return new StringBuilder( 32 ) - .append( "$__" ) - .append( serviceName ) - .append( "Stub$" ) - .append( method ) - .append( "_result" ) - .toString(); - } - - } - - public static String generateSetMethodName( String fieldName ) { - - return new StringBuilder( 16 ) - .append( "set" ) - .append( Character.toUpperCase( fieldName.charAt( 0 ) ) ) - .append( fieldName.substring( 1 ) ) - .toString(); - - } - - public static String generateGetMethodName( String fieldName ) { - return new StringBuffer( 16 ) - .append( "get" ) - .append( Character.toUpperCase( fieldName.charAt( 0 ) ) ) - .append( fieldName.substring( 1 ) ) - .toString(); - } - - public static String generateMethodArgsClassNameThrift( String serviceName, String methodName ) { - - int index = serviceName.indexOf( "$" ); - - if ( index > 0 ) { - return new StringBuilder( 32 ) - .append( serviceName.substring( 0, index + 1 ) ) - .append( methodName ) - .append( "_args" ) - .toString(); - } - - return null; - - } - - public static String generateMethodResultClassNameThrift( String serviceName, String methodName ) { - - int index = serviceName.indexOf( "$" ); - - if ( index > 0 ) { - return new StringBuilder( 32 ) - .append( serviceName.substring( 0, index + 1 ) ) - .append( methodName ) - .append( "_result" ) - .toString(); - } - - return null; - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java deleted file mode 100644 index c4ef07b8b03..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java +++ /dev/null @@ -1,122 +0,0 @@ -/** - * File Created at 2011-12-26 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift.ext; - -import com.alibaba.dubbo.common.logger.Logger; -import com.alibaba.dubbo.common.logger.LoggerFactory; -import com.alibaba.dubbo.rpc.protocol.thrift.ThriftCodec; -import org.apache.thrift.TException; -import org.apache.thrift.TProcessor; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.protocol.TProtocolFactory; -import org.apache.thrift.transport.TIOStreamTransport; - -import java.io.ByteArrayOutputStream; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * @author kimi - */ -public class MultiServiceProcessor implements TProcessor { - - private static final Logger logger = LoggerFactory.getLogger( MultiServiceProcessor.class ); - - private ConcurrentMap processorMap = new ConcurrentHashMap(); - - private TProtocolFactory protocolFactory = new TBinaryProtocol.Factory(); - - public MultiServiceProcessor() {} - - public boolean process( TProtocol in, TProtocol out ) throws TException { - - short magic = in.readI16(); - - if ( magic != ThriftCodec.MAGIC ) { - logger.error( - new StringBuilder( 24 ) - .append( "Unsupported magic " ) - .append( magic ).toString() ); - return false; - } - - in.readI32(); - in.readI16(); - byte version = in.readByte(); - String serviceName = in.readString(); - long id = in.readI64(); - - ByteArrayOutputStream bos = new ByteArrayOutputStream( 1024 ); - - TIOStreamTransport transport = new TIOStreamTransport( bos ); - - TProtocol protocol = protocolFactory.getProtocol( transport ); - - TProcessor processor = processorMap.get( serviceName ); - - if ( processor == null ) { - logger.error( - new StringBuilder( 32 ) - .append( "Could not find processor for service " ) - .append( serviceName ) - .toString() ); - return false; - } - - // todo if exception - boolean result = processor.process( in, protocol ); - - ByteArrayOutputStream header = new ByteArrayOutputStream( 512 ); - - TIOStreamTransport headerTransport = new TIOStreamTransport( header ); - - TProtocol headerProtocol = protocolFactory.getProtocol( headerTransport ); - - headerProtocol.writeI16( magic ); - headerProtocol.writeI32( Integer.MAX_VALUE ); - headerProtocol.writeI16( Short.MAX_VALUE ); - headerProtocol.writeByte( version ); - headerProtocol.writeString( serviceName ); - headerProtocol.writeI64( id ); - headerProtocol.getTransport().flush(); - - out.writeI16( magic ); - out.writeI32( bos.size() + header.size() ); - out.writeI16( ( short ) ( 0xffff & header.size() ) ); - out.writeByte( version ); - out.writeString( serviceName ); - out.writeI64( id ); - - out.getTransport().write( bos.toByteArray() ); - out.getTransport().flush(); - - return result; - - } - - public TProcessor addProcessor( Class service, TProcessor processor ) { - if ( service != null && processor != null ) { - return processorMap.putIfAbsent( service.getName(), processor ); - } - return processor; - } - - public void setProtocolFactory( TProtocolFactory factory ) { - if ( factory != null ) { - this.protocolFactory = factory; - } - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/InputStreamWrapper.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/InputStreamWrapper.java deleted file mode 100644 index 9cdfdc372c4..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/InputStreamWrapper.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift.io; - -import java.io.IOException; -import java.io.InputStream; - -/** - * @author kimi - */ -public class InputStreamWrapper extends InputStream { - - private InputStream is; - - public InputStreamWrapper(InputStream is) { - if (is == null) { - throw new NullPointerException("is == null"); - } - this.is = is; - } - - @Override - public int read(byte[] b) throws IOException { - if (is.available() >= b.length) { - return is.read(b); - } else { - return -1; - } - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (is.available() >= len) { - return is.read(b, off, len); - } else { - return -1; - } - } - - @Override - public long skip(long n) throws IOException { - return is.skip(n); - } - - @Override - public int available() throws IOException { - return is.available(); - } - - @Override - public void close() throws IOException { - is.close(); - } - - @Override - public void mark(int readlimit) { - is.mark(readlimit); - } - - @Override - public void reset() throws IOException { - is.reset(); - } - - @Override - public boolean markSupported() { - return is.markSupported(); - } - - @Override - public int read() throws IOException { - if (is.available() >= 1) { - return is.read(); - } - return -1; - } -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java deleted file mode 100644 index 4902b4d59cb..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * File Created at 2011-12-22 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift.io; - -import com.alibaba.dubbo.common.io.Bytes; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; - -/** - * @author kimi - */ -public class RandomAccessByteArrayOutputStream extends OutputStream { - - protected byte buffer[]; - - protected int count; - - public RandomAccessByteArrayOutputStream() { - - this( 32 ); - } - - public RandomAccessByteArrayOutputStream( int size ) { - - if ( size < 0 ) - throw new IllegalArgumentException( "Negative initial size: " + size ); - buffer = new byte[size]; - } - - public void write( int b ) { - - int newcount = count + 1; - if ( newcount > buffer.length ) - buffer = Bytes.copyOf( buffer, Math.max( buffer.length << 1, newcount ) ); - buffer[count] = ( byte ) b; - count = newcount; - } - - public void write( byte b[], int off, int len ) { - - if ( ( off < 0 ) || ( off > b.length ) || ( len < 0 ) || ( ( off + len ) > b.length ) || ( ( off + len ) < 0 ) ) - throw new IndexOutOfBoundsException(); - if ( len == 0 ) - return; - int newcount = count + len; - if ( newcount > buffer.length ) - buffer = Bytes.copyOf( buffer, Math.max( buffer.length << 1, newcount ) ); - System.arraycopy( b, off, buffer, count, len ); - count = newcount; - } - - public int size() { - - return count; - } - - public void setWriteIndex( int index ) { - count = index; - } - - public void reset() { - - count = 0; - } - - public byte[] toByteArray() { - - return Bytes.copyOf( buffer, count ); - } - - public ByteBuffer toByteBuffer() { - - return ByteBuffer.wrap( buffer, 0, count ); - } - - public void writeTo( OutputStream out ) throws IOException { - - out.write( buffer, 0, count ); - } - - public String toString() { - - return new String( buffer, 0, count ); - } - - public String toString( String charset ) throws UnsupportedEncodingException { - - return new String( buffer, 0, count, charset ); - } - - public void close() throws IOException {} - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 b/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 deleted file mode 100644 index 518ce0ae7a8..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.remoting.Codec2 +++ /dev/null @@ -1 +0,0 @@ -thrift=com.alibaba.dubbo.rpc.protocol.thrift.ThriftCodec \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol deleted file mode 100644 index 85233b7736a..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -thrift=com.alibaba.dubbo.rpc.protocol.thrift.ThriftProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.protocol.thrift.ClassNameGenerator b/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.protocol.thrift.ClassNameGenerator deleted file mode 100644 index b2e5598772b..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.protocol.thrift.ClassNameGenerator +++ /dev/null @@ -1,2 +0,0 @@ -dubbo=com.alibaba.dubbo.rpc.protocol.thrift.DubboClassNameGenerator -thrift=com.alibaba.dubbo.rpc.protocol.thrift.ThriftClassNameGenerator \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java deleted file mode 100644 index b73ee40fc45..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java +++ /dev/null @@ -1,658 +0,0 @@ -/** - * Autogenerated by Dubbo Compiler (0.1.0) - * - * Thrift (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class $__ClassNameTestDubboStub { - - public interface Iface { - - public String echo(String arg); - - } - - public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); - public Processor(I iface) { - super(iface, getProcessMap(new HashMap>())); - } - - protected Processor(I iface, Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static Map> getProcessMap(Map> processMap) { - processMap.put("echo", new echo()); - return processMap; - } - - private static class echo extends org.apache.thrift.ProcessFunction { - public echo() { - super("echo"); - } - - protected echo_args getEmptyArgsInstance() { - return new echo_args(); - } - - protected echo_result getResult(I iface, echo_args args) throws org.apache.thrift.TException { - echo_result result = new echo_result(); - result.success = iface.echo(args.arg); - return result; - } - } - - } - - public static class echo_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.STRING, (short)1); - - public String arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echo_args.class, metaDataMap); - } - - public echo_args() { - } - - public echo_args( - String arg) - { - this(); - this.arg = arg; - } - - /** - * Performs a deep copy on other. - */ - public echo_args(echo_args other) { - if (other.isSetArg()) { - this.arg = other.arg; - } - } - - public echo_args deepCopy() { - return new echo_args(this); - } - - public void clear() { - this.arg = null; - } - - public String getArg() { - return this.arg; - } - - public echo_args setArg(String arg) { - this.arg = arg; - return this; - } - - public void unsetArg() { - this.arg = null; - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return this.arg != null; - } - - public void setArgIsSet(boolean value) { - if (!value) { - this.arg = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return getArg(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echo_args) - return this.equals((echo_args)that); - return false; - } - - public boolean equals(echo_args that) { - if (that == null) - return false; - - boolean this_present_arg = true && this.isSetArg(); - boolean that_present_arg = true && that.isSetArg(); - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (!this.arg.equals(that.arg)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - return 0; - } - - public int compareTo(echo_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echo_args typedOther = (echo_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.arg = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (this.arg != null) { - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeString(this.arg); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("echo_args("); - boolean first = true; - - sb.append("arg:"); - if (this.arg == null) { - sb.append("null"); - } else { - sb.append(this.arg); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (arg == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not present! Struct: " + toString()); - } - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echo_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); - - public String success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echo_result.class, metaDataMap); - } - - public echo_result() { - } - - public echo_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public echo_result(echo_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public echo_result deepCopy() { - return new echo_result(this); - } - - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public echo_result setSuccess(String success) { - this.success = success; - return this; - } - - public void unsetSuccess() { - this.success = null; - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return this.success != null; - } - - public void setSuccessIsSet(boolean value) { - if (!value) { - this.success = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return getSuccess(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echo_result) - return this.equals((echo_result)that); - return false; - } - - public boolean equals(echo_result that) { - if (that == null) - return false; - - boolean this_present_success = true && this.isSetSuccess(); - boolean that_present_success = true && that.isSetSuccess(); - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (!this.success.equals(that.success)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - return 0; - } - - public int compareTo(echo_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echo_result typedOther = (echo_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.success = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("echo_result("); - boolean first = true; - - sb.append("success:"); - if (this.success == null) { - sb.append("null"); - } else { - sb.append(this.success); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java deleted file mode 100644 index 45de6d30682..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * File Created at 2012-01-09 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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. - */ - -import com.alibaba.dubbo.rpc.protocol.thrift.ThriftUtils; -import org.junit.Assert; -import org.junit.Test; - -/** - * @author kimi - */ -public class ClassNameTest { - - @Test - public void testThriftUtils() { - - Assert.assertEquals( $__ClassNameTestDubboStub.echo_args.class.getName(), - ThriftUtils.generateMethodArgsClassName( - ClassNameTestDubbo.class.getName(), "echo" ) ); - - Assert.assertEquals( $__ClassNameTestDubboStub.echo_result.class.getName(), - ThriftUtils.generateMethodResultClassName( - ClassNameTestDubbo.class.getName(), "echo" ) ); - - Assert.assertEquals( ClassNameTestThrift.echo_args.class.getName(), - ThriftUtils.generateMethodArgsClassNameThrift( - ClassNameTestThrift.Iface.class.getName(), "echo" ) ); - - Assert.assertEquals( ClassNameTestThrift.echo_result.class.getName(), - ThriftUtils.generateMethodResultClassNameThrift( - ClassNameTestThrift.Iface.class.getName(), "echo" )); - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestDubbo.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestDubbo.java deleted file mode 100644 index 71741e10571..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestDubbo.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Autogenerated by Dubbo Compiler (0.1.0) - * - * Thrift (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public interface ClassNameTestDubbo { - - public String echo(String arg); - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java deleted file mode 100644 index 8d48664d46d..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java +++ /dev/null @@ -1,757 +0,0 @@ -/** - * Autogenerated by Thrift Compiler (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ClassNameTestThrift { - - public interface Iface { - - public String echo(String arg) throws org.apache.thrift.TException; - - } - - public interface AsyncIface { - - public void echo(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - } - - public static class Client extends org.apache.thrift.TServiceClient implements Iface { - public static class Factory implements org.apache.thrift.TServiceClientFactory { - public Factory() {} - public Client getClient(org.apache.thrift.protocol.TProtocol prot) { - return new Client(prot); - } - public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { - return new Client(iprot, oprot); - } - } - - public Client(org.apache.thrift.protocol.TProtocol prot) - { - super(prot, prot); - } - - public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { - super(iprot, oprot); - } - - public String echo(String arg) throws org.apache.thrift.TException - { - send_echo(arg); - return recv_echo(); - } - - public void send_echo(String arg) throws org.apache.thrift.TException - { - echo_args args = new echo_args(); - args.setArg(arg); - sendBase("echo", args); - } - - public String recv_echo() throws org.apache.thrift.TException - { - echo_result result = new echo_result(); - receiveBase(result, "echo"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echo failed: unknown result"); - } - - } - public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { - public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { - private org.apache.thrift.async.TAsyncClientManager clientManager; - private org.apache.thrift.protocol.TProtocolFactory protocolFactory; - public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { - this.clientManager = clientManager; - this.protocolFactory = protocolFactory; - } - public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { - return new AsyncClient(protocolFactory, clientManager, transport); - } - } - - public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { - super(protocolFactory, clientManager, transport); - } - - public void echo(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echo_call method_call = new echo_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echo_call extends org.apache.thrift.async.TAsyncMethodCall { - private String arg; - public echo_call(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echo", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echo_args args = new echo_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public String getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echo(); - } - } - - } - - public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); - public Processor(I iface) { - super(iface, getProcessMap(new HashMap>())); - } - - protected Processor(I iface, Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static Map> getProcessMap(Map> processMap) { - processMap.put("echo", new echo()); - return processMap; - } - - private static class echo extends org.apache.thrift.ProcessFunction { - public echo() { - super("echo"); - } - - protected echo_args getEmptyArgsInstance() { - return new echo_args(); - } - - protected echo_result getResult(I iface, echo_args args) throws org.apache.thrift.TException { - echo_result result = new echo_result(); - result.success = iface.echo(args.arg); - return result; - } - } - - } - - public static class echo_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.STRING, (short)1); - - public String arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echo_args.class, metaDataMap); - } - - public echo_args() { - } - - public echo_args( - String arg) - { - this(); - this.arg = arg; - } - - /** - * Performs a deep copy on other. - */ - public echo_args(echo_args other) { - if (other.isSetArg()) { - this.arg = other.arg; - } - } - - public echo_args deepCopy() { - return new echo_args(this); - } - - public void clear() { - this.arg = null; - } - - public String getArg() { - return this.arg; - } - - public echo_args setArg(String arg) { - this.arg = arg; - return this; - } - - public void unsetArg() { - this.arg = null; - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return this.arg != null; - } - - public void setArgIsSet(boolean value) { - if (!value) { - this.arg = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return getArg(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echo_args) - return this.equals((echo_args)that); - return false; - } - - public boolean equals(echo_args that) { - if (that == null) - return false; - - boolean this_present_arg = true && this.isSetArg(); - boolean that_present_arg = true && that.isSetArg(); - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (!this.arg.equals(that.arg)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - return 0; - } - - public int compareTo(echo_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echo_args typedOther = (echo_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.arg = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (this.arg != null) { - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeString(this.arg); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("echo_args("); - boolean first = true; - - sb.append("arg:"); - if (this.arg == null) { - sb.append("null"); - } else { - sb.append(this.arg); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (arg == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not present! Struct: " + toString()); - } - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echo_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echo_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); - - public String success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echo_result.class, metaDataMap); - } - - public echo_result() { - } - - public echo_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public echo_result(echo_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public echo_result deepCopy() { - return new echo_result(this); - } - - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public echo_result setSuccess(String success) { - this.success = success; - return this; - } - - public void unsetSuccess() { - this.success = null; - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return this.success != null; - } - - public void setSuccessIsSet(boolean value) { - if (!value) { - this.success = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return getSuccess(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echo_result) - return this.equals((echo_result)that); - return false; - } - - public boolean equals(echo_result that) { - if (that == null) - return false; - - boolean this_present_success = true && this.isSetSuccess(); - boolean that_present_success = true && that.isSetSuccess(); - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (!this.success.equals(that.success)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - return 0; - } - - public int compareTo(echo_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echo_result typedOther = (echo_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.success = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("echo_result("); - boolean first = true; - - sb.append("success:"); - if (this.success == null) { - sb.append("null"); - } else { - sb.append(this.success); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/$__DemoStub.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/$__DemoStub.java deleted file mode 100644 index f29d6b74934..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/$__DemoStub.java +++ /dev/null @@ -1,4376 +0,0 @@ -/** - * Autogenerated by Dubbo Compiler (0.1.0) - * - * Thrift (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -package com.alibaba.dubbo.rpc.gen.dubbo; - -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class $__DemoStub { - - public interface Iface { - - public boolean echoBool(boolean arg); - - public byte echoByte(byte arg); - - public short echoI16(short arg); - - public int echoI32(int arg); - - public long echoI64(long arg); - - public double echoDouble(double arg); - - public String echoString(String arg); - - } - - public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); - public Processor(I iface) { - super(iface, getProcessMap(new HashMap>())); - } - - protected Processor(I iface, Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static Map> getProcessMap(Map> processMap) { - processMap.put("echoBool", new echoBool()); - processMap.put("echoByte", new echoByte()); - processMap.put("echoI16", new echoI16()); - processMap.put("echoI32", new echoI32()); - processMap.put("echoI64", new echoI64()); - processMap.put("echoDouble", new echoDouble()); - processMap.put("echoString", new echoString()); - return processMap; - } - - private static class echoBool extends org.apache.thrift.ProcessFunction { - public echoBool() { - super("echoBool"); - } - - protected echoBool_args getEmptyArgsInstance() { - return new echoBool_args(); - } - - protected echoBool_result getResult(I iface, echoBool_args args) throws org.apache.thrift.TException { - echoBool_result result = new echoBool_result(); - result.success = iface.echoBool(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoByte extends org.apache.thrift.ProcessFunction { - public echoByte() { - super("echoByte"); - } - - protected echoByte_args getEmptyArgsInstance() { - return new echoByte_args(); - } - - protected echoByte_result getResult(I iface, echoByte_args args) throws org.apache.thrift.TException { - echoByte_result result = new echoByte_result(); - result.success = iface.echoByte(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI16 extends org.apache.thrift.ProcessFunction { - public echoI16() { - super("echoI16"); - } - - protected echoI16_args getEmptyArgsInstance() { - return new echoI16_args(); - } - - protected echoI16_result getResult(I iface, echoI16_args args) throws org.apache.thrift.TException { - echoI16_result result = new echoI16_result(); - result.success = iface.echoI16(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI32 extends org.apache.thrift.ProcessFunction { - public echoI32() { - super("echoI32"); - } - - protected echoI32_args getEmptyArgsInstance() { - return new echoI32_args(); - } - - protected echoI32_result getResult(I iface, echoI32_args args) throws org.apache.thrift.TException { - echoI32_result result = new echoI32_result(); - result.success = iface.echoI32(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI64 extends org.apache.thrift.ProcessFunction { - public echoI64() { - super("echoI64"); - } - - protected echoI64_args getEmptyArgsInstance() { - return new echoI64_args(); - } - - protected echoI64_result getResult(I iface, echoI64_args args) throws org.apache.thrift.TException { - echoI64_result result = new echoI64_result(); - result.success = iface.echoI64(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoDouble extends org.apache.thrift.ProcessFunction { - public echoDouble() { - super("echoDouble"); - } - - protected echoDouble_args getEmptyArgsInstance() { - return new echoDouble_args(); - } - - protected echoDouble_result getResult(I iface, echoDouble_args args) throws org.apache.thrift.TException { - echoDouble_result result = new echoDouble_result(); - result.success = iface.echoDouble(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoString extends org.apache.thrift.ProcessFunction { - public echoString() { - super("echoString"); - } - - protected echoString_args getEmptyArgsInstance() { - return new echoString_args(); - } - - protected echoString_result getResult(I iface, echoString_args args) throws org.apache.thrift.TException { - echoString_result result = new echoString_result(); - result.success = iface.echoString(args.arg); - return result; - } - } - - } - - public static class echoBool_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoBool_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.BOOL, (short)1); - - public boolean arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoBool_args.class, metaDataMap); - } - - public echoBool_args() { - } - - public echoBool_args( - boolean arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoBool_args(echoBool_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoBool_args deepCopy() { - return new echoBool_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = false; - } - - public boolean isArg() { - return this.arg; - } - - public echoBool_args setArg(boolean arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Boolean)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Boolean.valueOf(isArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoBool_args) - return this.equals((echoBool_args)that); - return false; - } - - public boolean equals(echoBool_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoBool_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoBool_args typedOther = (echoBool_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.BOOL) { - this.arg = iprot.readBool(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeBool(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoBool_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoBool_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoBool_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0); - - public boolean success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoBool_result.class, metaDataMap); - } - - public echoBool_result() { - } - - public echoBool_result( - boolean success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoBool_result(echoBool_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoBool_result deepCopy() { - return new echoBool_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = false; - } - - public boolean isSuccess() { - return this.success; - } - - public echoBool_result setSuccess(boolean success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Boolean)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Boolean.valueOf(isSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoBool_result) - return this.equals((echoBool_result)that); - return false; - } - - public boolean equals(echoBool_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoBool_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoBool_result typedOther = (echoBool_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.BOOL) { - this.success = iprot.readBool(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeBool(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoBool_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoByte_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoByte_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.BYTE, (short)1); - - public byte arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BYTE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoByte_args.class, metaDataMap); - } - - public echoByte_args() { - } - - public echoByte_args( - byte arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoByte_args(echoByte_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoByte_args deepCopy() { - return new echoByte_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public byte getArg() { - return this.arg; - } - - public echoByte_args setArg(byte arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Byte)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Byte.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoByte_args) - return this.equals((echoByte_args)that); - return false; - } - - public boolean equals(echoByte_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoByte_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoByte_args typedOther = (echoByte_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.BYTE) { - this.arg = iprot.readByte(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeByte(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoByte_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoByte_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoByte_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BYTE, (short)0); - - public byte success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BYTE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoByte_result.class, metaDataMap); - } - - public echoByte_result() { - } - - public echoByte_result( - byte success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoByte_result(echoByte_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoByte_result deepCopy() { - return new echoByte_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public byte getSuccess() { - return this.success; - } - - public echoByte_result setSuccess(byte success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Byte)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Byte.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoByte_result) - return this.equals((echoByte_result)that); - return false; - } - - public boolean equals(echoByte_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoByte_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoByte_result typedOther = (echoByte_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.BYTE) { - this.success = iprot.readByte(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeByte(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoByte_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI16_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI16_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I16, (short)1); - - public short arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI16_args.class, metaDataMap); - } - - public echoI16_args() { - } - - public echoI16_args( - short arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI16_args(echoI16_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI16_args deepCopy() { - return new echoI16_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public short getArg() { - return this.arg; - } - - public echoI16_args setArg(short arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Short)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Short.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI16_args) - return this.equals((echoI16_args)that); - return false; - } - - public boolean equals(echoI16_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI16_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI16_args typedOther = (echoI16_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I16) { - this.arg = iprot.readI16(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI16(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI16_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI16_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI16_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I16, (short)0); - - public short success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI16_result.class, metaDataMap); - } - - public echoI16_result() { - } - - public echoI16_result( - short success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI16_result(echoI16_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI16_result deepCopy() { - return new echoI16_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public short getSuccess() { - return this.success; - } - - public echoI16_result setSuccess(short success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Short)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Short.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI16_result) - return this.equals((echoI16_result)that); - return false; - } - - public boolean equals(echoI16_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI16_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI16_result typedOther = (echoI16_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I16) { - this.success = iprot.readI16(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI16(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI16_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI32_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI32_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I32, (short)1); - - public int arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI32_args.class, metaDataMap); - } - - public echoI32_args() { - } - - public echoI32_args( - int arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI32_args(echoI32_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI32_args deepCopy() { - return new echoI32_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public int getArg() { - return this.arg; - } - - public echoI32_args setArg(int arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Integer)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Integer.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI32_args) - return this.equals((echoI32_args)that); - return false; - } - - public boolean equals(echoI32_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI32_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI32_args typedOther = (echoI32_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I32) { - this.arg = iprot.readI32(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI32(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI32_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI32_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI32_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I32, (short)0); - - public int success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI32_result.class, metaDataMap); - } - - public echoI32_result() { - } - - public echoI32_result( - int success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI32_result(echoI32_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI32_result deepCopy() { - return new echoI32_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public int getSuccess() { - return this.success; - } - - public echoI32_result setSuccess(int success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Integer)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Integer.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI32_result) - return this.equals((echoI32_result)that); - return false; - } - - public boolean equals(echoI32_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI32_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI32_result typedOther = (echoI32_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I32) { - this.success = iprot.readI32(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI32(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI32_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI64_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI64_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I64, (short)1); - - public long arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI64_args.class, metaDataMap); - } - - public echoI64_args() { - } - - public echoI64_args( - long arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI64_args(echoI64_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI64_args deepCopy() { - return new echoI64_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public long getArg() { - return this.arg; - } - - public echoI64_args setArg(long arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Long)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Long.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI64_args) - return this.equals((echoI64_args)that); - return false; - } - - public boolean equals(echoI64_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI64_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI64_args typedOther = (echoI64_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I64) { - this.arg = iprot.readI64(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI64(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI64_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI64_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI64_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I64, (short)0); - - public long success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI64_result.class, metaDataMap); - } - - public echoI64_result() { - } - - public echoI64_result( - long success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI64_result(echoI64_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI64_result deepCopy() { - return new echoI64_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public long getSuccess() { - return this.success; - } - - public echoI64_result setSuccess(long success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Long)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Long.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI64_result) - return this.equals((echoI64_result)that); - return false; - } - - public boolean equals(echoI64_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI64_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI64_result typedOther = (echoI64_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I64) { - this.success = iprot.readI64(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI64(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI64_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoDouble_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoDouble_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.DOUBLE, (short)1); - - public double arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoDouble_args.class, metaDataMap); - } - - public echoDouble_args() { - } - - public echoDouble_args( - double arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoDouble_args(echoDouble_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoDouble_args deepCopy() { - return new echoDouble_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0.0; - } - - public double getArg() { - return this.arg; - } - - public echoDouble_args setArg(double arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Double)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Double.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoDouble_args) - return this.equals((echoDouble_args)that); - return false; - } - - public boolean equals(echoDouble_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoDouble_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoDouble_args typedOther = (echoDouble_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.DOUBLE) { - this.arg = iprot.readDouble(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeDouble(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoDouble_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoDouble_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoDouble_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.DOUBLE, (short)0); - - public double success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoDouble_result.class, metaDataMap); - } - - public echoDouble_result() { - } - - public echoDouble_result( - double success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoDouble_result(echoDouble_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoDouble_result deepCopy() { - return new echoDouble_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0.0; - } - - public double getSuccess() { - return this.success; - } - - public echoDouble_result setSuccess(double success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Double)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Double.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoDouble_result) - return this.equals((echoDouble_result)that); - return false; - } - - public boolean equals(echoDouble_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoDouble_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoDouble_result typedOther = (echoDouble_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.DOUBLE) { - this.success = iprot.readDouble(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeDouble(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoDouble_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoString_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoString_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.STRING, (short)1); - - public String arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoString_args.class, metaDataMap); - } - - public echoString_args() { - } - - public echoString_args( - String arg) - { - this(); - this.arg = arg; - } - - /** - * Performs a deep copy on other. - */ - public echoString_args(echoString_args other) { - if (other.isSetArg()) { - this.arg = other.arg; - } - } - - public echoString_args deepCopy() { - return new echoString_args(this); - } - - - public void clear() { - this.arg = null; - } - - public String getArg() { - return this.arg; - } - - public echoString_args setArg(String arg) { - this.arg = arg; - return this; - } - - public void unsetArg() { - this.arg = null; - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return this.arg != null; - } - - public void setArgIsSet(boolean value) { - if (!value) { - this.arg = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return getArg(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoString_args) - return this.equals((echoString_args)that); - return false; - } - - public boolean equals(echoString_args that) { - if (that == null) - return false; - - boolean this_present_arg = true && this.isSetArg(); - boolean that_present_arg = true && that.isSetArg(); - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (!this.arg.equals(that.arg)) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoString_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoString_args typedOther = (echoString_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.arg = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (this.arg != null) { - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeString(this.arg); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoString_args("); - boolean first = true; - - sb.append("arg:"); - if (this.arg == null) { - sb.append("null"); - } else { - sb.append(this.arg); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (arg == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not present! Struct: " + toString()); - } - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoString_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoString_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); - - public String success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoString_result.class, metaDataMap); - } - - public echoString_result() { - } - - public echoString_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public echoString_result(echoString_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public echoString_result deepCopy() { - return new echoString_result(this); - } - - - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public echoString_result setSuccess(String success) { - this.success = success; - return this; - } - - public void unsetSuccess() { - this.success = null; - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return this.success != null; - } - - public void setSuccessIsSet(boolean value) { - if (!value) { - this.success = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return getSuccess(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoString_result) - return this.equals((echoString_result)that); - return false; - } - - public boolean equals(echoString_result that) { - if (that == null) - return false; - - boolean this_present_success = true && this.isSetSuccess(); - boolean that_present_success = true && that.isSetSuccess(); - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (!this.success.equals(that.success)) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoString_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoString_result typedOther = (echoString_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.success = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoString_result("); - boolean first = true; - - sb.append("success:"); - if (this.success == null) { - sb.append("null"); - } else { - sb.append(this.success); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/Demo.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/Demo.java deleted file mode 100644 index 8993ad2cfe2..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/dubbo/Demo.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Autogenerated by Dubbo Compiler (0.1.0) - * - * Thrift (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -package com.alibaba.dubbo.rpc.gen.dubbo; - -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public interface Demo { - - public boolean echoBool(boolean arg); - - public byte echoByte(byte arg); - - public short echoI16(short arg); - - public int echoI32(int arg); - - public long echoI64(long arg); - - public double echoDouble(double arg); - - public String echoString(String arg); - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/thrift/Demo.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/thrift/Demo.java deleted file mode 100644 index 2be2cfa99f5..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/gen/thrift/Demo.java +++ /dev/null @@ -1,4805 +0,0 @@ -/** - * Autogenerated by Thrift Compiler (0.7.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -package com.alibaba.dubbo.rpc.gen.thrift; - -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.HashMap; -import java.util.EnumMap; -import java.util.Set; -import java.util.HashSet; -import java.util.EnumSet; -import java.util.Collections; -import java.util.BitSet; -import java.nio.ByteBuffer; -import java.util.Arrays; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class Demo { - - public interface Iface { - - public boolean echoBool(boolean arg) throws org.apache.thrift.TException; - - public byte echoByte(byte arg) throws org.apache.thrift.TException; - - public short echoI16(short arg) throws org.apache.thrift.TException; - - public int echoI32(int arg) throws org.apache.thrift.TException; - - public long echoI64(long arg) throws org.apache.thrift.TException; - - public double echoDouble(double arg) throws org.apache.thrift.TException; - - public String echoString(String arg) throws org.apache.thrift.TException; - - } - - public interface AsyncIface { - - public void echoBool(boolean arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoByte(byte arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoI16(short arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoI32(int arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoI64(long arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoDouble(double arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - public void echoString(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - } - - public static class Client extends org.apache.thrift.TServiceClient implements Iface { - public static class Factory implements org.apache.thrift.TServiceClientFactory { - public Factory() {} - public Client getClient(org.apache.thrift.protocol.TProtocol prot) { - return new Client(prot); - } - public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { - return new Client(iprot, oprot); - } - } - - public Client(org.apache.thrift.protocol.TProtocol prot) - { - super(prot, prot); - } - - public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) { - super(iprot, oprot); - } - - public boolean echoBool(boolean arg) throws org.apache.thrift.TException - { - send_echoBool(arg); - return recv_echoBool(); - } - - public void send_echoBool(boolean arg) throws org.apache.thrift.TException - { - echoBool_args args = new echoBool_args(); - args.setArg(arg); - sendBase("echoBool", args); - } - - public boolean recv_echoBool() throws org.apache.thrift.TException - { - echoBool_result result = new echoBool_result(); - receiveBase(result, "echoBool"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoBool failed: unknown result"); - } - - public byte echoByte(byte arg) throws org.apache.thrift.TException - { - send_echoByte(arg); - return recv_echoByte(); - } - - public void send_echoByte(byte arg) throws org.apache.thrift.TException - { - echoByte_args args = new echoByte_args(); - args.setArg(arg); - sendBase("echoByte", args); - } - - public byte recv_echoByte() throws org.apache.thrift.TException - { - echoByte_result result = new echoByte_result(); - receiveBase(result, "echoByte"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoByte failed: unknown result"); - } - - public short echoI16(short arg) throws org.apache.thrift.TException - { - send_echoI16(arg); - return recv_echoI16(); - } - - public void send_echoI16(short arg) throws org.apache.thrift.TException - { - echoI16_args args = new echoI16_args(); - args.setArg(arg); - sendBase("echoI16", args); - } - - public short recv_echoI16() throws org.apache.thrift.TException - { - echoI16_result result = new echoI16_result(); - receiveBase(result, "echoI16"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoI16 failed: unknown result"); - } - - public int echoI32(int arg) throws org.apache.thrift.TException - { - send_echoI32(arg); - return recv_echoI32(); - } - - public void send_echoI32(int arg) throws org.apache.thrift.TException - { - echoI32_args args = new echoI32_args(); - args.setArg(arg); - sendBase("echoI32", args); - } - - public int recv_echoI32() throws org.apache.thrift.TException - { - echoI32_result result = new echoI32_result(); - receiveBase(result, "echoI32"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoI32 failed: unknown result"); - } - - public long echoI64(long arg) throws org.apache.thrift.TException - { - send_echoI64(arg); - return recv_echoI64(); - } - - public void send_echoI64(long arg) throws org.apache.thrift.TException - { - echoI64_args args = new echoI64_args(); - args.setArg(arg); - sendBase("echoI64", args); - } - - public long recv_echoI64() throws org.apache.thrift.TException - { - echoI64_result result = new echoI64_result(); - receiveBase(result, "echoI64"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoI64 failed: unknown result"); - } - - public double echoDouble(double arg) throws org.apache.thrift.TException - { - send_echoDouble(arg); - return recv_echoDouble(); - } - - public void send_echoDouble(double arg) throws org.apache.thrift.TException - { - echoDouble_args args = new echoDouble_args(); - args.setArg(arg); - sendBase("echoDouble", args); - } - - public double recv_echoDouble() throws org.apache.thrift.TException - { - echoDouble_result result = new echoDouble_result(); - receiveBase(result, "echoDouble"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoDouble failed: unknown result"); - } - - public String echoString(String arg) throws org.apache.thrift.TException - { - send_echoString(arg); - return recv_echoString(); - } - - public void send_echoString(String arg) throws org.apache.thrift.TException - { - echoString_args args = new echoString_args(); - args.setArg(arg); - sendBase("echoString", args); - } - - public String recv_echoString() throws org.apache.thrift.TException - { - echoString_result result = new echoString_result(); - receiveBase(result, "echoString"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "echoString failed: unknown result"); - } - - } - public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { - public static class Factory implements org.apache.thrift.async.TAsyncClientFactory { - private org.apache.thrift.async.TAsyncClientManager clientManager; - private org.apache.thrift.protocol.TProtocolFactory protocolFactory; - public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) { - this.clientManager = clientManager; - this.protocolFactory = protocolFactory; - } - public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) { - return new AsyncClient(protocolFactory, clientManager, transport); - } - } - - public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) { - super(protocolFactory, clientManager, transport); - } - - public void echoBool(boolean arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoBool_call method_call = new echoBool_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoBool_call extends org.apache.thrift.async.TAsyncMethodCall { - private boolean arg; - public echoBool_call(boolean arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoBool", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoBool_args args = new echoBool_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public boolean getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoBool(); - } - } - - public void echoByte(byte arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoByte_call method_call = new echoByte_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoByte_call extends org.apache.thrift.async.TAsyncMethodCall { - private byte arg; - public echoByte_call(byte arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoByte", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoByte_args args = new echoByte_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public byte getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoByte(); - } - } - - public void echoI16(short arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoI16_call method_call = new echoI16_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoI16_call extends org.apache.thrift.async.TAsyncMethodCall { - private short arg; - public echoI16_call(short arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoI16", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoI16_args args = new echoI16_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public short getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoI16(); - } - } - - public void echoI32(int arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoI32_call method_call = new echoI32_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoI32_call extends org.apache.thrift.async.TAsyncMethodCall { - private int arg; - public echoI32_call(int arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoI32", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoI32_args args = new echoI32_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public int getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoI32(); - } - } - - public void echoI64(long arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoI64_call method_call = new echoI64_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoI64_call extends org.apache.thrift.async.TAsyncMethodCall { - private long arg; - public echoI64_call(long arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoI64", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoI64_args args = new echoI64_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public long getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoI64(); - } - } - - public void echoDouble(double arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoDouble_call method_call = new echoDouble_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoDouble_call extends org.apache.thrift.async.TAsyncMethodCall { - private double arg; - public echoDouble_call(double arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoDouble", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoDouble_args args = new echoDouble_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public double getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoDouble(); - } - } - - public void echoString(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - echoString_call method_call = new echoString_call(arg, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class echoString_call extends org.apache.thrift.async.TAsyncMethodCall { - private String arg; - public echoString_call(String arg, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException { - super(client, protocolFactory, transport, resultHandler, false); - this.arg = arg; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("echoString", org.apache.thrift.protocol.TMessageType.CALL, 0)); - echoString_args args = new echoString_args(); - args.setArg(arg); - args.write(prot); - prot.writeMessageEnd(); - } - - public String getResult() throws org.apache.thrift.TException { - if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) { - throw new IllegalStateException("Method call not finished!"); - } - org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array()); - org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport); - return (new Client(prot)).recv_echoString(); - } - } - - } - - public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); - public Processor(I iface) { - super(iface, getProcessMap(new HashMap>())); - } - - protected Processor(I iface, Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static Map> getProcessMap(Map> processMap) { - processMap.put("echoBool", new echoBool()); - processMap.put("echoByte", new echoByte()); - processMap.put("echoI16", new echoI16()); - processMap.put("echoI32", new echoI32()); - processMap.put("echoI64", new echoI64()); - processMap.put("echoDouble", new echoDouble()); - processMap.put("echoString", new echoString()); - return processMap; - } - - private static class echoBool extends org.apache.thrift.ProcessFunction { - public echoBool() { - super("echoBool"); - } - - protected echoBool_args getEmptyArgsInstance() { - return new echoBool_args(); - } - - protected echoBool_result getResult(I iface, echoBool_args args) throws org.apache.thrift.TException { - echoBool_result result = new echoBool_result(); - result.success = iface.echoBool(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoByte extends org.apache.thrift.ProcessFunction { - public echoByte() { - super("echoByte"); - } - - protected echoByte_args getEmptyArgsInstance() { - return new echoByte_args(); - } - - protected echoByte_result getResult(I iface, echoByte_args args) throws org.apache.thrift.TException { - echoByte_result result = new echoByte_result(); - result.success = iface.echoByte(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI16 extends org.apache.thrift.ProcessFunction { - public echoI16() { - super("echoI16"); - } - - protected echoI16_args getEmptyArgsInstance() { - return new echoI16_args(); - } - - protected echoI16_result getResult(I iface, echoI16_args args) throws org.apache.thrift.TException { - echoI16_result result = new echoI16_result(); - result.success = iface.echoI16(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI32 extends org.apache.thrift.ProcessFunction { - public echoI32() { - super("echoI32"); - } - - protected echoI32_args getEmptyArgsInstance() { - return new echoI32_args(); - } - - protected echoI32_result getResult(I iface, echoI32_args args) throws org.apache.thrift.TException { - echoI32_result result = new echoI32_result(); - result.success = iface.echoI32(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoI64 extends org.apache.thrift.ProcessFunction { - public echoI64() { - super("echoI64"); - } - - protected echoI64_args getEmptyArgsInstance() { - return new echoI64_args(); - } - - protected echoI64_result getResult(I iface, echoI64_args args) throws org.apache.thrift.TException { - echoI64_result result = new echoI64_result(); - result.success = iface.echoI64(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoDouble extends org.apache.thrift.ProcessFunction { - public echoDouble() { - super("echoDouble"); - } - - protected echoDouble_args getEmptyArgsInstance() { - return new echoDouble_args(); - } - - protected echoDouble_result getResult(I iface, echoDouble_args args) throws org.apache.thrift.TException { - echoDouble_result result = new echoDouble_result(); - result.success = iface.echoDouble(args.arg); - result.setSuccessIsSet(true); - return result; - } - } - - private static class echoString extends org.apache.thrift.ProcessFunction { - public echoString() { - super("echoString"); - } - - protected echoString_args getEmptyArgsInstance() { - return new echoString_args(); - } - - protected echoString_result getResult(I iface, echoString_args args) throws org.apache.thrift.TException { - echoString_result result = new echoString_result(); - result.success = iface.echoString(args.arg); - return result; - } - } - - } - - public static class echoBool_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoBool_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.BOOL, (short)1); - - public boolean arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoBool_args.class, metaDataMap); - } - - public echoBool_args() { - } - - public echoBool_args( - boolean arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoBool_args(echoBool_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoBool_args deepCopy() { - return new echoBool_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = false; - } - - public boolean isArg() { - return this.arg; - } - - public echoBool_args setArg(boolean arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Boolean)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Boolean.valueOf(isArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoBool_args) - return this.equals((echoBool_args)that); - return false; - } - - public boolean equals(echoBool_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoBool_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoBool_args typedOther = (echoBool_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.BOOL) { - this.arg = iprot.readBool(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeBool(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoBool_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoBool_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoBool_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BOOL, (short)0); - - public boolean success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoBool_result.class, metaDataMap); - } - - public echoBool_result() { - } - - public echoBool_result( - boolean success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoBool_result(echoBool_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoBool_result deepCopy() { - return new echoBool_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = false; - } - - public boolean isSuccess() { - return this.success; - } - - public echoBool_result setSuccess(boolean success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Boolean)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Boolean.valueOf(isSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoBool_result) - return this.equals((echoBool_result)that); - return false; - } - - public boolean equals(echoBool_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoBool_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoBool_result typedOther = (echoBool_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.BOOL) { - this.success = iprot.readBool(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeBool(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoBool_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoByte_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoByte_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.BYTE, (short)1); - - public byte arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BYTE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoByte_args.class, metaDataMap); - } - - public echoByte_args() { - } - - public echoByte_args( - byte arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoByte_args(echoByte_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoByte_args deepCopy() { - return new echoByte_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public byte getArg() { - return this.arg; - } - - public echoByte_args setArg(byte arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Byte)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Byte.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoByte_args) - return this.equals((echoByte_args)that); - return false; - } - - public boolean equals(echoByte_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoByte_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoByte_args typedOther = (echoByte_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.BYTE) { - this.arg = iprot.readByte(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeByte(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoByte_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoByte_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoByte_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.BYTE, (short)0); - - public byte success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BYTE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoByte_result.class, metaDataMap); - } - - public echoByte_result() { - } - - public echoByte_result( - byte success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoByte_result(echoByte_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoByte_result deepCopy() { - return new echoByte_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public byte getSuccess() { - return this.success; - } - - public echoByte_result setSuccess(byte success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Byte)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Byte.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoByte_result) - return this.equals((echoByte_result)that); - return false; - } - - public boolean equals(echoByte_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoByte_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoByte_result typedOther = (echoByte_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.BYTE) { - this.success = iprot.readByte(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeByte(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoByte_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI16_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI16_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I16, (short)1); - - public short arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI16_args.class, metaDataMap); - } - - public echoI16_args() { - } - - public echoI16_args( - short arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI16_args(echoI16_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI16_args deepCopy() { - return new echoI16_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public short getArg() { - return this.arg; - } - - public echoI16_args setArg(short arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Short)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Short.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI16_args) - return this.equals((echoI16_args)that); - return false; - } - - public boolean equals(echoI16_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI16_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI16_args typedOther = (echoI16_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I16) { - this.arg = iprot.readI16(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI16(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI16_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI16_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI16_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I16, (short)0); - - public short success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I16))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI16_result.class, metaDataMap); - } - - public echoI16_result() { - } - - public echoI16_result( - short success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI16_result(echoI16_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI16_result deepCopy() { - return new echoI16_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public short getSuccess() { - return this.success; - } - - public echoI16_result setSuccess(short success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Short)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Short.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI16_result) - return this.equals((echoI16_result)that); - return false; - } - - public boolean equals(echoI16_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI16_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI16_result typedOther = (echoI16_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I16) { - this.success = iprot.readI16(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI16(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI16_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI32_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI32_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I32, (short)1); - - public int arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI32_args.class, metaDataMap); - } - - public echoI32_args() { - } - - public echoI32_args( - int arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI32_args(echoI32_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI32_args deepCopy() { - return new echoI32_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public int getArg() { - return this.arg; - } - - public echoI32_args setArg(int arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Integer)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Integer.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI32_args) - return this.equals((echoI32_args)that); - return false; - } - - public boolean equals(echoI32_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI32_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI32_args typedOther = (echoI32_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I32) { - this.arg = iprot.readI32(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI32(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI32_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI32_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI32_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I32, (short)0); - - public int success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI32_result.class, metaDataMap); - } - - public echoI32_result() { - } - - public echoI32_result( - int success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI32_result(echoI32_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI32_result deepCopy() { - return new echoI32_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public int getSuccess() { - return this.success; - } - - public echoI32_result setSuccess(int success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Integer)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Integer.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI32_result) - return this.equals((echoI32_result)that); - return false; - } - - public boolean equals(echoI32_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI32_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI32_result typedOther = (echoI32_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I32) { - this.success = iprot.readI32(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI32(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI32_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI64_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI64_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.I64, (short)1); - - public long arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI64_args.class, metaDataMap); - } - - public echoI64_args() { - } - - public echoI64_args( - long arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI64_args(echoI64_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoI64_args deepCopy() { - return new echoI64_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0; - } - - public long getArg() { - return this.arg; - } - - public echoI64_args setArg(long arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Long)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Long.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI64_args) - return this.equals((echoI64_args)that); - return false; - } - - public boolean equals(echoI64_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI64_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI64_args typedOther = (echoI64_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.I64) { - this.arg = iprot.readI64(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeI64(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI64_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoI64_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoI64_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I64, (short)0); - - public long success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoI64_result.class, metaDataMap); - } - - public echoI64_result() { - } - - public echoI64_result( - long success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoI64_result(echoI64_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoI64_result deepCopy() { - return new echoI64_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0; - } - - public long getSuccess() { - return this.success; - } - - public echoI64_result setSuccess(long success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Long)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Long.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoI64_result) - return this.equals((echoI64_result)that); - return false; - } - - public boolean equals(echoI64_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoI64_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoI64_result typedOther = (echoI64_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.I64) { - this.success = iprot.readI64(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeI64(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoI64_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoDouble_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoDouble_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.DOUBLE, (short)1); - - public double arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoDouble_args.class, metaDataMap); - } - - public echoDouble_args() { - } - - public echoDouble_args( - double arg) - { - this(); - this.arg = arg; - setArgIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoDouble_args(echoDouble_args other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.arg = other.arg; - } - - public echoDouble_args deepCopy() { - return new echoDouble_args(this); - } - - - public void clear() { - setArgIsSet(false); - this.arg = 0.0; - } - - public double getArg() { - return this.arg; - } - - public echoDouble_args setArg(double arg) { - this.arg = arg; - setArgIsSet(true); - return this; - } - - public void unsetArg() { - __isset_bit_vector.clear(__ARG_ISSET_ID); - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return __isset_bit_vector.get(__ARG_ISSET_ID); - } - - public void setArgIsSet(boolean value) { - __isset_bit_vector.set(__ARG_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((Double)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return Double.valueOf(getArg()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoDouble_args) - return this.equals((echoDouble_args)that); - return false; - } - - public boolean equals(echoDouble_args that) { - if (that == null) - return false; - - boolean this_present_arg = true; - boolean that_present_arg = true; - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (this.arg != that.arg) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoDouble_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoDouble_args typedOther = (echoDouble_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.DOUBLE) { - this.arg = iprot.readDouble(); - setArgIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!isSetArg()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not found in serialized data! Struct: " + toString()); - } - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeDouble(this.arg); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoDouble_args("); - boolean first = true; - - sb.append("arg:"); - sb.append(this.arg); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'arg' because it's a primitive and you chose the non-beans generator. - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor. - __isset_bit_vector = new BitSet(1); - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoDouble_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoDouble_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.DOUBLE, (short)0); - - public double success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - private BitSet __isset_bit_vector = new BitSet(1); - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.DOUBLE))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoDouble_result.class, metaDataMap); - } - - public echoDouble_result() { - } - - public echoDouble_result( - double success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public echoDouble_result(echoDouble_result other) { - __isset_bit_vector.clear(); - __isset_bit_vector.or(other.__isset_bit_vector); - this.success = other.success; - } - - public echoDouble_result deepCopy() { - return new echoDouble_result(this); - } - - - public void clear() { - setSuccessIsSet(false); - this.success = 0.0; - } - - public double getSuccess() { - return this.success; - } - - public echoDouble_result setSuccess(double success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bit_vector.clear(__SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return __isset_bit_vector.get(__SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bit_vector.set(__SUCCESS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((Double)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return Double.valueOf(getSuccess()); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoDouble_result) - return this.equals((echoDouble_result)that); - return false; - } - - public boolean equals(echoDouble_result that) { - if (that == null) - return false; - - boolean this_present_success = true; - boolean that_present_success = true; - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (this.success != that.success) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoDouble_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoDouble_result typedOther = (echoDouble_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.DOUBLE) { - this.success = iprot.readDouble(); - setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeDouble(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoDouble_result("); - boolean first = true; - - sb.append("success:"); - sb.append(this.success); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoString_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoString_args"); - - private static final org.apache.thrift.protocol.TField ARG_FIELD_DESC = new org.apache.thrift.protocol.TField("arg", org.apache.thrift.protocol.TType.STRING, (short)1); - - public String arg; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ARG((short)1, "arg"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 1: // ARG - return ARG; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ARG, new org.apache.thrift.meta_data.FieldMetaData("arg", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoString_args.class, metaDataMap); - } - - public echoString_args() { - } - - public echoString_args( - String arg) - { - this(); - this.arg = arg; - } - - /** - * Performs a deep copy on other. - */ - public echoString_args(echoString_args other) { - if (other.isSetArg()) { - this.arg = other.arg; - } - } - - public echoString_args deepCopy() { - return new echoString_args(this); - } - - - public void clear() { - this.arg = null; - } - - public String getArg() { - return this.arg; - } - - public echoString_args setArg(String arg) { - this.arg = arg; - return this; - } - - public void unsetArg() { - this.arg = null; - } - - /** Returns true if field arg is set (has been assigned a value) and false otherwise */ - public boolean isSetArg() { - return this.arg != null; - } - - public void setArgIsSet(boolean value) { - if (!value) { - this.arg = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ARG: - if (value == null) { - unsetArg(); - } else { - setArg((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ARG: - return getArg(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case ARG: - return isSetArg(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoString_args) - return this.equals((echoString_args)that); - return false; - } - - public boolean equals(echoString_args that) { - if (that == null) - return false; - - boolean this_present_arg = true && this.isSetArg(); - boolean that_present_arg = true && that.isSetArg(); - if (this_present_arg || that_present_arg) { - if (!(this_present_arg && that_present_arg)) - return false; - if (!this.arg.equals(that.arg)) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoString_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoString_args typedOther = (echoString_args)other; - - lastComparison = Boolean.valueOf(isSetArg()).compareTo(typedOther.isSetArg()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetArg()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.arg, typedOther.arg); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 1: // ARG - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.arg = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (this.arg != null) { - oprot.writeFieldBegin(ARG_FIELD_DESC); - oprot.writeString(this.arg); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoString_args("); - boolean first = true; - - sb.append("arg:"); - if (this.arg == null) { - sb.append("null"); - } else { - sb.append(this.arg); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (arg == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'arg' was not present! Struct: " + toString()); - } - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - - public static class echoString_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("echoString_result"); - - private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.STRING, (short)0); - - public String success; // required - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - SUCCESS((short)0, "success"); - - private static final Map byName = new HashMap(); - - static { - for (_Fields field : EnumSet.allOf(_Fields.class)) { - byName.put(field.getFieldName(), field); - } - } - - /** - * Find the _Fields constant that matches fieldId, or null if its not found. - */ - public static _Fields findByThriftId(int fieldId) { - switch(fieldId) { - case 0: // SUCCESS - return SUCCESS; - default: - return null; - } - } - - /** - * Find the _Fields constant that matches fieldId, throwing an exception - * if it is not found. - */ - public static _Fields findByThriftIdOrThrow(int fieldId) { - _Fields fields = findByThriftId(fieldId); - if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); - return fields; - } - - /** - * Find the _Fields constant that matches name, or null if its not found. - */ - public static _Fields findByName(String name) { - return byName.get(name); - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - // isset id assignments - - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(echoString_result.class, metaDataMap); - } - - public echoString_result() { - } - - public echoString_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public echoString_result(echoString_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public echoString_result deepCopy() { - return new echoString_result(this); - } - - - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public echoString_result setSuccess(String success) { - this.success = success; - return this; - } - - public void unsetSuccess() { - this.success = null; - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return this.success != null; - } - - public void setSuccessIsSet(boolean value) { - if (!value) { - this.success = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case SUCCESS: - if (value == null) { - unsetSuccess(); - } else { - setSuccess((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case SUCCESS: - return getSuccess(); - - } - throw new IllegalStateException(); - } - - /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ - public boolean isSet(_Fields field) { - if (field == null) { - throw new IllegalArgumentException(); - } - - switch (field) { - case SUCCESS: - return isSetSuccess(); - } - throw new IllegalStateException(); - } - - - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof echoString_result) - return this.equals((echoString_result)that); - return false; - } - - public boolean equals(echoString_result that) { - if (that == null) - return false; - - boolean this_present_success = true && this.isSetSuccess(); - boolean that_present_success = true && that.isSetSuccess(); - if (this_present_success || that_present_success) { - if (!(this_present_success && that_present_success)) - return false; - if (!this.success.equals(that.success)) - return false; - } - - return true; - } - - - public int hashCode() { - return 0; - } - - public int compareTo(echoString_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - echoString_result typedOther = (echoString_result)other; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(typedOther.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, typedOther.success); - if (lastComparison != 0) { - return lastComparison; - } - } - return 0; - } - - public _Fields fieldForId(int fieldId) { - return _Fields.findByThriftId(fieldId); - } - - public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField field; - iprot.readStructBegin(); - while (true) - { - field = iprot.readFieldBegin(); - if (field.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (field.id) { - case 0: // SUCCESS - if (field.type == org.apache.thrift.protocol.TType.STRING) { - this.success = iprot.readString(); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - oprot.writeStructBegin(STRUCT_DESC); - - if (this.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(this.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - - public String toString() { - StringBuilder sb = new StringBuilder("echoString_result("); - boolean first = true; - - sb.append("success:"); - if (this.success == null) { - sb.append("null"); - } else { - sb.append(this.success); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - } - - private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { - try { - write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { - try { - read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); - } catch (org.apache.thrift.TException te) { - throw new java.io.IOException(te); - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/AbstractTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/AbstractTest.java deleted file mode 100644 index 6b68d331b29..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/AbstractTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * File Created at 2011-11-25 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Protocol; -import com.alibaba.dubbo.rpc.gen.dubbo.$__DemoStub; -import com.alibaba.dubbo.rpc.gen.dubbo.Demo; -import com.alibaba.dubbo.rpc.protocol.thrift.ext.MultiServiceProcessor; -import org.apache.thrift.TProcessor; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.server.TServer; -import org.apache.thrift.server.TThreadPoolServer; -import org.apache.thrift.transport.TServerSocket; -import org.apache.thrift.transport.TServerTransport; -import org.apache.thrift.transport.TTransportFactory; -import org.junit.After; -import org.junit.Before; - -/** - * @author gang.lvg 2011-11-25 13:05 - */ -public abstract class AbstractTest { - - static final int PORT = 30660; - - protected TServer server; - - protected Protocol protocol; - - protected Invoker invoker; - - protected void init() throws Exception { - TServerTransport serverTransport = new TServerSocket( PORT ); - - TBinaryProtocol.Factory bFactory = new TBinaryProtocol.Factory(); - - server = new TThreadPoolServer( - new TThreadPoolServer.Args( serverTransport ) - .inputProtocolFactory( bFactory ) - .outputProtocolFactory( bFactory ) - .inputTransportFactory( getTransportFactory() ) - .outputTransportFactory( getTransportFactory() ) - .processor( getProcessor() ) ); - - Thread startTread = new Thread() { - - @Override - public void run() { - server.serve(); - } - - }; - - startTread.setName( "thrift-server" ); - - startTread.start(); - - while( !server.isServing() ) { - Thread.sleep( 100 ); - } - - protocol = ExtensionLoader.getExtensionLoader(Protocol.class) - .getExtension( ThriftProtocol.NAME ); - - invoker = protocol.refer( getInterface(), getUrl() ); - - } - - protected void destroy() throws Exception { - - if ( server != null ) { - server.stop(); - server = null; - } - - if ( protocol != null ) { - protocol.destroy(); - protocol = null; - } - - if ( invoker != null ) { - invoker.destroy(); - invoker = null; - } - - } - - protected TTransportFactory getTransportFactory() { - return new FramedTransportFactory(); - } - - protected $__DemoStub.Iface getServiceImpl() { - return new DubboDemoImpl(); - } - - protected TProcessor getProcessor() { - MultiServiceProcessor result = new MultiServiceProcessor(); - result.addProcessor( - com.alibaba.dubbo.rpc.gen.dubbo.Demo.class, - new $__DemoStub.Processor( getServiceImpl() ) ); - return result; - } - - protected Class getInterface() { - return Demo.class; - } - - protected URL getUrl() { - return URL.valueOf( - "thrift://127.0.0.1:" + PORT + "/" + getInterface().getName() ); - } - - @After - public void tearDown() throws Exception{ - destroy(); - } - - @Before - public void setUp() throws Exception { - init(); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DemoImpl.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DemoImpl.java deleted file mode 100644 index 983e5799d92..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DemoImpl.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * File Created at 2011-11-23 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -/** - * @author gang.lvg 2011-11-23 14:17 - */ -public class DemoImpl { - - public boolean echoBool( boolean arg ) { - - return arg; - } - - public byte echoByte( byte arg ) { - - return arg; - } - - public short echoI16( short arg ) { - - return arg; - } - - public int echoI32( int arg ) { - - return arg; - } - - public long echoI64( long arg ) { - - return arg; - } - - public double echoDouble( double arg ) { - - return arg; - } - - public String echoString( String arg ) { - - return arg; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboDemoImpl.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboDemoImpl.java deleted file mode 100644 index 37c7a056d76..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/DubboDemoImpl.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * File Created at 2011-12-31 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -import com.alibaba.dubbo.rpc.gen.dubbo.$__DemoStub; -import com.alibaba.dubbo.rpc.gen.dubbo.Demo; - -/** - * @author kimi - */ -public class DubboDemoImpl extends DemoImpl implements Demo, $__DemoStub.Iface {} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/FramedTransportFactory.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/FramedTransportFactory.java deleted file mode 100644 index 2ca4a5b54f6..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/FramedTransportFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * File Created at 2011-12-09 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TTransport; -import org.apache.thrift.transport.TTransportFactory; - -/** - * @author kimi - */ -public class FramedTransportFactory extends TTransportFactory { - - @Override - public TTransport getTransport( TTransport trans ) { - - return new TFramedTransport( trans ); - } -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/MockedChannel.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/MockedChannel.java deleted file mode 100644 index 062dc67b6d7..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/MockedChannel.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * File Created at 2011-12-06 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -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 java.net.InetSocketAddress; - -/** - * @author gang.lvg - */ -public class MockedChannel implements Channel { - - private URL url; - - public MockedChannel( URL url ) { - this.url = url; - } - - public InetSocketAddress getRemoteAddress() { - - return null; - } - - public boolean isConnected() { - - return false; - } - - public boolean hasAttribute( String key ) { - - return false; - } - - public Object getAttribute( String key ) { - - return null; - } - - public void setAttribute( String key, Object value ) { - - } - - public void removeAttribute( String key ) { - - } - - public URL getUrl() { - return url; - } - - public ChannelHandler getChannelHandler() { - - return null; - } - - public InetSocketAddress getLocalAddress() { - - return null; - } - - public void send( Object message ) throws RemotingException { - - } - - public void send( Object message, boolean sent ) throws RemotingException { - - } - - public void close() { - - } - - public void close( int timeout ) { - - } - - public boolean isClosed() { - - return false; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServerExceptionTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServerExceptionTest.java deleted file mode 100644 index 58ecbe1520b..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServerExceptionTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/** - * File Created at 2011-12-09 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.gen.dubbo.$__DemoStub; -import org.junit.Assert; -import org.junit.Test; - -/** - * @author kimi - */ -public class ServerExceptionTest extends AbstractTest { - - @Override - protected $__DemoStub.Iface getServiceImpl() { - - return new $__DemoStub.Iface () { - - public boolean echoBool( boolean arg ) { - - return false; - } - - public byte echoByte( byte arg ) { - - return 0; - } - - public short echoI16( short arg ) { - - return 0; - } - - public int echoI32( int arg ) { - - return 0; - } - - public long echoI64( long arg ) { - - return 0; - } - - public double echoDouble( double arg ) { - return 0; - } - - public String echoString( String arg ) { - // 在 server 端,thrift 无法处理 idl 中没有声明的异常 - throw new RuntimeException( "just for test" ); - } - }; - - } - - @Test( expected = RpcException.class ) - public void testServerException() throws Exception { - - Assert.assertNotNull( invoker ); - - RpcInvocation invocation = new RpcInvocation(); - - invocation.setMethodName( "echoString" ); - - invocation.setParameterTypes( new Class[]{ String.class } ); - - String arg = "Hello, World!"; - - invocation.setArguments( new Object[] { arg } ); - - Result result = invoker.invoke( invocation ); - - System.out.println( result ); - - } - - @Override - protected URL getUrl() { - URL url = super.getUrl(); -// url = url.addParameter( Constants.TIMEOUT_KEY, Integer.MAX_VALUE ); - return url; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java deleted file mode 100644 index 224e1c8a93c..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/** - * File Created at 2011-12-09 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.gen.dubbo.$__DemoStub; -import com.alibaba.dubbo.rpc.gen.dubbo.Demo; -import com.alibaba.dubbo.rpc.protocol.thrift.ext.MultiServiceProcessor; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.server.TThreadPoolServer; -import org.apache.thrift.transport.TServerSocket; -import org.apache.thrift.transport.TServerTransport; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.lang.reflect.Field; -import java.util.Map; - -/** - * @author kimi - */ -public class ServiceMethodNotFoundTest extends AbstractTest { - - private URL url; - - protected void init() throws Exception { - - TServerTransport serverTransport = new TServerSocket( PORT ); - - DubboDemoImpl impl = new DubboDemoImpl(); - - $__DemoStub.Processor processor = new $__DemoStub.Processor( impl ); - - // for test - Field field = processor.getClass().getSuperclass().getDeclaredField( "processMap" ); - - field.setAccessible( true ); - - Object obj = field.get( processor ); - - if ( obj instanceof Map ) { - ( ( Map ) obj ).remove( "echoString" ); - } - // ~ - - TBinaryProtocol.Factory bFactory = new TBinaryProtocol.Factory(); - - MultiServiceProcessor wrapper = new MultiServiceProcessor(); - wrapper.addProcessor( Demo.class, processor ); - - server = new TThreadPoolServer( - new TThreadPoolServer.Args( serverTransport ) - .inputProtocolFactory( bFactory ) - .outputProtocolFactory( bFactory ) - .inputTransportFactory( getTransportFactory() ) - .outputTransportFactory( getTransportFactory() ) - .processor( wrapper ) ); - - Thread startTread = new Thread() { - - @Override - public void run() { - - server.serve(); - } - - }; - - startTread.start(); - - while ( !server.isServing() ) { - Thread.sleep( 100 ); - } - - } - - @Before - public void setUp() throws Exception { - - init(); - - protocol = new ThriftProtocol(); - - url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:" + PORT + "/" + Demo.class.getName() ); - - } - - @After - public void tearDown() throws Exception { - - destroy(); - - if ( protocol != null ) { - protocol.destroy(); - protocol = null; - } - - if ( invoker != null ) { - invoker.destroy(); - invoker = null; - } - - } - - @Test - public void testServiceMethodNotFound() throws Exception { - // FIXME - /*url = url.addParameter( "echoString." + Constants.TIMEOUT_KEY, Integer.MAX_VALUE ); - - invoker = protocol.refer( Demo.class, url ); - - org.junit.Assert.assertNotNull( invoker ); - - RpcInvocation invocation = new RpcInvocation(); - - invocation.setMethodName( "echoString" ); - - invocation.setParameterTypes( new Class[]{ String.class } ); - - String arg = "Hello, World!"; - - invocation.setArguments( new Object[] { arg } ); - - invocation.setAttachment(Constants.INTERFACE_KEY, DemoImpl.class.getName()); - - Result result = invoker.invoke( invocation ); - - Assert.assertNull( result.getResult() ); - - Assert.assertTrue( result.getException() instanceof RpcException );*/ - - } - -} 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 deleted file mode 100644 index 4b0ecdaa0d1..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftCodecTest.java +++ /dev/null @@ -1,460 +0,0 @@ -/** - * File Created at 2011-12-05 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.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; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.RpcResult; -import com.alibaba.dubbo.rpc.gen.thrift.Demo; -import com.alibaba.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; - -/** - * @author gang.lvg - */ -public class ThriftCodecTest { - - private ThriftCodec codec = new ThriftCodec(); - private Channel channel = new MockedChannel(URL.valueOf("thrift://127.0.0.1")); - - @Test - public void testEncodeRequest() throws Exception { - - Request request = createRequest(); - - ChannelBuffer output = ChannelBuffers.dynamicBuffer(1024); - - codec.encode( channel, output, request ); - - byte[] bytes = new byte[output.readableBytes()]; - output.readBytes(bytes); - - ByteArrayInputStream bis = new ByteArrayInputStream( bytes ); - - TTransport transport = new TIOStreamTransport( bis ); - - TBinaryProtocol protocol = new TBinaryProtocol( transport ); - - // frame - byte[] length = new byte[4]; - transport.read( length, 0, 4 ); - - if ( bis.markSupported() ) { - bis.mark( 0 ); - } - - // magic - Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() ); - - // message length - int messageLength = protocol.readI32(); - Assert.assertEquals( messageLength + 4, bytes.length ); - - // header length - short headerLength = protocol.readI16(); - // version - Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() ); - // service name - Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() ); - // dubbo request id - Assert.assertEquals( request.getId(), protocol.readI64() ); - - // test message header length - if ( bis.markSupported() ) { - bis.reset(); - bis.skip( headerLength ); - } - - TMessage message = protocol.readMessageBegin(); - - Demo.echoString_args args = new Demo.echoString_args(); - - args.read( protocol ); - - protocol.readMessageEnd(); - - Assert.assertEquals( "echoString", message.name ); - - Assert.assertEquals( TMessageType.CALL, message.type ); - - Assert.assertEquals( "Hello, World!", args.getArg() ); - - } - - @Test - public void testDecodeReplyResponse() throws Exception { - - URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() ); - - Channel channel = new MockedChannel( url ); - - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 128 ); - - Request request = createRequest(); - - DefaultFuture future = new DefaultFuture( channel, request, 10 ); - - TMessage message = new TMessage( "echoString", TMessageType.REPLY, ThriftCodec.getSeqId() ); - - Demo.echoString_result methodResult = new Demo.echoString_result(); - - methodResult.success = "Hello, World!"; - - TTransport transport = new TIOStreamTransport( bos ); - - TBinaryProtocol protocol = new TBinaryProtocol( transport ); - - int messageLength, headerLength; - // prepare - protocol.writeI16( ThriftCodec.MAGIC ); - protocol.writeI32( Integer.MAX_VALUE ); - protocol.writeI16( Short.MAX_VALUE ); - protocol.writeByte( ThriftCodec.VERSION ); - protocol.writeString( Demo.Iface.class.getName() ); - protocol.writeI64( request.getId() ); - protocol.getTransport().flush(); - headerLength = bos.size(); - - protocol.writeMessageBegin( message ); - methodResult.write( protocol ); - protocol.writeMessageEnd(); - protocol.getTransport().flush(); - int oldIndex = messageLength = bos.size(); - - try { - bos.setWriteIndex( ThriftCodec.MESSAGE_LENGTH_INDEX ); - protocol.writeI32( messageLength ); - bos.setWriteIndex( ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX ); - protocol.writeI16( ( short ) ( 0xffff & headerLength ) ); - } finally { - bos.setWriteIndex( oldIndex ); - } - // prepare - - byte[] buf = new byte[ 4 + bos.size()]; - System.arraycopy( bos.toByteArray(), 0, buf, 4, bos.size() ); - - ChannelBuffer bis = ChannelBuffers.wrappedBuffer(buf); - - Object obj = codec.decode( ( Channel ) null, bis ); - - Assert.assertNotNull( obj ); - - Assert.assertEquals( true, obj instanceof Response ); - - Response response = ( Response ) obj; - - Assert.assertEquals( request.getId(), response.getId() ); - - Assert.assertTrue( response.getResult() instanceof RpcResult ); - - RpcResult result = ( RpcResult ) response.getResult(); - - Assert.assertTrue( result.getResult() instanceof String ); - - Assert.assertEquals( methodResult.success, result.getResult() ); - - } - - @Test - public void testDecodeExceptionResponse() throws Exception { - - URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.class.getName() ); - - Channel channel = new MockedChannel( url ); - - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 128 ); - - Request request = createRequest(); - - DefaultFuture future = new DefaultFuture( channel, request, 10 ); - - TMessage message = new TMessage( "echoString", TMessageType.EXCEPTION, ThriftCodec.getSeqId() ); - - TTransport transport = new TIOStreamTransport( bos ); - - TBinaryProtocol protocol = new TBinaryProtocol( transport ); - - TApplicationException exception = new TApplicationException(); - - int messageLength, headerLength; - // prepare - protocol.writeI16( ThriftCodec.MAGIC ); - protocol.writeI32( Integer.MAX_VALUE ); - protocol.writeI16( Short.MAX_VALUE ); - protocol.writeByte( ThriftCodec.VERSION ); - protocol.writeString( Demo.class.getName() ); - protocol.writeI64( request.getId() ); - protocol.getTransport().flush(); - headerLength = bos.size(); - - protocol.writeMessageBegin( message ); - exception.write( protocol ); - protocol.writeMessageEnd(); - protocol.getTransport().flush(); - int oldIndex = messageLength = bos.size(); - - try { - bos.setWriteIndex( ThriftCodec.MESSAGE_LENGTH_INDEX ); - protocol.writeI32( messageLength ); - bos.setWriteIndex( ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX ); - protocol.writeI16( ( short ) ( 0xffff & headerLength ) ); - } finally { - bos.setWriteIndex( oldIndex ); - } - // prepare - - ChannelBuffer bis = ChannelBuffers.wrappedBuffer(encodeFrame(bos.toByteArray())); - - Object obj = codec.decode( ( Channel ) null, bis ); - - Assert.assertNotNull( obj ); - - Assert.assertTrue( obj instanceof Response ); - - Response response = ( Response ) obj; - - Assert.assertTrue( response.getResult() instanceof RpcResult ); - - RpcResult result = ( RpcResult ) response.getResult(); - - Assert.assertTrue( result.hasException() ); - - Assert.assertTrue( result.getException() instanceof RpcException ); - - } - - @Test - public void testEncodeReplyResponse() throws Exception { - - URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() ); - - Channel channel = new MockedChannel( url ); - - Request request = createRequest(); - - RpcResult rpcResult = new RpcResult(); - rpcResult.setResult( "Hello, World!" ); - - Response response = new Response(); - response.setResult( rpcResult ); - response.setId( request.getId() ); - 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.writerIndex() - 4]; - System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 ); - - ByteArrayInputStream bis = new ByteArrayInputStream( buf ); - - if ( bis.markSupported() ) { - bis.mark( 0 ); - } - - TIOStreamTransport transport = new TIOStreamTransport( bis ); - TBinaryProtocol protocol = new TBinaryProtocol( transport ); - - Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() ); - Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() ); - int headerLength = protocol.readI16(); - - Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() ); - Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() ); - Assert.assertEquals( request.getId(), protocol.readI64() ); - - if ( bis.markSupported() ) { - bis.reset(); - bis.skip( headerLength ); - } - - TMessage message = protocol.readMessageBegin(); - Assert.assertEquals( "echoString", message.name ); - Assert.assertEquals( TMessageType.REPLY, message.type ); - Assert.assertEquals( ThriftCodec.getSeqId(), message.seqid ); - Demo.echoString_result result = new Demo.echoString_result(); - result.read( protocol ); - protocol.readMessageEnd(); - - Assert.assertEquals( rpcResult.getValue(), result.getSuccess() ); - } - - @Test - public void testEncodeExceptionResponse() throws Exception { - - URL url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:40880/" + Demo.Iface.class.getName() ); - - Channel channel = new MockedChannel( url ); - - Request request = createRequest(); - - RpcResult rpcResult = new RpcResult(); - String exceptionMessage = "failed"; - rpcResult.setException( new RuntimeException( exceptionMessage ) ); - - Response response = new Response(); - response.setResult( rpcResult ); - response.setId( request.getId() ); - 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.writerIndex() - 4]; - System.arraycopy( bos.array(), 4, buf, 0, bos.writerIndex() - 4 ); - ByteArrayInputStream bis = new ByteArrayInputStream( buf); - - if ( bis.markSupported() ) { - bis.mark( 0 ); - } - - TIOStreamTransport transport = new TIOStreamTransport( bis ); - TBinaryProtocol protocol = new TBinaryProtocol( transport ); - - Assert.assertEquals( ThriftCodec.MAGIC, protocol.readI16() ); - Assert.assertEquals( protocol.readI32() + 4, bos.writerIndex() ); - int headerLength = protocol.readI16(); - - Assert.assertEquals( ThriftCodec.VERSION, protocol.readByte() ); - Assert.assertEquals( Demo.Iface.class.getName(), protocol.readString() ); - Assert.assertEquals( request.getId(), protocol.readI64() ); - - if ( bis.markSupported() ) { - bis.reset(); - bis.skip( headerLength ); - } - - TMessage message = protocol.readMessageBegin(); - Assert.assertEquals( "echoString", message.name ); - Assert.assertEquals( TMessageType.EXCEPTION, message.type ); - Assert.assertEquals( ThriftCodec.getSeqId(), message.seqid ); - TApplicationException exception = TApplicationException.read( protocol ); - protocol.readMessageEnd(); - - Assert.assertEquals( exceptionMessage, exception.getMessage() ); - - } - - @Test - public void testDecodeRequest() throws Exception { - Request request = createRequest(); - // encode - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream( 1024 ); - - TIOStreamTransport transport = new TIOStreamTransport( bos ); - - TBinaryProtocol protocol = new TBinaryProtocol( transport ); - - int messageLength, headerLength; - - protocol.writeI16( ThriftCodec.MAGIC ); - protocol.writeI32( Integer.MAX_VALUE ); - protocol.writeI16( Short.MAX_VALUE ); - protocol.writeByte( ThriftCodec.VERSION ); - protocol.writeString( - ( ( RpcInvocation ) request.getData() ) - .getAttachment( Constants.INTERFACE_KEY) ); - protocol.writeI64( request.getId() ); - protocol.getTransport().flush(); - headerLength = bos.size(); - - Demo.echoString_args args = new Demo.echoString_args( ); - args.setArg( "Hell, World!" ); - - TMessage message = new TMessage( "echoString", TMessageType.CALL, ThriftCodec.getSeqId() ); - - protocol.writeMessageBegin( message ); - args.write( protocol ); - protocol.writeMessageEnd(); - protocol.getTransport().flush(); - int oldIndex = messageLength = bos.size(); - - try{ - bos.setWriteIndex( ThriftCodec.MESSAGE_HEADER_LENGTH_INDEX ); - protocol.writeI16( ( short ) ( 0xffff & headerLength ) ); - bos.setWriteIndex( ThriftCodec.MESSAGE_LENGTH_INDEX ); - protocol.writeI32( messageLength ); - } finally { - bos.setWriteIndex( oldIndex ); - } - - Object obj = codec.decode( ( Channel ) null, ChannelBuffers.wrappedBuffer( - encodeFrame(bos.toByteArray())) ); - - Assert.assertTrue( obj instanceof Request ); - - obj = ( ( Request ) obj ).getData(); - - Assert.assertTrue( obj instanceof RpcInvocation ); - - RpcInvocation invocation = ( RpcInvocation ) obj; - - Assert.assertEquals( "echoString", invocation.getMethodName() ); - Assert.assertArrayEquals( new Class[] {String .class}, invocation.getParameterTypes() ); - Assert.assertArrayEquals( new Object[] { args.getArg() }, invocation.getArguments() ); - - } - - private Request createRequest() { - - RpcInvocation invocation = new RpcInvocation(); - - invocation.setMethodName( "echoString" ); - - invocation.setArguments( new Object[]{ "Hello, World!" } ); - - invocation.setParameterTypes( new Class[]{ String.class } ); - - invocation.setAttachment( Constants.INTERFACE_KEY, Demo.Iface.class.getName() ); - - Request request = new Request( 1L ); - - request.setData( invocation ); - - return request; - - } - - static byte[] encodeFrame( byte[] content ) { - byte[] result = new byte[4+content.length]; - TFramedTransport.encodeFrameSize( content.length, result ); - System.arraycopy( content, 0, result, 4, content.length ); - return result; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftDemoImpl.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftDemoImpl.java deleted file mode 100644 index 38bcd4c62d9..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftDemoImpl.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * File Created at 2011-12-31 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -import com.alibaba.dubbo.rpc.gen.thrift.Demo; -import org.apache.thrift.TException; - -/** - * @author kimi - */ -public class ThriftDemoImpl extends DemoImpl implements Demo.Iface {} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java deleted file mode 100644 index a233cc18013..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * File Created at 2011-12-08 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.rpc.Invoker; -import com.alibaba.dubbo.rpc.Result; -import com.alibaba.dubbo.rpc.RpcInvocation; -import com.alibaba.dubbo.rpc.gen.dubbo.Demo; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * @author kimi - */ -public class ThriftProtocolTest extends AbstractTest { - - public static final int DEFAULT_PORT = 30660; - - private ThriftProtocol protocol; - - private Invoker invoker; - - private URL url; - - @Before - public void setUp() throws Exception { - - init(); - - protocol = new ThriftProtocol(); - - url = URL.valueOf( ThriftProtocol.NAME + "://127.0.0.1:" + PORT + "/" + Demo.class.getName() ); - - } - - @After - public void tearDown() throws Exception { - - destroy(); - - if ( protocol != null ) { - protocol.destroy(); - protocol = null; - } - - if ( invoker != null ) { - invoker.destroy(); - invoker = null; - } - - } - - @Test - public void testRefer() throws Exception { - // FIXME - /*invoker = protocol.refer( Demo.class, url ); - - Assert.assertNotNull( invoker ); - - RpcInvocation invocation = new RpcInvocation(); - - invocation.setMethodName( "echoString" ); - - invocation.setParameterTypes( new Class[]{ String.class } ); - - String arg = "Hello, World!"; - - invocation.setArguments( new Object[] { arg } ); - - Result result = invoker.invoke( invocation ); - - Assert.assertEquals( arg, result.getResult() );*/ - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java deleted file mode 100644 index 9cd1f5826da..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * File Created at 2011-12-05 - * $Id$ - * - * Copyright 2008 Alibaba.com Croporation 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.rpc.protocol.thrift; - -import com.alibaba.dubbo.common.extension.ExtensionLoader; -import com.alibaba.dubbo.rpc.gen.dubbo.$__DemoStub; -import org.junit.Assert; -import org.junit.Test; - -/** - * @author gang.lvg - */ -public class ThriftUtilsTest { - - @Test - public void testGenerateMethodArgsClassName() { - - Assert.assertEquals( - $__DemoStub.echoString_args.class.getName(), - ThriftUtils.generateMethodArgsClassName( - com.alibaba.dubbo.rpc.gen.dubbo.Demo.class.getName(), - "echoString" ) ); - - Assert.assertEquals( - $__DemoStub.echoString_args.class.getName(), - ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) - .getExtension( DubboClassNameGenerator.NAME ).generateArgsClassName( - com.alibaba.dubbo.rpc.gen.dubbo.Demo.class.getName(), "echoString" ) ); - - } - - @Test - public void testGenerateMethodResultClassName() { - - Assert.assertEquals( $__DemoStub.echoString_result.class.getName(), - ThriftUtils.generateMethodResultClassName( - com.alibaba.dubbo.rpc.gen.dubbo.Demo.class.getName(), - "echoString" )); - - Assert.assertEquals( $__DemoStub.echoString_result.class.getName(), - ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ) - .getExtension( DubboClassNameGenerator.NAME ).generateResultClassName ( - com.alibaba.dubbo.rpc.gen.dubbo.Demo.class.getName(), "echoString" )); - - } - - @Test - public void testGenerateMethodArgsClassNameThrift() { - Assert.assertEquals( com.alibaba.dubbo.rpc.gen.thrift.Demo.echoString_args.class.getName(), - ThriftUtils.generateMethodArgsClassNameThrift( - com.alibaba.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString" ) ); - - Assert.assertEquals( com.alibaba.dubbo.rpc.gen.thrift.Demo.echoString_args.class.getName(), - ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ) - .getExtension( ThriftClassNameGenerator.NAME ).generateArgsClassName( - com.alibaba.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString" ) ); - - } - - @Test - public void testGenerateMethodResultClassNameThrift() { - Assert.assertEquals( com.alibaba.dubbo.rpc.gen.thrift.Demo.echoString_result.class.getName(), - ThriftUtils.generateMethodResultClassNameThrift( - com.alibaba.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString" ) ); - - Assert.assertEquals( com.alibaba.dubbo.rpc.gen.thrift.Demo.echoString_result.class.getName(), - ExtensionLoader.getExtensionLoader( ClassNameGenerator.class ) - .getExtension( ThriftClassNameGenerator.NAME ).generateResultClassName( - com.alibaba.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString" ) ); - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java deleted file mode 100644 index 369f61a5c8d..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift.examples; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.rpc.gen.thrift.Demo; - -/** - * @author kimi - */ -public class DubboDemoConsumer { - - public static void main(String[] args) throws Exception { - ClassPathXmlApplicationContext context = - new ClassPathXmlApplicationContext("dubbo-demo-consumer.xml"); - context.start(); - Demo.Iface demo = (Demo.Iface) context.getBean("demoService"); - System.out.println(demo.echoI32(32)); - for (int i = 0; i < 10; i++) { - System.out.println(demo.echoI32(i + 1)); - } - context.close(); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoProvider.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoProvider.java deleted file mode 100644 index d65d21e69a7..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/com/alibaba/dubbo/rpc/protocol/thrift/examples/DubboDemoProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.alibaba.dubbo.rpc.protocol.thrift.examples; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * @author kimi - */ -public class DubboDemoProvider { - - public static void main(String[] args) throws Exception { - ClassPathXmlApplicationContext context = - new ClassPathXmlApplicationContext("dubbo-demo-provider.xml"); - context.start(); - System.out.println("context started"); - System.in.read(); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-consumer.xml b/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-consumer.xml deleted file mode 100644 index 4f1ccc42380..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-consumer.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-provider.xml b/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-provider.xml deleted file mode 100644 index 8727b7bea1e..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-provider.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestDubbo.thrift b/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestDubbo.thrift deleted file mode 100644 index 3e2023a9e17..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestDubbo.thrift +++ /dev/null @@ -1,3 +0,0 @@ -service ClassNameTestDubbo { - string echo(1:required string arg); -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestThrift.thrift b/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestThrift.thrift deleted file mode 100644 index ccac7a1e0a4..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestThrift.thrift +++ /dev/null @@ -1,3 +0,0 @@ -service ClassNameTestThrift { - string echo(1:required string arg); -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/Demo.thrift b/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/Demo.thrift deleted file mode 100644 index 91a264a5251..00000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/Demo.thrift +++ /dev/null @@ -1,16 +0,0 @@ -namespace dubbo_java com.alibaba.dubbo.rpc.gen.dubbo -namespace dubbo_cpp com.alibaba.dubbo.rpc.gen.dubbo - -namespace java com.alibaba.dubbo.rpc.gen.thrift -namespace cpp com.alibaba.dubbo.rpc.gen.thrift - -service Demo { - bool echoBool( 1:required bool arg ); - byte echoByte( 1:required byte arg ); - i16 echoI16 ( 1:required i16 arg ); - i32 echoI32 ( 1:required i32 arg ); - i64 echoI64 ( 1:required i64 arg ); - - double echoDouble( 1:required double arg ); - string echoString( 1:required string arg ); -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift2/pom.xml b/dubbo-rpc/dubbo-rpc-thrift2/pom.xml new file mode 100644 index 00000000000..d5e36ef0809 --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-thrift2/pom.xml @@ -0,0 +1,57 @@ + + + 4.0.0 + + com.alibaba + dubbo-rpc + 2.8.5-SNAPSHOT + + dubbo-rpc-thrift2 + jar + ${project.artifactId} + The avro-rpc module of dubbo project + + true + + + + + com.alibaba + dubbo-rpc-api + ${project.parent.version} + + + + org.apache.thrift + libthrift + 0.9.3 + + + org.apache.httpcomponents + httpcore + + + + + + commons-pool + commons-pool + 1.6 + + + \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift2/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift2/Thrift2Protocol.java b/dubbo-rpc/dubbo-rpc-thrift2/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift2/Thrift2Protocol.java new file mode 100644 index 00000000000..605a7f6b68f --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-thrift2/src/main/java/com/alibaba/dubbo/rpc/protocol/thrift2/Thrift2Protocol.java @@ -0,0 +1,326 @@ +package com.alibaba.dubbo.rpc.protocol.thrift2; + +import com.alibaba.dubbo.common.URL; +import com.alibaba.dubbo.common.logger.Logger; +import com.alibaba.dubbo.common.logger.LoggerFactory; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import org.apache.thrift.TException; +import org.apache.thrift.TProcessor; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TCompactProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.server.TNonblockingServer; +import org.apache.thrift.server.TServer; +import org.apache.thrift.server.TThreadPoolServer; +import org.apache.thrift.server.TThreadedSelectorServer; +import org.apache.thrift.transport.*; + +import java.lang.reflect.Constructor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +/** + * 为dubbo-rpc添加"原生thrift"支持 + * by 杨俊明(http://yjmyzz.cnblogs.com/) + */ +public class Thrift2Protocol extends AbstractProxyProtocol { + public static final int DEFAULT_PORT = 33208; + private static final Logger logger = LoggerFactory.getLogger(Thrift2Protocol.class); + + public int getDefaultPort() { + return DEFAULT_PORT; + } + + public Thrift2Protocol() { + super(TException.class, RpcException.class); + } + + + @Override + protected Runnable doExport(T impl, Class type, URL url) + throws RpcException { + + logger.info("impl => " + impl.getClass()); + logger.info("type => " + type.getName()); + logger.info("url => " + url); + + return exportNonblockingServer(impl, type, url); + //return exportThreadPoolServer(impl, type, url); + //return exportThreadedSelectorServer(impl, type, url); + } + + @Override + protected T doRefer(Class type, URL url) throws RpcException { + logger.info("type => " + type.getName()); + logger.info("url => " + url); + return doReferFrameAndCompact(type, url); + //return doReferFrameAndBinary(type, url); + } + + + private Runnable exportNonblockingServer(T impl, Class type, URL url) + throws RpcException { + TProcessor tprocessor; + TNonblockingServer.Args tArgs = null; + String iFace = "$Iface"; + String processor = "$Processor"; + String typeName = type.getName(); + TNonblockingServerSocket transport; + if (typeName.endsWith(iFace)) { + String processorClsName = typeName.substring(0, typeName.indexOf(iFace)) + processor; + try { + Class clazz = Class.forName(processorClsName); + Constructor constructor = clazz.getConstructor(type); + try { + tprocessor = (TProcessor) constructor.newInstance(impl); + transport = new TNonblockingServerSocket(url.getPort()); + tArgs = new TNonblockingServer.Args(transport); + tArgs.processor(tprocessor); + tArgs.transportFactory(new TFramedTransport.Factory()); + tArgs.protocolFactory(new TBinaryProtocol.Factory()); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create thrift server(" + url + ") : " + e.getMessage(), e); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create thrift server(" + url + ") : " + e.getMessage(), e); + } + } + + if (tArgs == null) { + logger.error("Fail to create thrift server(" + url + ") due to null args"); + throw new RpcException("Fail to create thrift server(" + url + ") due to null args"); + } + final TServer thriftServer = new TNonblockingServer(tArgs); + + new Thread(new Runnable() { + public void run() { + logger.info("Start Thrift NonblockingServer"); + thriftServer.serve(); + logger.info("Thrift NonblockingServer started."); + } + }).start(); + + return new Runnable() { + public void run() { + try { + logger.info("Close Thrift NonblockingServer"); + thriftServer.stop(); + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + } + } + }; + } + + private Runnable exportThreadPoolServer(T impl, Class type, URL url) + throws RpcException { + TProcessor tprocessor; + TThreadPoolServer.Args tArgs = null; + String iFace = "$Iface"; + String processor = "$Processor"; + String typeName = type.getName(); + TServerTransport transport; + if (typeName.endsWith(iFace)) { + String processorClsName = typeName.substring(0, typeName.indexOf(iFace)) + processor; + try { + Class clazz = Class.forName(processorClsName); + Constructor constructor = clazz.getConstructor(type); + try { + tprocessor = (TProcessor) constructor.newInstance(impl); + transport = new TServerSocket(url.getPort()); + tArgs = new TThreadPoolServer.Args(transport); + tArgs.processor(tprocessor); + tArgs.executorService(Executors.newFixedThreadPool(100)); + tArgs.protocolFactory(new TBinaryProtocol.Factory()); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create thrift server(" + url + ") : " + e.getMessage(), e); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create thrift server(" + url + ") : " + e.getMessage(), e); + } + } + + if (tArgs == null) { + logger.error("Fail to create thrift server(" + url + ") due to null args"); + throw new RpcException("Fail to create thrift server(" + url + ") due to null args"); + } + final TServer thriftServer = new TThreadPoolServer(tArgs); + + ExecutorService service = Executors.newFixedThreadPool(50); + service.submit(() -> { + logger.info("Start Thrift ThreadPoolServer"); + thriftServer.serve(); + logger.info("Thrift ThreadPoolServer started."); + }); + + return () -> { + try { + logger.info("Close Thrift ThreadPoolServer"); + thriftServer.stop(); + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + } + }; + } + + private Runnable exportThreadedSelectorServer(T impl, Class type, URL url) + throws RpcException { + TProcessor tprocessor; + TThreadedSelectorServer.Args tArgs = null; + String iFace = "$Iface"; + String processor = "$Processor"; + String typeName = type.getName(); + TNonblockingServerSocket transport; + if (typeName.endsWith(iFace)) { + String processorClsName = typeName.substring(0, typeName.indexOf(iFace)) + processor; + try { + Class clazz = Class.forName(processorClsName); + Constructor constructor = clazz.getConstructor(type); + try { + tprocessor = (TProcessor) constructor.newInstance(impl); + transport = new TNonblockingServerSocket(url.getPort()); + tArgs = new TThreadedSelectorServer.Args(transport); + tArgs.processor(tprocessor); + tArgs.executorService(Executors.newFixedThreadPool(100)); + tArgs.protocolFactory(new TBinaryProtocol.Factory()); + tArgs.transportFactory(new TFramedTransport.Factory()); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create thrift server(" + url + ") : " + e.getMessage(), e); + } + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create thrift server(" + url + ") : " + e.getMessage(), e); + } + } + + if (tArgs == null) { + logger.error("Fail to create thrift server(" + url + ") due to null args"); + throw new RpcException("Fail to create thrift server(" + url + ") due to null args"); + } + final TServer thriftServer = new TThreadedSelectorServer(tArgs); + + new Thread(new Runnable() { + public void run() { + logger.info("Start Thrift ThreadedSelectorServer"); + thriftServer.serve(); + logger.info("Thrift ThreadedSelectorServer started."); + } + }).start(); + + return () -> { + try { + logger.info("Close Thrift ThreadedSelectorServer"); + thriftServer.stop(); + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + } + }; + } + + + private T doReferFrameAndCompact(Class type, URL url) throws RpcException { + try { + TSocket tSocket; + TTransport transport; + TProtocol protocol; + T thriftClient = null; + String iFace = "$Iface"; + String client = "$Client"; + + String typeName = type.getName(); + if (typeName.endsWith(iFace)) { + String clientClsName = typeName.substring(0, typeName.indexOf(iFace)) + client; + Class clazz = Class.forName(clientClsName); + Constructor constructor = clazz.getConstructor(TProtocol.class); + try { + tSocket = new TSocket(url.getHost(), url.getPort()); + transport = new TFramedTransport(tSocket); + protocol = new TCompactProtocol(transport); + thriftClient = (T) constructor.newInstance(protocol); + transport.open(); + logger.info("thrift client opened for service(" + url + ")"); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create remote client:" + e.getMessage(), e); + } + } + return thriftClient; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create remote client for service(" + url + "): " + e.getMessage(), e); + } + } + + private T doReferFrameAndBinary(Class type, URL url) throws RpcException { + try { + TSocket tSocket; + TTransport transport; + TProtocol protocol; + T thriftClient = null; + String iFace = "$Iface"; + String client = "$Client"; + + String typeName = type.getName(); + if (typeName.endsWith(iFace)) { + String clientClsName = typeName.substring(0, typeName.indexOf(iFace)) + client; + Class clazz = Class.forName(clientClsName); + Constructor constructor = clazz.getConstructor(TProtocol.class); + try { + tSocket = new TSocket(url.getHost(), url.getPort()); + transport = new TFramedTransport(tSocket); + protocol = new TBinaryProtocol(transport); + thriftClient = (T) constructor.newInstance(protocol); + transport.open(); + logger.info("thrift client opened for service(" + url + ")"); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create remote client:" + e.getMessage(), e); + } + } + return thriftClient; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create remote client for service(" + url + "): " + e.getMessage(), e); + } + } + + + private T doReferBinary(Class type, URL url) throws RpcException { + + try { + TTransport transport; + TProtocol protocol; + T thriftClient = null; + String iFace = "$Iface"; + String client = "$Client"; + + String typeName = type.getName(); + if (typeName.endsWith(iFace)) { + String clientClsName = typeName.substring(0, typeName.indexOf(iFace)) + client; + Class clazz = Class.forName(clientClsName); + Constructor constructor = clazz.getConstructor(TProtocol.class); + try { + transport = new TSocket(url.getHost(), url.getPort()); + protocol = new TBinaryProtocol(transport); + thriftClient = (T) constructor.newInstance(protocol); + transport.open(); + logger.info("thrift client opened for service(" + url + ")"); + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create remote client:" + e.getMessage(), e); + } + } + return thriftClient; + } catch (Exception e) { + logger.error(e.getMessage(), e); + throw new RpcException("Fail to create remote client for service(" + url + "): " + e.getMessage(), e); + } + } + +} diff --git a/dubbo-rpc/dubbo-rpc-thrift2/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-thrift2/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol new file mode 100644 index 00000000000..e289229aeac --- /dev/null +++ b/dubbo-rpc/dubbo-rpc-thrift2/src/main/resources/META-INF/dubbo/internal/com.alibaba.dubbo.rpc.Protocol @@ -0,0 +1 @@ +thrift2=com.alibaba.dubbo.rpc.protocol.thrift2.Thrift2Protocol diff --git a/dubbo-rpc/dubbo-rpc-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml index 069d285b432..c827373cd1a 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.5-SNAPSHOT dubbo-rpc-webservice jar diff --git a/dubbo-rpc/dubbo-rpc-webservice/src/main/java/com/alibaba/dubbo/rpc/protocol/webservice/WebServiceProtocol.java b/dubbo-rpc/dubbo-rpc-webservice/src/main/java/com/alibaba/dubbo/rpc/protocol/webservice/WebServiceProtocol.java index 7432aeb824c..2418a271ab8 100644 --- a/dubbo-rpc/dubbo-rpc-webservice/src/main/java/com/alibaba/dubbo/rpc/protocol/webservice/WebServiceProtocol.java +++ b/dubbo-rpc/dubbo-rpc-webservice/src/main/java/com/alibaba/dubbo/rpc/protocol/webservice/WebServiceProtocol.java @@ -15,16 +15,15 @@ */ package com.alibaba.dubbo.rpc.protocol.webservice; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - +import com.alibaba.dubbo.common.Constants; +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.DispatcherServlet; +import com.alibaba.dubbo.rpc.RpcContext; +import com.alibaba.dubbo.rpc.RpcException; +import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; import org.apache.cxf.bus.extension.ExtensionManagerBus; import org.apache.cxf.endpoint.Client; import org.apache.cxf.frontend.ClientProxy; @@ -38,33 +37,34 @@ import org.apache.cxf.transport.servlet.ServletDestinationFactory; import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; -import com.alibaba.dubbo.common.Constants; -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.DispatcherServlet; -import com.alibaba.dubbo.rpc.RpcContext; -import com.alibaba.dubbo.rpc.RpcException; -import com.alibaba.dubbo.rpc.protocol.AbstractProxyProtocol; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** * WebServiceProtocol. - * + * * @author netcomm */ public class WebServiceProtocol extends AbstractProxyProtocol { - + public static final int DEFAULT_PORT = 80; private final Map serverMap = new ConcurrentHashMap(); - + private final ExtensionManagerBus bus = new ExtensionManagerBus(); - private final HTTPTransportFactory transportFactory = new HTTPTransportFactory(bus); - + //private final HTTPTransportFactory transportFactory = new HTTPTransportFactory(bus);//升级cxf到3.0.5后,编译通不过,暂时注掉 -- 杨俊明 + + private final HTTPTransportFactory transportFactory = new HTTPTransportFactory(); + private HttpBinder httpBinder; - + public WebServiceProtocol() { super(Fault.class); bus.setExtension(new ServletDestinationFactory(), HttpDestinationFactory.class); @@ -80,21 +80,21 @@ public int getDefaultPort() { private class WebServiceHandler implements HttpHandler { - private volatile ServletController servletController; + private volatile ServletController servletController; public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - if (servletController == null) { - HttpServlet httpServlet = DispatcherServlet.getInstance(); - if (httpServlet == null) { - response.sendError(500, "No such DispatcherServlet instance."); - return; - } - synchronized (this) { - if (servletController == null) { - servletController = new ServletController(transportFactory.getRegistry(), httpServlet.getServletConfig(), httpServlet); - } - } - } + if (servletController == null) { + HttpServlet httpServlet = DispatcherServlet.getInstance(); + if (httpServlet == null) { + response.sendError(500, "No such DispatcherServlet instance."); + return; + } + synchronized (this) { + if (servletController == null) { + servletController = new ServletController(transportFactory.getRegistry(), httpServlet.getServletConfig(), httpServlet); + } + } + } RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); servletController.invoke(request, response); } @@ -102,7 +102,7 @@ public void handle(HttpServletRequest request, HttpServletResponse response) thr } protected Runnable doExport(T impl, Class type, URL url) throws RpcException { - String addr = url.getIp() + ":" + url.getPort(); + String addr = url.getIp() + ":" + url.getPort(); HttpServer httpServer = serverMap.get(addr); if (httpServer == null) { httpServer = httpBinder.bind(url, new WebServiceHandler()); @@ -110,36 +110,39 @@ protected Runnable doExport(T impl, Class type, URL url) throws RpcExcept } final ServerFactoryBean serverFactoryBean = new ServerFactoryBean(); serverFactoryBean.setAddress(url.getAbsolutePath()); - serverFactoryBean.setServiceClass(type); - serverFactoryBean.setServiceBean(impl); - serverFactoryBean.setBus(bus); + serverFactoryBean.setServiceClass(type); + serverFactoryBean.setServiceBean(impl); + serverFactoryBean.setBus(bus); serverFactoryBean.setDestinationFactory(transportFactory); - serverFactoryBean.create(); + serverFactoryBean.create(); return new Runnable() { public void run() { - serverFactoryBean.destroy(); + //serverFactoryBean.destroy(); //升级到cxf 3后编译失败,暂时注掉 - 杨俊明 + if (serverFactoryBean.getServer() != null) { + serverFactoryBean.getServer().destroy(); + } } }; } @SuppressWarnings("unchecked") protected T doRefer(final Class serviceType, final URL url) throws RpcException { - ClientProxyFactoryBean proxyFactoryBean = new ClientProxyFactoryBean(); - proxyFactoryBean.setAddress(url.setProtocol("http").toIdentityString()); - proxyFactoryBean.setServiceClass(serviceType); - proxyFactoryBean.setBus(bus); - T ref = (T) proxyFactoryBean.create(); - Client proxy = ClientProxy.getClient(ref); - HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); - HTTPClientPolicy policy = new HTTPClientPolicy(); - policy.setConnectionTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); - policy.setReceiveTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); - conduit.setClient(policy); + ClientProxyFactoryBean proxyFactoryBean = new ClientProxyFactoryBean(); + proxyFactoryBean.setAddress(url.setProtocol("http").toIdentityString()); + proxyFactoryBean.setServiceClass(serviceType); + proxyFactoryBean.setBus(bus); + T ref = (T) proxyFactoryBean.create(); + Client proxy = ClientProxy.getClient(ref); + HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); + HTTPClientPolicy policy = new HTTPClientPolicy(); + policy.setConnectionTimeout(url.getParameter(Constants.CONNECT_TIMEOUT_KEY, Constants.DEFAULT_CONNECT_TIMEOUT)); + policy.setReceiveTimeout(url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT)); + conduit.setClient(policy); return ref; } protected int getErrorCode(Throwable e) { - if (e instanceof Fault) { + if (e instanceof Fault) { e = e.getCause(); } if (e instanceof SocketTimeoutException) { diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 4dd07112ac0..b0822ba4671 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -14,31 +14,33 @@ - limitations under the License. --> - 4.0.0 - - com.alibaba - dubbo-parent - 2.8.4 - - dubbo-rpc - pom - ${project.artifactId} - The rpc module of dubbo project - - true - - - dubbo-rpc-api - dubbo-rpc-default - dubbo-rpc-injvm - dubbo-rpc-rmi - dubbo-rpc-hessian - dubbo-rpc-http - dubbo-rpc-webservice - dubbo-rpc-thrift - dubbo-rpc-memcached - dubbo-rpc-redis - dubbo-rpc-rest - + 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.5-SNAPSHOT + + dubbo-rpc + pom + ${project.artifactId} + The rpc module of dubbo project + + true + + + dubbo-rpc-api + dubbo-rpc-avro + dubbo-rpc-default + dubbo-rpc-injvm + dubbo-rpc-rmi + dubbo-rpc-hessian + dubbo-rpc-http + dubbo-rpc-webservice + dubbo-rpc-thrift2 + dubbo-rpc-grpc + dubbo-rpc-memcached + dubbo-rpc-redis + dubbo-rpc-rest + diff --git a/dubbo-simple/dubbo-monitor-simple/pom.xml b/dubbo-simple/dubbo-monitor-simple/pom.xml index 4068dfc52fa..096fff4d63b 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.5-SNAPSHOT dubbo-monitor-simple jar @@ -75,7 +75,7 @@ zookeeper - com.github.sgroschupf + com.alibaba zkclient diff --git a/dubbo-simple/dubbo-monitor-simple/src/main/assembly/conf/dubbo.properties b/dubbo-simple/dubbo-monitor-simple/src/main/assembly/conf/dubbo.properties index 5aa89460f23..ac2b8196a20 100644 --- a/dubbo-simple/dubbo-monitor-simple/src/main/assembly/conf/dubbo.properties +++ b/dubbo-simple/dubbo-monitor-simple/src/main/assembly/conf/dubbo.properties @@ -16,8 +16,8 @@ dubbo.container=log4j,spring,registry,jetty dubbo.application.name=simple-monitor dubbo.application.owner= -dubbo.registry.address=multicast://224.5.6.7:1234 -#dubbo.registry.address=zookeeper://127.0.0.1:2181 +#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.protocol.port=7070 diff --git a/dubbo-simple/dubbo-registry-simple/pom.xml b/dubbo-simple/dubbo-registry-simple/pom.xml index 6c1912bee66..63e9aeeafe0 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.5-SNAPSHOT dubbo-registry-simple jar diff --git a/dubbo-simple/pom.xml b/dubbo-simple/pom.xml index 5bb270f0179..cff6069f41a 100644 --- a/dubbo-simple/pom.xml +++ b/dubbo-simple/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 2.8.5-SNAPSHOT dubbo-simple pom diff --git a/dubbo-test/dubbo-test-benchmark-api/pom.xml b/dubbo-test/dubbo-test-benchmark-api/pom.xml deleted file mode 100644 index 79f9a30036c..00000000000 --- a/dubbo-test/dubbo-test-benchmark-api/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - 4.0.0 - - com.alibaba - dubbo-test - 2.8.4 - - 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 - javax.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 deleted file mode 100644 index 0073d0ba000..00000000000 --- a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidRequest.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * 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 deleted file mode 100644 index b38f1507f48..00000000000 --- a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidResponse.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 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 deleted file mode 100644 index c99b00e4393..00000000000 --- a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Device.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * 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 deleted file mode 100644 index 1d735918ada..00000000000 --- a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/EchoService.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * 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 deleted file mode 100644 index 2733c494e22..00000000000 --- a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Geo.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 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 deleted file mode 100644 index 9d7ac8f1331..00000000000 --- a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Impression.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 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 deleted file mode 100644 index 8132e267c5c..00000000000 --- a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/SeatBid.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 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 deleted file mode 100644 index ba7aa3fcb2a..00000000000 --- a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/SerializationOptimizerImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 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 deleted file mode 100644 index 077ffdda5d9..00000000000 --- a/dubbo-test/dubbo-test-benchmark-api/src/main/java/com/alibaba/dubbo/rpc/benchmark/Text.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * 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 deleted file mode 100644 index 09aded71106..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/pom.xml +++ /dev/null @@ -1,200 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-test - 2.8.4 - - 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 - - - io.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 - - - 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 deleted file mode 100644 index 0617798a708..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/assembly/assembly.xml +++ /dev/null @@ -1,23 +0,0 @@ - - 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 deleted file mode 100644 index 54b4406fa89..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/cli/run.bat +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 7389f902f9c..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/cli/run.sh +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 63dbf9783e4..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java +++ /dev/null @@ -1,251 +0,0 @@ -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 deleted file mode 100644 index 9df55a6799e..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractClientRunnable.java +++ /dev/null @@ -1,176 +0,0 @@ -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 deleted file mode 100644 index d136543f0ce..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/BidClientRunnable.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 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 deleted file mode 100644 index 6710ecb0272..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/ClientRunnable.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * 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 deleted file mode 100644 index 5972e757752..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcBenchmarkClient.java +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 29a497ea328..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/ServiceFactory.java +++ /dev/null @@ -1,118 +0,0 @@ -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 deleted file mode 100644 index 923e885825d..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/main/java/com/alibaba/dubbo/rpc/benchmark/TextClientRunnable.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * 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 deleted file mode 100644 index be0c538174c..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/main/resources/META-INF/cxf/org.apache.cxf.Logger +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index f28a602c692..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/main/resources/dubbo.properties +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index cd275123fd4..00000000000 --- a/dubbo-test/dubbo-test-benchmark-client/src/main/resources/log4j.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ 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 deleted file mode 100644 index 9a97c7df23f..00000000000 --- a/dubbo-test/dubbo-test-benchmark-server/pom.xml +++ /dev/null @@ -1,195 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-test - 2.8.4 - - 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 - - - io.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 - - - 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 deleted file mode 100644 index 674a2dc869a..00000000000 --- a/dubbo-test/dubbo-test-benchmark-server/src/assembly/assembly.xml +++ /dev/null @@ -1,23 +0,0 @@ - - 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 deleted file mode 100644 index 0d4c7b031f1..00000000000 --- a/dubbo-test/dubbo-test-benchmark-server/src/cli/run.bat +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 30d00abd10f..00000000000 --- a/dubbo-test/dubbo-test-benchmark-server/src/cli/run.sh +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 5ae5810d69b..00000000000 --- a/dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/EchoServiceImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * 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/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 deleted file mode 100644 index be0c538174c..00000000000 --- a/dubbo-test/dubbo-test-benchmark-server/src/main/resources/META-INF/cxf/org.apache.cxf.Logger +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index ada9b4d5cd3..00000000000 --- a/dubbo-test/dubbo-test-benchmark-server/src/main/resources/META-INF/spring/dubbo-provider.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ 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 deleted file mode 100644 index cd275123fd4..00000000000 --- a/dubbo-test/dubbo-test-benchmark-server/src/main/resources/log4j.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - \ 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 deleted file mode 100644 index 2a2f3a6cead..00000000000 --- a/dubbo-test/dubbo-test-benchmark-server/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - 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 diff --git a/dubbo-test/dubbo-test-benchmark/pom.xml b/dubbo-test/dubbo-test-benchmark/pom.xml deleted file mode 100644 index 2593c9e5054..00000000000 --- a/dubbo-test/dubbo-test-benchmark/pom.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-test - 2.8.4 - - dubbo-test-benchmark - jar - ${project.artifactId} - The performance benchmark kit test module of dubbo project - - true - - - - com.alibaba - dubbo - ${project.parent.version} - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - package-exclude-resources - - jar - - package - - - dubbo.properties - ProviderSample.xml - - assemble - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - 1.6 - 1.6 - UTF-8 - - - - maven-assembly-plugin - 2.2.1 - - - assembly - package - - single - - - - ${basedir}/src/assembly/release.xml - - false - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark/src/assembly/dev.xml b/dubbo-test/dubbo-test-benchmark/src/assembly/dev.xml deleted file mode 100644 index 24adf50b9d1..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/assembly/dev.xml +++ /dev/null @@ -1,24 +0,0 @@ - - dist - - tar.gz - - false - - - src/main/resources - dubbo.benchmark - 0755 - - - - - dubbo.benchmark/lib - false - true - - *:sources - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark/src/assembly/release.xml b/dubbo-test/dubbo-test-benchmark/src/assembly/release.xml deleted file mode 100644 index 24adf50b9d1..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/assembly/release.xml +++ /dev/null @@ -1,24 +0,0 @@ - - dist - - tar.gz - - false - - - src/main/resources - dubbo.benchmark - 0755 - - - - - dubbo.benchmark/lib - false - true - - *:sources - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java deleted file mode 100644 index 6ac6d95b3f2..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkClient.java +++ /dev/null @@ -1,247 +0,0 @@ -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")); - - // 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(",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(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 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/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkServer.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkServer.java deleted file mode 100644 index 3fade03740b..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractBenchmarkServer.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.alibaba.dubbo.rpc.benchmark; - -/** - * nfs-rpc Apache License http://code.google.com/p/nfs-rpc (c) 2011 - */ -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ExchangeChannel; -import com.alibaba.dubbo.remoting.exchange.Exchangers; -import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; - -/** - * Abstract benchmark server Usage: BenchmarkServer listenPort maxThreads responseSize - * - * @author bluedavy - */ -public abstract class AbstractBenchmarkServer { - - private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - public void run(String[] args) throws Exception { - if (args == null || args.length != 5) { - throw new IllegalArgumentException( - "must give three args: listenPort | maxThreads | responseSize | transporter | serialization"); - } - int listenPort = Integer.parseInt(args[0]); - int maxThreads = Integer.parseInt(args[1]); - final int responseSize = Integer.parseInt(args[2]); - String transporter = args[3]; - String serialization = args[4]; - System.out.println(dateFormat.format(new Date()) + " ready to start server,listenPort is: " + listenPort - + ",maxThreads is:" + maxThreads + ",responseSize is:" + responseSize - + " bytes,transporter is:" + transporter + ",serialization is:" + serialization); - StringBuilder url = new StringBuilder(); - url.append("exchange://0.0.0.0:"); - url.append(listenPort); - url.append("?transporter="); - url.append(transporter); - url.append("&serialization="); - url.append(serialization); - url.append("&threads="); - url.append(maxThreads); - Exchangers.bind(url.toString(), new ExchangeHandlerAdapter() { - - public Object reply(ExchangeChannel channel, Object message) throws RemotingException { - return new ResponseObject(responseSize); // 发送响应 - } - }); - } -} diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractClientRunnable.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractClientRunnable.java deleted file mode 100644 index 725ae9b9fc4..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/AbstractClientRunnable.java +++ /dev/null @@ -1,173 +0,0 @@ -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 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.setTargetIP(targetIP); - serviceFactory.setClientNums(clientNums); - serviceFactory.setTargetPort(targetPort); - serviceFactory.setConnectTimeout(rpcTimeout); - 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) { - 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/src/main/java/com/alibaba/dubbo/rpc/benchmark/BenchmarkClient.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/BenchmarkClient.java deleted file mode 100644 index 68102e39b9b..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/BenchmarkClient.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.alibaba.dubbo.rpc.benchmark; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; - -public class BenchmarkClient extends AbstractBenchmarkClient { - - @Override - public ClientRunnable getClientRunnable(String targetIP, int targetPort, int clientNums, int rpcTimeout, - CyclicBarrier barrier, - CountDownLatch latch, long endTime, long startTime) { - return new SimpleProcessorBenchmarkClientRunnable(targetIP, targetPort, clientNums, rpcTimeout, - barrier, latch, startTime, endTime); - } - - public static void main(String[] args) throws Exception { - new BenchmarkClient().run(args); - } -} diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/BenchmarkServer.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/BenchmarkServer.java deleted file mode 100644 index cf974b5d312..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/BenchmarkServer.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.alibaba.dubbo.rpc.benchmark; - -public class BenchmarkServer extends AbstractBenchmarkServer { - - public static void main(String[] args) throws Exception { - new BenchmarkServer().run(args); - synchronized (BenchmarkServer.class) { - BenchmarkServer.class.wait(); - } - } -} diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/ClientRunnable.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/ClientRunnable.java deleted file mode 100644 index ba48cfc4956..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/ClientRunnable.java +++ /dev/null @@ -1,20 +0,0 @@ -/** - * 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/src/main/java/com/alibaba/dubbo/rpc/benchmark/DemoService.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/DemoService.java deleted file mode 100644 index 4c477233851..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/DemoService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.alibaba.dubbo.rpc.benchmark; - - -/** - * TODO Comment of HelloService - * - * @author tony.chenl - */ -public interface DemoService { - public Object sendRequest(Object requestObject); -} diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/DemoServiceImpl.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/DemoServiceImpl.java deleted file mode 100644 index dbeee75a765..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/DemoServiceImpl.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.alibaba.dubbo.rpc.benchmark; - - -/** - * TODO Comment of HelloService - * - * @author tony.chenl - */ -public class DemoServiceImpl implements DemoService{ - ResponseObject responseObject = new ResponseObject(100); - - public Object sendRequest(Object request) { - return request; - } -} diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/ExchangeClientFactory.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/ExchangeClientFactory.java deleted file mode 100644 index 81af8bb3689..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/ExchangeClientFactory.java +++ /dev/null @@ -1,101 +0,0 @@ -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.Random; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.FutureTask; - -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.Exchangers; - -/** - * Abstract ExchangeClient Factory,create custom nums ExchangeClient - * - * @author bluedavy - */ -public class ExchangeClientFactory { - - // Cache ExchangeClient - private static ConcurrentHashMap>> clients = new ConcurrentHashMap>>(); - - public ExchangeClient get(final String targetIP, final int targetPort, final int connectTimeout) throws Exception { - return get(targetIP, targetPort, connectTimeout, 1); - } - - public ExchangeClient get(final String targetIP, final int targetPort, final int connectTimeout, - final int clientNums) throws Exception { - String key = targetIP + ":" + targetPort; - if (clients.containsKey(key)) { - if (clientNums == 1) { - return clients.get(key).get().get(0); - } else { - Random random = new Random(); - return clients.get(key).get().get(random.nextInt(clientNums)); - } - } else { - FutureTask> task = new FutureTask>( - new Callable>() { - - public List call() - throws Exception { - List clients = new ArrayList( - clientNums); - for (int i = 0; i < clientNums; i++) { - clients.add(createClient(targetIP, - targetPort, - connectTimeout)); - } - return clients; - } - }); - FutureTask> currentTask = clients.putIfAbsent(key, task); - if (currentTask == null) { - task.run(); - } else { - task = currentTask; - } - if (clientNums == 1) return task.get().get(0); - else { - Random random = new Random(); - return task.get().get(random.nextInt(clientNums)); - } - } - } - - public void removeClient(String key, ExchangeClient ExchangeClient) { - try { - // TODO: Fix It - clients.remove(key); - // clients.get(key).get().remove(ExchangeClient); - // clients.get(key) - // .get() - // .add(createClient(ExchangeClient.getServerIP(), - // ExchangeClient.getServerPort(), ExchangeClient.getConnectTimeout(), - // key)); - } catch (Exception e) { - // IGNORE - } - } - - public static ExchangeClientFactory getInstance() { - throw new UnsupportedOperationException("should be implemented by true class"); - } - - protected ExchangeClient createClient(String targetIP, int targetPort, int connectTimeout) throws Exception { - StringBuilder url = new StringBuilder(); - url.append("exchange://"); - url.append(targetIP); - url.append(":"); - url.append(targetPort); - url.append("?"); - url.append("timeout="); - url.append(connectTimeout); - return Exchangers.connect(url.toString()); - } - -} diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/RequestObject.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/RequestObject.java deleted file mode 100644 index c7c498eca1f..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/RequestObject.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.alibaba.dubbo.rpc.benchmark; - -/** - * nfs-rpc - * Apache License - * - * http://code.google.com/p/nfs-rpc (c) 2011 - */ -import java.io.Serializable; - -/** - * Just for RPC Benchmark Test,request object - * - * @author bluedavy - */ -public class RequestObject implements Serializable { - - private static final long serialVersionUID = 1L; - - public RequestObject(){ - } - - private byte[] bytes = null; - - public void setBytes(byte[] bytes) { - this.bytes = bytes; - } - - public RequestObject(int size){ - bytes = new byte[size]; - } - - public byte[] getBytes() { - return bytes; - } - -} diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/ResponseObject.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/ResponseObject.java deleted file mode 100644 index c8ede56a7df..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/ResponseObject.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.alibaba.dubbo.rpc.benchmark; -/** - * nfs-rpc - * Apache License - * - * http://code.google.com/p/nfs-rpc (c) 2011 - */ -import java.io.Serializable; -/** - * Just for RPC Benchmark Test,response object - * - * @author bluedavy - */ -public class ResponseObject implements Serializable { - - private static final long serialVersionUID = 1L; - - private byte[] bytes = null; - - public ResponseObject(int size){ - bytes = new byte[size]; - } - - public byte[] getBytes() { - return bytes; - } - - -} diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcBenchmarkClient.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcBenchmarkClient.java deleted file mode 100644 index 4dcb35e0de2..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcBenchmarkClient.java +++ /dev/null @@ -1,24 +0,0 @@ -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 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, int.class, int.class, int.class, CyclicBarrier.class, - CountDownLatch.class, long.class, long.class }; - Object[] parameters = new Object[] { 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/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcBenchmarkServer.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcBenchmarkServer.java deleted file mode 100644 index cfe846b4712..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcBenchmarkServer.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.alibaba.dubbo.rpc.benchmark; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class RpcBenchmarkServer extends AbstractBenchmarkServer { - - public static void main(String[] args) throws Exception { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("ProviderSample.xml"); - ctx.start(); - synchronized (RpcBenchmarkServer.class) { - try { - RpcBenchmarkServer.class.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } -} diff --git a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcClient.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcClient.java deleted file mode 100644 index 3b73333dea4..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/RpcClient.java +++ /dev/null @@ -1,65 +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.rpc.benchmark; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; - -/** - * RpcClient.java - * @author tony.chenl - */ -public class RpcClient extends AbstractClientRunnable{ - private static String message = null; - private static int length = 100; - - static{ - length = Integer.valueOf(System.getProperty("message.length","1000")); - StringBuilder sb = new StringBuilder(); - for(int i=0;i { - - String targetIP = null; - - int targetPort = 0; - - int connectTimeout = 0; - - int clientNums = 0; - - 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; - } - - // 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); - services.put(key, service); - return (T) services.get(key); - } - } - - protected T createClient(Class cls, String targetIP, int targetPort, int connectTimeout,int clientNums){ - ReferenceConfig referenceConfig = new ReferenceConfig(); - referenceConfig.setInterface(cls); - StringBuilder url = new StringBuilder(); - url.append("dubbo://"); - url.append(targetIP); - url.append(":"); - url.append(targetPort); - url.append("/"); - url.append(cls.getName()); - 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/src/main/java/com/alibaba/dubbo/rpc/benchmark/SimpleProcessorBenchmarkClientRunnable.java b/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/SimpleProcessorBenchmarkClientRunnable.java deleted file mode 100644 index f663a6af097..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/java/com/alibaba/dubbo/rpc/benchmark/SimpleProcessorBenchmarkClientRunnable.java +++ /dev/null @@ -1,184 +0,0 @@ -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 class SimpleProcessorBenchmarkClientRunnable implements ClientRunnable { - - private static final Log LOGGER = LogFactory.getLog(SimpleProcessorBenchmarkClientRunnable.class); - - private int requestSize; - - private CyclicBarrier barrier; - - private CountDownLatch latch; - - private long endTime; - - private boolean running = true; - - private ExchangeClientFactory clientFactory = new ExchangeClientFactory(); - - private String targetIP; - - private int targetPort; - - private int clientNums; - - private int rpcTimeout; - - // 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; - - public SimpleProcessorBenchmarkClientRunnable(String targetIP, int targetPort, int clientNums, int rpcTimeout, - CyclicBarrier barrier, CountDownLatch latch, long startTime, - long endTime){ - - this.targetIP = targetIP; - this.targetPort = targetPort; - this.clientNums = clientNums; - this.rpcTimeout = rpcTimeout; - this.barrier = barrier; - this.latch = latch; - this.startTime = startTime; - this.endTime = endTime; - maxRange = (Integer.parseInt(String.valueOf((endTime - startTime))) / 1000) + 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) { - Object requestObject = new RequestObject(requestSize); - long beginTime = System.nanoTime(); - if (beginTime >= endTime) { - running = false; - break; - } - try { - Object response = null; - response = clientFactory.get(targetIP, targetPort, rpcTimeout, clientNums).request(requestObject).get(); - long currentTime = System.nanoTime(); - if (beginTime <= startTime) { - continue; - } - long consumeTime = currentTime - beginTime; - sumResponseTimeSpread(consumeTime); - int range = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000; - if (range >= maxRange) { - System.err.println("benchmark range exceeds maxRange,range is: " + range + ",maxRange is: " - + maxRange); - continue; - } - if (((ResponseObject) response).getBytes() != null) { - tps[range] = tps[range] + 1; - responseTimes[range] = responseTimes[range] + consumeTime; - } else { - LOGGER.error("server return response is null"); - errorTPS[range] = errorTPS[range] + 1; - errorResponseTimes[range] = errorResponseTimes[range] + consumeTime; - } - } catch (Exception e) { - LOGGER.error("client.invokeSync error", e); - long currentTime = System.nanoTime(); - if (beginTime <= startTime) { - continue; - } - long consumeTime = currentTime - beginTime; - sumResponseTimeSpread(consumeTime); - int range = Integer.parseInt(String.valueOf(beginTime - startTime)) / 1000; - 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 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 / 1000; - 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/src/main/resources/ProviderSample.xml b/dubbo-test/dubbo-test-benchmark/src/main/resources/ProviderSample.xml deleted file mode 100644 index 4a7a3f9828e..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/resources/ProviderSample.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - classpath:dubbo-default.properties - classpath:dubbo.properties - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark/src/main/resources/ReadMe.txt b/dubbo-test/dubbo-test-benchmark/src/main/resources/ReadMe.txt deleted file mode 100644 index 5d695e4a804..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/resources/ReadMe.txt +++ /dev/null @@ -1,13 +0,0 @@ -一、新建一个benchmark工程,如demo.benchmark -二、导入自己服务的接口api包和dubbo.benchmark.jar(解压dubbo.benchmark.tar.gz,在lib目录下) -三、新建一个类,实现AbstractClientRunnable - a、实现父类的构造函数 - b、实现invoke方法,通过serviceFactory创建本地接口代理,并实现自己的业务逻辑,如下 - public Object invoke(ServiceFactory serviceFactory) { - DemoService demoService = (DemoService) serviceFactory.get(DemoService.class); - return demoService.sendRequest("hello"); - } -四、将自己的benchmark工程打成jar包,如demo.benchmark.jar -五、将demo.benchmark.jar放到dubbo.benchmark/lib目录下 -六、配置dubbo.properties -七、运行run.bat(windows)或run.sh(linux) \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark/src/main/resources/dubbo.properties b/dubbo-test/dubbo-test-benchmark/src/main/resources/dubbo.properties deleted file mode 100644 index 84a779fc764..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/resources/dubbo.properties +++ /dev/null @@ -1,14 +0,0 @@ -#\u5b9e\u73b0\u7684benchmark runnable\u7c7b\u540d -classname= -#\u63d0\u4f9b\u8005ip -serverip= -#\u63d0\u4f9b\u8005\u7aef\u53e3 -serverport= -#\u5ba2\u6237\u7aef\u5e76\u53d1\u6570 -concurrents= -#\u5ba2\u6237\u7aef\u8d85\u65f6\u65f6\u95f4\uff0c\u5355\u4f4d\u6beb\u79d2 -timeout= -#benchmark\u8fd0\u884c\u65f6\u95f4,\u5355\u4f4d\u79d2 -runtime= -#\u8fde\u63a5\u6570 -connectionnums= \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark/src/main/resources/run.bat b/dubbo-test/dubbo-test-benchmark/src/main/resources/run.bat deleted file mode 100644 index dad18798808..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/resources/run.bat +++ /dev/null @@ -1 +0,0 @@ -java -Xms512m -Xmx512m -Xmn128m -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log -Dwrite.statistics=true -Djava.ext.dirs="./lib" "com.alibaba.dubbo.rpc.benchmark.RpcBenchmarkClient" > "benchmark.log" \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark/src/main/resources/run.sh b/dubbo-test/dubbo-test-benchmark/src/main/resources/run.sh deleted file mode 100644 index 05f52bbaf60..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/main/resources/run.sh +++ /dev/null @@ -1 +0,0 @@ -java -Xms512m -Xmx512m -Xmn128m -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log -Dwrite.statistics=true -Djava.ext.dirs="./lib" "com.alibaba.dubbo.rpc.benchmark.RpcBenchmarkClient" > "benchmark.log" 2>&1 & \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark/src/test/backup/BenchmarkRunner.java b/dubbo-test/dubbo-test-benchmark/src/test/backup/BenchmarkRunner.java deleted file mode 100644 index c28c5bdadf3..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/test/backup/BenchmarkRunner.java +++ /dev/null @@ -1,1022 +0,0 @@ -package com.dubbo.serialize.benchmark; - -import java.io.*; -import java.net.URLEncoder; -import java.util.*; -import java.util.regex.Pattern; -import java.util.zip.DeflaterOutputStream; - -import serializers.jackson.*; -import serializers.json.JsonGsonDatabind; -import serializers.json.JsonArgoTree; -import serializers.json.FastJSONDatabind; -import serializers.json.FlexjsonDatabind; -import serializers.json.JsonGsonManual; -import serializers.json.JsonGsonTree; -import serializers.json.JsonDotOrgManualTree; -import serializers.json.JsonLibJsonDatabind; -import serializers.json.JsonPathDeserializerOnly; -import serializers.json.JsonSimpleManualTree; -import serializers.json.JsonSimpleWithContentHandler; -import serializers.json.JsonSmartManualTree; -import serializers.json.JsonTwoLattes; -import serializers.json.JsonijJpath; -import serializers.json.JsonijManualTree; -import serializers.json.JsonSvensonDatabind; -import serializers.protostuff.Protostuff; -import serializers.protostuff.ProtostuffJson; -import serializers.protostuff.ProtostuffSmile; -import serializers.xml.XmlJavolution; -import serializers.xml.XmlStax; -import serializers.xml.XmlXStream; - -public class BenchmarkRunner -{ - public final static int DEFAULT_ITERATIONS = 2000; - public final static int DEFAULT_TRIALS = 20; - - /** - * Number of milliseconds to warm up for each operation type for each serializer. Let's - * start with 3 seconds. - */ - final static long DEFAULT_WARMUP_MSECS = 3000; - - // These tests aren't included by default. Use the "-hidden" flag to enable them. - private static final HashSet HIDDEN = new HashSet(); - static { - // CKS is not included because it's not really publicly released. - HIDDEN.add("cks"); - HIDDEN.add("cks-text"); - } - - private static final String ERROR_DIVIDER = "-------------------------------------------------------------------"; - - public static void main(String[] args) - { - // -------------------------------------------------- - // Parse command-line options. - - Boolean filterIsInclude = null; - Set filterStrings = null; - Integer iterations = null; - Integer trials = null; - Long warmupTime = null; - boolean printChart = false; - boolean prewarm = false; - String dataFileName = null; - boolean enableHidden = false; - - Set optionsSeen = new HashSet(); - - for (String arg : args) { - String remainder; - if (arg.startsWith("--")) { - remainder = arg.substring(2); - } - else if (arg.startsWith("-")) { - remainder = arg.substring(1); - } - else if (dataFileName == null) { - dataFileName = arg; - continue; - } - else { - System.err.println("Expecting only one non-option argument ( = \"" + dataFileName + "\")."); - System.err.println("Found a second one: \"" + arg + "\""); - System.err.println("Use \"-help\" for usage information."); - System.exit(1); return; - } - - String option, value; - int eqPos = remainder.indexOf('='); - if (eqPos >= 0) { - option = remainder.substring(0, eqPos); - value = remainder.substring(eqPos+1); - } else { - option = remainder; - value = null; - } - - if (!optionsSeen.add(option)) { - System.err.println("Repeated option: \"" + arg + "\""); - System.exit(1); return; - } - - if (option.equals("include")) { - if (value == null) { - System.err.println("The \"include\" option requires a value."); - System.exit(1); return; - } - if (filterIsInclude == null) { - filterIsInclude = true; - filterStrings = new HashSet(Arrays.asList(value.split(","))); - } else { - System.err.println("Can't use 'include' and 'exclude' options at the same time."); - System.exit(1); return; - } - } - else if (option.equals("exclude")) { - if (value == null) { - System.err.println("The \"exclude\" option requires a value."); - System.exit(1); return; - } - if (filterIsInclude == null) { - filterIsInclude = false; - filterStrings = new HashSet(Arrays.asList(value.split(","))); - } else { - System.err.println("Can't use 'include' and 'exclude' options at the same time."); - System.exit(1); return; - } - } - else if (option.equals("iterations")) { - if (value == null) { - System.err.println("The \"iterations\" option requires a value."); - System.exit(1); return; - } - assert iterations == null; - try { - iterations = Integer.parseInt(value); - } catch (NumberFormatException ex) { - System.err.println("Invalid value for \"iterations\" option: \"" + value + "\""); - System.exit(1); return; - } - if (iterations < 1) { - System.err.println("Invalid value for \"iterations\" option: \"" + value + "\""); - System.exit(1); return; - } - } - else if (option.equals("trials")) { - if (value == null) { - System.err.println("The \"trials\" option requires a value."); - System.exit(1); return; - } - assert trials == null; - try { - trials = Integer.parseInt(value); - } catch (NumberFormatException ex) { - System.err.println("Invalid value for \"trials\" option: \"" + value + "\""); - System.exit(1); return; - } - if (trials < 1) { - System.err.println("Invalid value for \"trials\" option: \"" + value + "\""); - System.exit(1); return; - } - } - else if (option.equals("warmup-time")) { - if (value == null) { - System.err.println("The \"warmup-time\" option requires a value."); - System.exit(1); return; - } - assert warmupTime == null; - try { - warmupTime = Long.parseLong(value); - } catch (NumberFormatException ex) { - System.err.println("Invalid value for \"warmup-time\" option: \"" + value + "\""); - System.exit(1); return; - } - if (warmupTime < 0) { - System.err.println("Invalid value for \"warmup-time\" option: \"" + value + "\""); - System.exit(1); return; - } - } - else if (option.equals("pre-warmup")) { - if (value != null) { - System.err.println("The \"pre-warmup\" option does not take a value: \"" + arg + "\""); - System.exit(1); return; - } - assert !prewarm; - prewarm = true; - } - else if (option.equals("chart")) { - if (value != null) { - System.err.println("The \"chart\" option does not take a value: \"" + arg + "\""); - System.exit(1); return; - } - assert !printChart; - printChart = true; - } - else if (option.equals("hidden")) { - if (value != null) { - System.err.println("The \"hidden\" option does not take a value: \"" + arg + "\""); - System.exit(1); return; - } - assert !enableHidden; - enableHidden = true; - } - else if (option.equals("help")) { - if (value != null) { - System.err.println("The \"help\" option does not take a value: \"" + arg + "\""); - System.exit(1); return; - } - if (args.length != 1) { - System.err.println("The \"help\" option cannot be combined with any other option."); - System.exit(1); return; - } - - System.out.println(); - System.out.println("Usage: run [options] "); - System.out.println(); - System.out.println("Options:"); - System.out.println(" -iterations=n [default=" + DEFAULT_ITERATIONS + "]"); - System.out.println(" -trials=n [default=" + DEFAULT_TRIALS + "]"); - System.out.println(" -warmup-time=millis [default=" + DEFAULT_WARMUP_MSECS + "]"); - System.out.println(" -pre-warmup (warm all serializers before the first measurement)"); - System.out.println(" -chart (generate a Google Chart URL for the results)"); - System.out.println(" -include=impl1,impl2,impl3,..."); - System.out.println(" -exclude=impl1,impl2,impl3,..."); - System.out.println(" -hidden (enable \"hidden\" serializers)"); - System.out.println(" -help"); - System.out.println(); - System.out.println("Example: run -chart -include=protobuf,thrift data/media.1.cks"); - System.out.println(); - System.exit(0); return; - } - else { - System.err.println("Unknown option: \"" + arg + "\""); - System.err.println("Use \"-help\" for usage information."); - System.exit(1); return; - } - } - - if (iterations == null) iterations = DEFAULT_ITERATIONS; - if (trials == null) trials = DEFAULT_TRIALS; - if (warmupTime == null) warmupTime = DEFAULT_WARMUP_MSECS; - - if (dataFileName == null) { - System.err.println("Missing argument."); - System.err.println("Use \"-help\" for usage information."); - System.exit(1); return; - } - - // -------------------------------------------------- - // Load serializers. - - TestGroups groups = new TestGroups(); - - // Binary Formats; language-specific ones - JavaBuiltIn.register(groups); - JavaManual.register(groups); - Scala.register(groups); - // hessian and kryo are Java object serializations - Hessian.register(groups); - Dubbo.register(groups); - Kryo.register(groups); - Wobly.register(groups); - - // Binary formats, generic: protobuf, thrift, avro, kryo, CKS, msgpack - Protobuf.register(groups); - ActiveMQProtobuf.register(groups); - Protostuff.register(groups); - Thrift.register(groups); - AvroSpecific.register(groups); - AvroGeneric.register(groups); - CksBinary.register(groups); - MsgPack.register(groups); - - // JSON - JacksonJsonManual.register(groups); - JacksonJsonTree.register(groups); - JacksonJsonTreeWithStrings.register(groups); - JacksonJsonDatabind.register(groups); - JacksonJsonDatabindWithStrings.register(groups); - JsonTwoLattes.register(groups); - ProtostuffJson.register(groups); - ProtobufJson.register(groups); - JsonGsonManual.register(groups); - JsonGsonTree.register(groups); - JsonGsonDatabind.register(groups); - JsonSvensonDatabind.register(groups); - FlexjsonDatabind.register(groups); - JsonLibJsonDatabind.register(groups); - FastJSONDatabind.register(groups); - JsonSimpleWithContentHandler.register(groups); - JsonSimpleManualTree.register(groups); - JsonSmartManualTree.register(groups); - JsonDotOrgManualTree.register(groups); - JsonijJpath.register(groups); - JsonijManualTree.register(groups); - JsonArgoTree.register(groups); - JsonPathDeserializerOnly.register(groups); - // Then JSON-like - // CKS text is textual JSON-like format - CksText.register(groups); - // then binary variants - // BSON is binary JSON-like format - JacksonBsonManual.register(groups); - JacksonBsonDatabind.register(groups); - MongoDB.register(groups); - // Smile is 1-to-1 binary representation of JSON - JacksonSmileManual.register(groups); - JacksonSmileDatabind.register(groups); - ProtostuffSmile.register(groups); - - // XML-based formats. - XmlStax.register(groups); - XmlXStream.register(groups); - JacksonXmlDatabind.register(groups); - XmlJavolution.register(groups); - - // -------------------------------------------------- - // Load data value. - - Object dataValue; - TestGroup group; - { - File dataFile = new File(dataFileName); - if (!dataFile.exists()) { - System.out.println("Couldn't find data file \"" + dataFile.getPath() + "\""); - System.exit(1); return; - } - - String[] parts = dataFile.getName().split("\\."); - if (parts.length < 3) { - System.out.println("Data file \"" + dataFile.getName() + "\" should be of the form \"..\""); - System.exit(1); return; - } - - String dataType = parts[0]; - String extension = parts[parts.length-1]; - - group = groups.groupMap.get(dataType); - if (group == null) { - System.out.println("Data file \"" + dataFileName + "\" can't be loaded."); - System.out.println("Don't know about data type \"" + dataType + "\""); - System.exit(1); return; - } - - TestGroup.Entry loader = group.extensionMap.get(parts[parts.length-1]); - if (loader == null) { - System.out.println("Data file \"" + dataFileName + "\" can't be loaded."); - System.out.println("No deserializer registered for data type \"" + dataType + "\" and file extension \"." + extension + "\""); - System.exit(1); return; - } - - - Object deserialized; - try { - byte[] fileBytes = readFile(new File(dataFileName)); // Load entire file into a byte array. - deserialized = loader.serializer.deserialize(fileBytes); - } - catch (Exception ex) { - System.err.println("Error loading data from file \"" + dataFileName + "\"."); - System.err.println(ex.getMessage()); - System.exit(1); return; - } - - dataValue = loader.transformer.reverse(deserialized); - } - - @SuppressWarnings("unchecked") - TestGroup group_ = (TestGroup) group; - - // -------------------------------------------------- - - Set matched = new HashSet(); - - Iterable> available; - - if (enableHidden) { - // Use all of them. - available = group_.entries; - } else { - // Remove the hidden ones. - ArrayList> unhidden = new ArrayList>(); - for (TestGroup.Entry entry_ : group.entries) { - @SuppressWarnings("unchecked") - TestGroup.Entry entry = (TestGroup.Entry) entry_; - String name = entry.serializer.getName(); - if (!HIDDEN.contains(name)) unhidden.add(entry); - } - available = unhidden; - } - - Iterable> matchingEntries; - if (filterStrings == null) { - matchingEntries = available; - } - else { - ArrayList> al = new ArrayList>(); - matchingEntries = al; - - for (TestGroup.Entry entry_ : available) { - @SuppressWarnings("unchecked") - TestGroup.Entry entry = (TestGroup.Entry) entry_; - - String name = entry.serializer.getName(); - - // See if any of the filters match. - boolean found = false; - for (String s : filterStrings) { - boolean thisOneMatches = match(s, name); - if (thisOneMatches) { - matched.add(s); - found = true; - } - } - - if (found == filterIsInclude) { - al.add(entry); - } - } - - Set unmatched = new HashSet(filterStrings); - unmatched.removeAll(matched); - for (String s : unmatched) { - System.err.println("Warning: there is no implementation name matching the pattern \"" + s + "\""); - - if (!enableHidden) { - for (String hiddenName : HIDDEN) { - if (match(s, hiddenName)) { - System.err.println("(The \"" + hiddenName + "\", serializer is hidden by default."); - System.err.println(" Use the \"-hidden\" option to enable hidden serializers)"); - break; - } - } - } - } - } - - EnumMap> values; - StringWriter errors = new StringWriter(); - PrintWriter errorsPW = new PrintWriter(errors); - try { - values = start(errorsPW, iterations, trials, warmupTime, prewarm, matchingEntries, dataValue); - } - catch (Exception ex) { - ex.printStackTrace(System.err); - System.exit(1); return; - } - - if (printChart) { - printImages(values); - } - - // Print errors after chart. That way you can't miss it. - String errorsString = errors.toString(); - if (errorsString.length() > 0) { - System.out.println(ERROR_DIVIDER); - System.out.println("Errors occurred during benchmarking:"); - System.out.print(errorsString); - System.exit(1); return; - } - } - - private static boolean match(String pattern, String name) - { - StringBuilder regex = new StringBuilder(); - - while (pattern.length() > 0) { - int starPos = pattern.indexOf('*'); - if (starPos < 0) { - regex.append(Pattern.quote(pattern)); - break; - } - else { - String beforeStar = pattern.substring(0, starPos); - String afterStar = pattern.substring(starPos + 1); - - regex.append(Pattern.quote(beforeStar)); - regex.append(".*"); - pattern = afterStar; - } - } - - return Pattern.matches(regex.toString(), name); - } - - // ------------------------------------------------------------------------------------ - - private static byte[] readFile(File file) - throws IOException - { - FileInputStream fin = new FileInputStream(file); - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); - byte[] data = new byte[1024]; - while (true) { - int numBytes = fin.read(data); - if (numBytes < 0) break; - baos.write(data, 0, numBytes); - } - return baos.toByteArray(); - } - finally { - fin.close(); - } - } - - // ------------------------------------------------------------------------------------ - - private static double iterationTime(long delta, int iterations) - { - return (double) delta / (double) (iterations); - } - - private static final TestCase Create = new TestCase() - { - public double run(Transformer transformer, Serializer serializer, J value, int iterations) throws Exception - { - long start = System.nanoTime(); - for (int i = 0; i < iterations; i++) - { - transformer.forward(value); - } - return iterationTime(System.nanoTime() - start, iterations); - } - }; - - private static final TestCase Serialize = new TestCase() - { - public double run(Transformer transformer, Serializer serializer, J value, int iterations) throws Exception - { - long start = System.nanoTime(); - for (int i = 0; i < iterations; i++) - { - Object obj = transformer.forward(value); - serializer.serialize(obj); - } - return iterationTime(System.nanoTime() - start, iterations); - } - }; - - private static final TestCase SerializeSameObject = new TestCase() - { - public double run(Transformer transformer, Serializer serializer, J value, int iterations) throws Exception - { - // let's reuse same instance to reduce overhead - Object obj = transformer.forward(value); - long start = System.nanoTime(); - for (int i = 0; i < iterations; i++) - { - serializer.serialize(obj); - //if (i % 1000 == 0) - // doGc(); - } - return iterationTime(System.nanoTime() - start, iterations); - } - }; - - private static final TestCase Deserialize = new TestCase() - { - public double run(Transformer transformer, Serializer serializer, J value, int iterations) throws Exception - { - byte[] array = serializer.serialize(transformer.forward(value)); - long start = System.nanoTime(); - for (int i = 0; i < iterations; i++) - { - serializer.deserialize(array); - } - return iterationTime(System.nanoTime() - start, iterations); - } - }; - - private static final TestCase DeserializeAndCheck = new TestCase() - { - public double run(Transformer transformer, Serializer serializer, J value, int iterations) throws Exception - { - byte[] array = serializer.serialize(transformer.forward(value)); - long start = System.nanoTime(); - for (int i = 0; i < iterations; i++) - { - Object obj = serializer.deserialize(array); - transformer.reverse(obj); - } - return iterationTime(System.nanoTime() - start, iterations); - } - }; - - private static final TestCase DeserializeAndCheckShallow = new TestCase() - { - public double run(Transformer transformer, Serializer serializer, J value, int iterations) throws Exception - { - byte[] array = serializer.serialize(transformer.forward(value)); - long start = System.nanoTime(); - for (int i = 0; i < iterations; i++) - { - Object obj = serializer.deserialize(array); - transformer.shallowReverse(obj); - } - return iterationTime(System.nanoTime() - start, iterations); - } - }; - - /** - * JVM is not required to honor GC requests, but adding bit of sleep around request is - * most likely to give it a chance to do it. - */ - private static void doGc() - { - try { - Thread.sleep(50L); - } catch (InterruptedException ie) { - System.err.println("Interrupted while sleeping in serializers.BenchmarkRunner.doGc()"); - } - System.gc(); - try { // longer sleep afterwards (not needed by GC, but may help with scheduling) - Thread.sleep(200L); - } catch (InterruptedException ie) { - System.err.println("Interrupted while sleeping in serializers.BenchmarkRunner.doGc()"); - } - } - - // ------------------------------------------------------------------------------------ - - private static abstract class TestCase - { - public abstract double run(Transformer transformer, Serializer serializer, J value, int iterations) throws Exception; - } - - private static final class TestCaseRunner - { - private final Transformer transformer; - private final Serializer serializer; - private final J value; - - public TestCaseRunner(Transformer transformer, Serializer serializer, J value) - { - this.transformer = transformer; - this.serializer = serializer; - this.value = value; - } - - public double run(TestCase tc, int iterations) throws Exception - { - return tc.run(transformer, serializer, value, iterations); - } - - public double runTakeMin(int trials, TestCase tc, int iterations) throws Exception - { - double minTime = Double.MAX_VALUE; - for (int i = 0; i < trials; i++) { - double time = tc.run(transformer, serializer, value, iterations); - minTime = Math.min(minTime, time); - } - return minTime; - } - } - - enum measurements - { - timeCreate("create (nanos)"), timeSerializeDifferentObjects("ser (nanos)"), timeSerializeSameObject("ser+same (nanos)"), - timeDeserializeNoFieldAccess("deser (nanos)"), timeDeserializeAndCheck("deser+deep (nanos)"), timeDeserializeAndCheckShallow("deser+shal (nanos)"), - totalTime("total (nanos)"), length("size (bytes)"), lengthDeflate("size+dfl (bytes)"), - ; - - public final String displayName; - - measurements(String displayName) - { - this.displayName = displayName; - } - } - - private static EnumMap> - start(PrintWriter errors, int iterations, int trials, long warmupTime, boolean prewarm, Iterable> groups, J value) throws Exception - { - // Check correctness first. - System.out.println("Checking correctness..."); - for (TestGroup.Entry entry : groups) - { - checkCorrectness(errors, entry.transformer, entry.serializer, value); - } - System.out.println("[done]"); - - // Pre-warm. - if (prewarm) { - System.out.print("Pre-warmup..."); - for (TestGroup.Entry entry : groups) - { - TestCaseRunner runner = new TestCaseRunner(entry.transformer, entry.serializer, value); - String name = entry.serializer.getName(); - System.out.print(" " + name); - - warmCreation(runner, warmupTime); - warmSerialization(runner, warmupTime); - warmDeserialization(runner, warmupTime); - } - System.out.println(); - System.out.println("[done]"); - } - - System.out.printf("%-32s %6s %7s %7s %7s %7s %7s %7s %6s %5s\n", - "", - "create", - "ser", - "+same", - "deser", - "+shal", - "+deep", - "total", - "size", - "+dfl"); - EnumMap> values = new EnumMap>(measurements.class); - for (measurements m : measurements.values()) - values.put(m, new HashMap()); - - // Actual tests. - for (TestGroup.Entry entry : groups) - { - TestCaseRunner runner = new TestCaseRunner(entry.transformer, entry.serializer, value); - String name = entry.serializer.getName(); - try { - - /* - * Should only warm things for the serializer that we test next: HotSpot JIT will - * otherwise spent most of its time optimizing slower ones... Use - * -XX:CompileThreshold=1 to hint the JIT to start immediately - * - * Actually: 1 is often not a good value -- threshold is the number - * of samples needed to trigger inlining, and there's no point in - * inlining everything. Default value is in thousands, so lowering - * it to, say, 1000 is usually better. - */ - warmCreation(runner, warmupTime); - - doGc(); - double timeCreate = runner.runTakeMin(trials, Create, iterations * 100); // do more iteration for object creation because of its short time - - warmSerialization(runner, warmupTime); - - doGc(); - double timeSerializeDifferentObjects = runner.runTakeMin(trials, Serialize, iterations); - - doGc(); - double timeSerializeSameObject = runner.runTakeMin(trials, SerializeSameObject, iterations); - - warmDeserialization(runner, warmupTime); - - doGc(); - double timeDeserializeNoFieldAccess = runner.runTakeMin(trials, Deserialize, iterations); - - doGc(); - double timeDeserializeAndCheckShallow = runner.runTakeMin(trials, DeserializeAndCheckShallow, iterations); - - doGc(); - double timeDeserializeAndCheck = runner.runTakeMin(trials, DeserializeAndCheck, iterations); - - double totalTime = timeSerializeDifferentObjects + timeDeserializeAndCheck; - - byte[] array = entry.serializer.serialize(entry.transformer.forward(value)); - - byte[] compressDeflate = compressDeflate(array); - - System.out.printf("%-32s %6.0f %7.0f %7.0f %7.0f %7.0f %7.0f %7.0f %6d %5d\n", - name, - timeCreate, - timeSerializeDifferentObjects, - timeSerializeSameObject, - timeDeserializeNoFieldAccess, - timeDeserializeAndCheckShallow, - timeDeserializeAndCheck, - totalTime, - array.length, - compressDeflate.length); - - addValue(values, name, timeCreate, timeSerializeDifferentObjects, timeSerializeSameObject, - timeDeserializeNoFieldAccess, timeDeserializeAndCheckShallow, timeDeserializeAndCheck, totalTime, - array.length, compressDeflate.length); - } - catch (Exception ex) { - System.out.println("ERROR: \"" + name + "\" crashed during benchmarking."); - errors.println(ERROR_DIVIDER); - errors.println("\"" + name + "\" crashed during benchmarking."); - ex.printStackTrace(errors); - } - } - - return values; - } - - private static byte[] compressDeflate(byte[] data) - { - try { - ByteArrayOutputStream bout = new ByteArrayOutputStream(500); - DeflaterOutputStream compresser = new DeflaterOutputStream(bout); - compresser.write(data, 0, data.length); - compresser.finish(); - compresser.flush(); - return bout.toByteArray(); - } - catch (IOException ex) { - AssertionError ae = new AssertionError("IOException while writing to ByteArrayOutputStream!"); - ae.initCause(ex); - throw ae; - } - } - - /** - * Method that tries to validate correctness of serializer, using - * round-trip (construct, serializer, deserialize; compare objects - * after steps 1 and 3). - */ - private static void checkCorrectness(PrintWriter errors, Transformer transformer, Serializer serializer, J value) - throws Exception - { - Object specialInput; - String name = serializer.getName(); - - try { - specialInput = transformer.forward(value); - } - catch (Exception ex) { - System.out.println("ERROR: \"" + name + "\" crashed during forward transformation."); - errors.println(ERROR_DIVIDER); - errors.println("\"" + name + "\" crashed during forward transformation."); - ex.printStackTrace(errors); - return; - } - - byte[] array; - - try { - array = serializer.serialize(specialInput); - } - catch (Exception ex) { - System.out.println("ERROR: \"" + name + "\" crashed during serialization."); - errors.println(ERROR_DIVIDER); - errors.println("\"" + name + "\" crashed during serialization."); - ex.printStackTrace(errors); - return; - } - - Object specialOutput; - - try { - specialOutput = serializer.deserialize(array); - } - catch (Exception ex) { - System.out.println("ERROR: \"" + name + "\" crashed during deserialization."); - errors.println(ERROR_DIVIDER); - errors.println("\"" + name + "\" crashed during deserialization."); - ex.printStackTrace(errors); - return; - } - - J output; - try { - output = transformer.reverse(specialOutput); - } - catch (Exception ex) { - System.out.println("ERROR: \"" + name + "\" crashed during reverse transformation."); - errors.println(ERROR_DIVIDER); - errors.println("\"" + name + "\" crashed during reverse transformation."); - ex.printStackTrace(errors); - return; - } - - - if (!value.equals(output)) { - System.out.println("ERROR: \"" + name + "\" failed round-trip check."); - errors.println(ERROR_DIVIDER); - errors.println("\"" + name + "\" failed round-trip check."); - errors.println("ORIGINAL: " + value); - errors.println("ROUNDTRIP: " + output); - } - } - - private static void printImages(EnumMap> values) - { - for (measurements m : values.keySet()) { - Map map = values.get(m); - ArrayList> list = new ArrayList>(map.entrySet()); - Collections.sort(list, new Comparator>() { - public int compare (Map.Entry o1, Map.Entry o2) { - double diff = o1.getValue() - o2.getValue(); - return diff > 0 ? 1 : (diff < 0 ? -1 : 0); - } - }); - LinkedHashMap sortedMap = new LinkedHashMap(); - for (Map.Entry entry : list) { - if( !entry.getValue().isNaN() ) { - sortedMap.put(entry.getKey(), entry.getValue()); - } - } - if (!sortedMap.isEmpty()) printImage(sortedMap, m); - } - } - - private static String urlEncode(String s) - { - try { - return URLEncoder.encode(s, "UTF-8"); - } - catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } - - private static void printImage(Map map, measurements m) - { - StringBuilder valSb = new StringBuilder(); - String names = ""; - double max = Double.MIN_NORMAL; - for (Map.Entry entry : map.entrySet()) - { - double value = entry.getValue(); - valSb.append((int) value).append(','); - max = Math.max(max, entry.getValue()); - names = urlEncode(entry.getKey()) + '|' + names; - } - - int headerSize = 30; - - int maxPixels = 300 * 1000; // Limit set by Google's Chart API. - - int maxHeight = 600; - int width = maxPixels / maxHeight; - - int barThickness = 10; - int barSpacing = 10; - - int height; - - // Reduce bar thickness and spacing until we can fit in the maximum height. - while (true) { - height = headerSize + map.size()*(barThickness + barSpacing); - if (height <= maxHeight) break; - barSpacing--; - if (barSpacing == 1) break; - - height = headerSize + map.size()*(barThickness + barSpacing); - if (height <= maxHeight) break; - barThickness--; - if (barThickness == 1) break; - } - - boolean truncated = false; - if (height > maxHeight) { - truncated = true; - height = maxHeight; - } - - double scale = max * 1.1; - System.out.println(""); - - if (truncated) { - System.err.println("WARNING: Not enough room to fit all bars in chart."); - } - } - - private static void addValue( - EnumMap> values, - String name, - double timeCreate, - double timeSerializeDifferentObjects, - double timeSerializeSameObject, - double timeDeserializeNoFieldAccess, - double timeDeserializeAndCheckShallow, - double timeDeserializeAndCheck, - double totalTime, - double length, double lengthDeflate) - { - values.get(measurements.timeSerializeDifferentObjects).put(name, timeSerializeDifferentObjects); - values.get(measurements.timeSerializeSameObject).put(name, timeSerializeSameObject); - values.get(measurements.timeDeserializeNoFieldAccess).put(name, timeDeserializeNoFieldAccess); - values.get(measurements.timeDeserializeAndCheckShallow).put(name, timeDeserializeAndCheckShallow); - values.get(measurements.timeDeserializeAndCheck).put(name, timeDeserializeAndCheck); - values.get(measurements.totalTime).put(name, totalTime); - values.get(measurements.length).put(name, length); - values.get(measurements.lengthDeflate).put(name, lengthDeflate); - values.get(measurements.timeCreate).put(name, timeCreate); - } - - private static void warmCreation(TestCaseRunner runner, long warmupTime) throws Exception - { - // Instead of fixed counts, let's try to prime by running for N seconds - long endTime = System.currentTimeMillis() + warmupTime; - do - { - runner.run(Create, 10); - } - while (System.currentTimeMillis() < endTime); - } - - private static void warmSerialization(TestCaseRunner runner, long warmupTime) throws Exception - { - // Instead of fixed counts, let's try to prime by running for N seconds - long endTime = System.currentTimeMillis() + warmupTime; - do - { - runner.run(Serialize, 10); - } - while (System.currentTimeMillis() < endTime); - } - - private static void warmDeserialization(TestCaseRunner runner, long warmupTime) throws Exception - { - // Instead of fixed counts, let's try to prime by running for N seconds - long endTime = System.currentTimeMillis() + warmupTime; - do - { - runner.run(DeserializeAndCheck, 10); - } - while (System.currentTimeMillis() < endTime); - } -} diff --git a/dubbo-test/dubbo-test-benchmark/src/test/backup/Dubbo.java b/dubbo-test/dubbo-test-benchmark/src/test/backup/Dubbo.java deleted file mode 100644 index 4be9444e4b9..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/test/backup/Dubbo.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2011 Alibaba.com All right reserved. This software is the - * confidential and proprietary information of Alibaba.com ("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.dubbo.serialize.benchmark; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import com.alibaba.dubbo.common.io.UnsafeByteArrayInputStream; -import com.alibaba.dubbo.common.io.UnsafeByteArrayOutputStream; -import com.alibaba.dubbo.common.serialize.support.dubbo.GenericObjectInput; -import com.alibaba.dubbo.common.serialize.support.dubbo.GenericObjectOutput; -import com.caucho.hessian.io.Hessian2StreamingInput; -import com.caucho.hessian.io.Hessian2StreamingOutput; - -import data.media.MediaContent; - -/** - * 类Dubbo.java的实现描述:Dubbo Seriazition Benchmark - * - * @author tony.chenl 2011-9-30 上午10:17:21 - */ -public class Dubbo { - - public static void register(TestGroups groups) { - groups.media.add(JavaBuiltIn.MediaTransformer, Dubbo.GenericSerializer()); - } - - public static Serializer GenericSerializer() - { - @SuppressWarnings("unchecked") - Serializer s = (Serializer) GenericSerializer; - return s; - } - - // ------------------------------------------------------------ - // Serializer (just one) - - public static Serializer GenericSerializer = new Serializer() - { - public Object deserialize(byte[] array) throws Exception - { - GenericObjectInput objectInput = new GenericObjectInput(new ByteArrayInputStream(array)); - return objectInput.readObject(); - } - - public byte[] serialize(Object data) throws java.io.IOException - { - UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(10240); - GenericObjectOutput objectOutput = new GenericObjectOutput(os); - objectOutput.writeObject(data); - objectOutput.flushBuffer(); - return os.toByteArray(); - } - - public String getName() - { - return "dubbo"; - } - }; -} diff --git a/dubbo-test/dubbo-test-benchmark/src/test/java/com/jingdong/client/DemoBenchmarkClientRunnable.java b/dubbo-test/dubbo-test-benchmark/src/test/java/com/jingdong/client/DemoBenchmarkClientRunnable.java deleted file mode 100644 index 08e881ab598..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/test/java/com/jingdong/client/DemoBenchmarkClientRunnable.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 1999-2101 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.jingdong.client; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; - -import com.alibaba.dubbo.rpc.benchmark.AbstractClientRunnable; -import com.alibaba.dubbo.rpc.benchmark.DemoService; -import com.alibaba.dubbo.rpc.benchmark.ServiceFactory; - -/** - * DemoBenchmarkClient.java - * @author tony.chenl - */ -public class DemoBenchmarkClientRunnable extends AbstractClientRunnable{ - - public DemoBenchmarkClientRunnable(String targetIP, int targetPort, int clientNums, int rpcTimeout, - CyclicBarrier barrier, CountDownLatch latch, long startTime, - long endTime){ - super(targetIP, targetPort, clientNums, rpcTimeout, barrier, latch, startTime, endTime); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public Object invoke(ServiceFactory serviceFactory) { - DemoService demoService = (DemoService) serviceFactory.get(DemoService.class); - return demoService.sendRequest("hello"); - } - -} diff --git a/dubbo-test/dubbo-test-benchmark/src/test/resources/dubbo-default.properties b/dubbo-test/dubbo-test-benchmark/src/test/resources/dubbo-default.properties deleted file mode 100644 index e185bedc19a..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/test/resources/dubbo-default.properties +++ /dev/null @@ -1,7 +0,0 @@ -dubbo.registry.address=10.20.153.28:9090 -dubbo.provider.port=20880 -dubbo.provider.protocol=dubbo -dubbo.provider.codec= -dubbo.provider.client= -dubbo.provider.server= -dubbo.provider.serialization= \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark/src/test/resources/log4j.properties b/dubbo-test/dubbo-test-benchmark/src/test/resources/log4j.properties deleted file mode 100644 index 02bc05eaf9b..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/test/resources/log4j.properties +++ /dev/null @@ -1,6 +0,0 @@ -log4j.rootLogger=WARN,stdout -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.Target=System.out -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} [%t] %5p %c{1}\:%L - %m%n -log4j.logger.com.alibaba.dubbo=WARN \ No newline at end of file diff --git a/dubbo-test/dubbo-test-benchmark/src/test/resources/server/dubborpcserver.sh b/dubbo-test/dubbo-test-benchmark/src/test/resources/server/dubborpcserver.sh deleted file mode 100644 index 1cc54b786a9..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/test/resources/server/dubborpcserver.sh +++ /dev/null @@ -1 +0,0 @@ -sh servercommon.sh "../lib" "com.alibaba.dubbo.rpc.benchmark.RpcBenchmarkServer" "rpcserver.log.dubbo" diff --git a/dubbo-test/dubbo-test-benchmark/src/test/resources/server/dubboserver.sh b/dubbo-test/dubbo-test-benchmark/src/test/resources/server/dubboserver.sh deleted file mode 100644 index 33e6522c020..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/test/resources/server/dubboserver.sh +++ /dev/null @@ -1 +0,0 @@ -sh servercommon.sh "../lib" "com.alibaba.dubbo.rpc.benchmark.BenchmarkServer" "server.log.dubbo" diff --git a/dubbo-test/dubbo-test-benchmark/src/test/resources/server/servercommon.sh b/dubbo-test/dubbo-test-benchmark/src/test/resources/server/servercommon.sh deleted file mode 100644 index 68e4ef8de36..00000000000 --- a/dubbo-test/dubbo-test-benchmark/src/test/resources/server/servercommon.sh +++ /dev/null @@ -1 +0,0 @@ -java -Xms2g -Xmx2g -Xmn500m -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log -Djava.ext.dirs=$1 $2 [listenport] [maxthreads] [responsesize] [transporter] [serialization]> $3 2>&1 & diff --git a/dubbo-test/dubbo-test-compatibility/pom.xml b/dubbo-test/dubbo-test-compatibility/pom.xml deleted file mode 100644 index d02370e64cc..00000000000 --- a/dubbo-test/dubbo-test-compatibility/pom.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-test - 2.8.4 - - dubbo-test-compatibility - jar - ${project.artifactId} - The technology compatibility kit(TCK) test module of dubbo project - - true - - - - com.alibaba - dubbo - ${project.parent.version} - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/pom.xml b/dubbo-test/dubbo-test-examples/pom.xml deleted file mode 100644 index 43b4b699291..00000000000 --- a/dubbo-test/dubbo-test-examples/pom.xml +++ /dev/null @@ -1,180 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-test - 2.8.4 - - dubbo-test-examples - jar - ${project.artifactId} - The examples demo module of dubbo project - - true - - - - com.alibaba - dubbo-config-api - ${project.parent.version} - - - com.alibaba - dubbo-config-spring - ${project.parent.version} - - - com.alibaba - dubbo-remoting-netty - ${project.parent.version} - - - com.alibaba - dubbo-remoting-mina - ${project.parent.version} - - - com.alibaba - dubbo-remoting-grizzly - ${project.parent.version} - - - com.alibaba - dubbo-remoting-p2p - ${project.parent.version} - - - com.alibaba - dubbo-remoting-http - ${project.parent.version} - - - 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.alibaba - dubbo-rpc-http - ${project.parent.version} - - - com.alibaba - dubbo-rpc-webservice - ${project.parent.version} - - - com.alibaba - dubbo-rpc-thrift - ${project.parent.version} - - - com.alibaba - dubbo-rpc-memcached - ${project.parent.version} - - - com.alibaba - dubbo-rpc-redis - ${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} - - - com.alibaba - dubbo-monitor-default - ${project.parent.version} - - - javax.validation - validation-api - - - org.hibernate - hibernate-validator - - - com.alibaba - fastjson - - - joda-time - joda-time - 2.4 - - - com.fasterxml.jackson.datatype - jackson-datatype-joda - 2.4.0 - - - org.springframework - spring-aop - - - - org.aspectj - aspectjweaver - 1.7.4 - - - - - - - ${basedir}/src/main/java - - **/*.java - - - - ${basedir}/src/main/resources - - - - - diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/AnnotationConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/AnnotationConsumer.java deleted file mode 100644 index eea49d94588..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/AnnotationConsumer.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.annotation; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.annotation.action.AnnotationAction; - -/** - * CallbackConsumer - * - * @author william.liangf - */ -public class AnnotationConsumer { - - public static void main(String[] args) throws Exception { - String config = AnnotationConsumer.class.getPackage().getName().replace('.', '/') + "/annotation-consumer.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - final AnnotationAction annotationAction = (AnnotationAction)context.getBean("annotationAction"); - 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/annotation/AnnotationProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/AnnotationProvider.java deleted file mode 100644 index 6185a99fc61..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/AnnotationProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.annotation; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * MergeProvider - * - * @author william.liangf - */ -public class AnnotationProvider { - - public static void main(String[] args) throws Exception { - String config = AnnotationProvider.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/annotation/action/AnnotationAction.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/action/AnnotationAction.java deleted file mode 100644 index 0d82b44aebf..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/action/AnnotationAction.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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.annotation.action; - -import org.springframework.stereotype.Component; - -import com.alibaba.dubbo.config.annotation.Reference; -import com.alibaba.dubbo.examples.annotation.api.AnnotationService; - -/** - * AnnotationAction - * - * @author william.liangf - */ -@Component("annotationAction") -public class AnnotationAction { - - @Reference - private AnnotationService 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/annotation/annotation-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/annotation-consumer.xml deleted file mode 100644 index dbf8a3e4fe4..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/annotation-consumer.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/annotation-provider.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/annotation-provider.xml deleted file mode 100644 index 4e38e9345df..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/annotation-provider.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/api/AnnotationService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/api/AnnotationService.java deleted file mode 100644 index 6d35a8c65d8..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/api/AnnotationService.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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.annotation.api; - -/** - * AsyncService - * - * @author william.liangf - */ -public interface AnnotationService { - - String sayHello(String name); - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/impl/AnnotationServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/impl/AnnotationServiceImpl.java deleted file mode 100644 index d0d29c11ed6..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/annotation/impl/AnnotationServiceImpl.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.annotation.impl; - -import com.alibaba.dubbo.config.annotation.Service; -import com.alibaba.dubbo.examples.annotation.api.AnnotationService; - -/** - * AsyncServiceImpl - * - * @author william.liangf - */ -@Service -public class AnnotationServiceImpl implements AnnotationService { - - public String sayHello(String name) { - System.out.println("async provider received: " + name); - return "annotation: hello, " + name; - } - -} \ No newline at end of file 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 deleted file mode 100644 index be5a4d04f3c..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/AopAnnotationConsumer.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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 deleted file mode 100644 index 9a9542a34ae..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/AopAnnotationProvider.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 deleted file mode 100644 index 52a4ed20b07..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/action/AopAnnotationAction.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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 deleted file mode 100644 index 6eb4da39361..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/annotation-consumer.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - \ 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 deleted file mode 100644 index 9dfaf32445d..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/annotation-provider.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - \ 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 deleted file mode 100644 index 8061f37f73b..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/aop-aspect.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - \ 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 deleted file mode 100644 index 60e6cefc303..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/api/AopAnnotationService.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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 deleted file mode 100644 index 5fb0743599d..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/aspect/AnnotationAspect.java +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 71440f6ee3e..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/aop/impl/AopAnnotationServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/AsyncConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/AsyncConsumer.java deleted file mode 100644 index 3bb73e0ea88..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/AsyncConsumer.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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.async; - -import java.util.concurrent.Callable; -import java.util.concurrent.Future; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.async.api.AsyncService; -import com.alibaba.dubbo.rpc.RpcContext; - -/** - * CallbackConsumer - * - * @author william.liangf - */ -public class AsyncConsumer { - - public static void main(String[] args) throws Exception { - String config = AsyncConsumer.class.getPackage().getName().replace('.', '/') + "/async-consumer.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - - final AsyncService asyncService = (AsyncService)context.getBean("asyncService"); - - Future f = RpcContext.getContext().asyncCall(new Callable() { - public String call() throws Exception { - return asyncService.sayHello("async call request"); - } - }); - - System.out.println("async call ret :" + f.get()); - - RpcContext.getContext().asyncCall(new Runnable() { - public void run() { - asyncService.sayHello("oneway call request1"); - asyncService.sayHello("oneway call request2"); - } - }); - - System.in.read(); - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/AsyncProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/AsyncProvider.java deleted file mode 100644 index 15993fbf5f2..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/AsyncProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.async; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * MergeProvider - * - * @author william.liangf - */ -public class AsyncProvider { - - public static void main(String[] args) throws Exception { - String config = AsyncProvider.class.getPackage().getName().replace('.', '/') + "/async-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/async/api/AsyncService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/api/AsyncService.java deleted file mode 100644 index b659e38f3ba..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/api/AsyncService.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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.async.api; - -/** - * AsyncService - * - * @author william.liangf - */ -public interface AsyncService { - - String sayHello(String name); - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/async-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/async-consumer.xml deleted file mode 100644 index 71a54a287e3..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/async-consumer.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/async-provider.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/async-provider.xml deleted file mode 100644 index a40a3e8cfe7..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/async-provider.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/impl/AsyncServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/impl/AsyncServiceImpl.java deleted file mode 100644 index 52cf92bd3be..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/async/impl/AsyncServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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.async.impl; - -import com.alibaba.dubbo.examples.async.api.AsyncService; - -/** - * AsyncServiceImpl - * - * @author william.liangf - */ -public class AsyncServiceImpl implements AsyncService { - - public String sayHello(String name) { - System.out.println("async provider received: " + name); - return "hello, " + name; - } - -} \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/CacheConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/CacheConsumer.java deleted file mode 100644 index ec70d7952bd..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/CacheConsumer.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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.cache; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.cache.api.CacheService; - -/** - * CacheConsumer - * - * @author william.liangf - */ -public class CacheConsumer { - - public static void main(String[] args) throws Exception { - String config = CacheConsumer.class.getPackage().getName().replace('.', '/') + "/cache-consumer.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - - CacheService cacheService = (CacheService)context.getBean("cacheService"); - - // 测试缓存生效,多次调用返回同样的结果。(服务器端自增长返回值) - String fix = null; - for (int i = 0; i < 5; i ++) { - String result = cacheService.findCache("0"); - if (fix == null || fix.equals(result)) { - System.out.println("OK: " + result); - } else { - System.err.println("ERROR: " + result); - } - fix = result; - Thread.sleep(500); - } - - // LRU的缺省cache.size为1000,执行1001次,应有溢出 - for (int n = 0; n < 1001; n ++) { - String pre = null; - for (int i = 0; i < 10; i ++) { - String result = cacheService.findCache(String.valueOf(n)); - if (pre != null && ! pre.equals(result)) { - System.err.println("ERROR: " + result); - } - pre = result; - } - } - - // 测试LRU有移除最开始的一个缓存项 - String result = cacheService.findCache("0"); - if (fix != null && ! fix.equals(result)) { - System.out.println("OK: " + result); - } else { - System.err.println("ERROR: " + result); - } - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/CacheProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/CacheProvider.java deleted file mode 100644 index 88dd11bbaec..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/CacheProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.cache; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * CacheProvider - * - * @author william.liangf - */ -public class CacheProvider { - - public static void main(String[] args) throws Exception { - String config = CacheProvider.class.getPackage().getName().replace('.', '/') + "/cache-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/cache/api/CacheService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/api/CacheService.java deleted file mode 100644 index 90facfd4b76..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/api/CacheService.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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.cache.api; - -/** - * ValidationService - * - * @author william.liangf - */ -public interface CacheService { - - String findCache(String id); - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/cache-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/cache-consumer.xml deleted file mode 100644 index 32dfb10fb07..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/cache-consumer.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/cache-provider.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/cache-provider.xml deleted file mode 100644 index 1875559fe5b..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/cache-provider.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/impl/CacheServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/impl/CacheServiceImpl.java deleted file mode 100644 index 5710e0fa354..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/cache/impl/CacheServiceImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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.cache.impl; - -import java.util.concurrent.atomic.AtomicInteger; - -import com.alibaba.dubbo.examples.cache.api.CacheService; - -/** - * ValidationServiceImpl - * - * @author william.liangf - */ -public class CacheServiceImpl implements CacheService { - - private final AtomicInteger i = new AtomicInteger(); - - public String findCache(String id) { - return "request: " + id + ", response: " + i.getAndIncrement(); - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/CallbackConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/CallbackConsumer.java deleted file mode 100644 index 576762bb540..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/CallbackConsumer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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.callback; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.callback.api.CallbackListener; -import com.alibaba.dubbo.examples.callback.api.CallbackService; - -/** - * CallbackConsumer - * - * @author william.liangf - */ -public class CallbackConsumer { - - public static void main(String[] args) throws Exception { - String config = CallbackConsumer.class.getPackage().getName().replace('.', '/') + "/callback-consumer.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - CallbackService callbackService = (CallbackService) context.getBean("callbackService"); - callbackService.addListener("foo.bar", new CallbackListener() { - public void changed(String msg) { - System.out.println("callback1:" + msg); - } - }); - System.in.read(); - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/CallbackProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/CallbackProvider.java deleted file mode 100644 index a530d973f1a..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/CallbackProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.callback; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * MergeProvider - * - * @author william.liangf - */ -public class CallbackProvider { - - public static void main(String[] args) throws Exception { - String config = CallbackProvider.class.getPackage().getName().replace('.', '/') + "/callback-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/callback/api/CallbackListener.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/api/CallbackListener.java deleted file mode 100644 index bc7d1726d38..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/api/CallbackListener.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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.callback.api; - -/** - * CallbackListener - * - * @author william.liangf - */ -public interface CallbackListener { - - void changed(String msg); - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/api/CallbackService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/api/CallbackService.java deleted file mode 100644 index 93675aac9d6..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/api/CallbackService.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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.callback.api; - -/** - * CallbackService - * - * @author william.liangf - */ -public interface CallbackService { - - void addListener(String key, CallbackListener listener); - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/callback-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/callback-consumer.xml deleted file mode 100644 index 66cdaca23b9..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/callback-consumer.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/callback-provider.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/callback-provider.xml deleted file mode 100644 index 013abe17e6c..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/callback-provider.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/impl/CallbackServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/impl/CallbackServiceImpl.java deleted file mode 100644 index c904b337f8d..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/callback/impl/CallbackServiceImpl.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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.callback.impl; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.alibaba.dubbo.examples.callback.api.CallbackListener; -import com.alibaba.dubbo.examples.callback.api.CallbackService; - -/** - * CallbackServiceImpl - * - * @author william.liangf - */ -public class CallbackServiceImpl implements CallbackService { - - private final Map listeners = new ConcurrentHashMap(); - - public CallbackServiceImpl() { - Thread t = new Thread(new Runnable() { - public void run() { - while(true) { - try { - for(Map.Entry entry : listeners.entrySet()){ - try { - entry.getValue().changed(getChanged(entry.getKey())); - } catch (Throwable t) { - listeners.remove(entry.getKey()); - } - } - Thread.sleep(5000); // 定时触发变更通知 - } catch (Throwable t) { // 防御容错 - t.printStackTrace(); - } - } - } - }); - t.setDaemon(true); - t.start(); - } - - public void addListener(String key, CallbackListener listener) { - listeners.put(key, listener); - listener.changed(getChanged(key)); // 发送变更通知 - } - - private String getChanged(String key) { - return "Changed: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); - } - -} \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/GenericConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/GenericConsumer.java deleted file mode 100644 index 0d95d5b69f5..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/GenericConsumer.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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.generic; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.generic.api.IUserService; -import com.alibaba.dubbo.examples.generic.api.IUserService.Params; -import com.alibaba.dubbo.examples.generic.api.IUserService.User; - -/** - * GenericConsumer - * - * @author chao.liuc - */ -public class GenericConsumer { - - public static void main(String[] args) throws Exception { - String config = GenericConsumer.class.getPackage().getName().replace('.', '/') + "/generic-consumer.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - IUserService userservice = (IUserService) context.getBean("userservice"); - User user = userservice.get(new Params("a=b")); - System.out.println(user); - System.in.read(); - } -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/GenericProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/GenericProvider.java deleted file mode 100644 index 0fc38f9a26b..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/GenericProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.generic; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * GenericProvider - * - * @author chao.liuc - */ -public class GenericProvider { - - public static void main(String[] args) throws Exception { - String config = GenericProvider.class.getPackage().getName().replace('.', '/') + "/generic-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/generic/api/IService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/api/IService.java deleted file mode 100644 index 3d1f3e3b2c9..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/api/IService.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.alibaba.dubbo.examples.generic.api; - -public interface IService { - V get(P params); -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/api/IUserService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/api/IUserService.java deleted file mode 100644 index 09a855a2eb9..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/api/IUserService.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * 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.generic.api; - -import java.io.Serializable; - -import com.alibaba.dubbo.examples.generic.api.IUserService.Params; -import com.alibaba.dubbo.examples.generic.api.IUserService.User; - -/** - * @author chao.liuc - * - */ -public interface IUserService extends IService { - - - public static class Params implements Serializable{ - private static final long serialVersionUID = 1L; - - public Params(String query) { - } - } - public static class User implements Serializable{ - private static final long serialVersionUID = 1L; - public User(int id, String name) { - super(); - this.id = id; - this.name = name; - } - private int id; - private String name; - public int getId() { - return id; - } - public void setId(int 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/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/generic-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/generic-consumer.xml deleted file mode 100644 index 4f4b38785ed..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/generic-consumer.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/generic-provider.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/generic-provider.xml deleted file mode 100644 index efddb376fe2..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/generic-provider.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/impl/UserServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/impl/UserServiceImpl.java deleted file mode 100644 index 31329b1b574..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/generic/impl/UserServiceImpl.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 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.generic.impl; - -import com.alibaba.dubbo.examples.generic.api.IUserService; - -/** - * @author chao.liuc - * - */ -public class UserServiceImpl implements IUserService { - - public User get(Params params) { - return new User(1, "charles"); - } -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java deleted file mode 100644 index 016fc87b29b..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartBeatExchangeHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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.heartbeat; - -import java.util.concurrent.atomic.AtomicInteger; - -import com.alibaba.dubbo.remoting.Channel; -import com.alibaba.dubbo.remoting.RemotingException; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.Request; -import com.alibaba.dubbo.remoting.exchange.Response; -import com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeHandler; - -/** - * @author kimi - */ -public class HeartBeatExchangeHandler extends HeaderExchangeHandler { - - private AtomicInteger heartBeatCounter = new AtomicInteger( 0 ); - - public HeartBeatExchangeHandler( ExchangeHandler handler ) { - super( handler ); - } - - @Override - public void received( Channel channel, Object message ) throws RemotingException { - if ( message instanceof Request ) { - Request req = ( Request ) message; - if ( req.isHeartbeat() ) { - heartBeatCounter.incrementAndGet(); - channel.setAttribute(KEY_READ_TIMESTAMP, System.currentTimeMillis()); - Response res = new Response( req.getId(), req.getVersion() ); - res.setEvent( req.getData() == null ? null : req.getData().toString() ); - channel.send( res ); - } - } else { - super.received( channel, message ); - } - } - - public int getHeartBeatCount() { - return heartBeatCounter.get(); - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatClient.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatClient.java deleted file mode 100644 index 770322300ae..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatClient.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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.heartbeat; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Transporters; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.ExchangeServer; -import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeClient; -import com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeServer; - -/** - * @author kimi - */ -public class HeartbeatClient { - - private static final URL serverUrl = URL.valueOf( - new StringBuilder( 32 ) - .append( "netty://" ) - .append( NetUtils.getLocalHost() ) - .append( ":9999" ).toString() ) - .addParameter( Constants.CODEC_KEY, "exchange" ); - - private static final ExchangeHandler handler = new ExchangeHandlerAdapter() { - - }; - - private static ExchangeServer exchangeServer; - - private static volatile boolean serverStarted = false; - - public static void main( String[] args ) throws Exception { - - final HeartBeatExchangeHandler serverHandler = new HeartBeatExchangeHandler( handler ); - - Thread serverThread = new Thread( new Runnable() { - - public void run() { - try { - exchangeServer = new HeaderExchangeServer( - Transporters.bind( serverUrl, serverHandler ) ); - serverStarted = true; - } catch ( Exception e ) { - e.printStackTrace(); - } - } - } ); - - serverThread.setDaemon( true ); - serverThread.start(); - - while ( ! serverStarted ) { - Thread.sleep( 1000 ); - } - - URL url = serverUrl.addParameter( Constants.HEARTBEAT_KEY, 1000 ); - - HeartBeatExchangeHandler clientHandler = new HeartBeatExchangeHandler( handler ); - ExchangeClient exchangeClient = new HeaderExchangeClient( - Transporters.connect( url, clientHandler ) ); - - for( int i = 0; i < 10; i++ ) { - Thread.sleep( 1000 ); - System.out.print( "." ); - } - - System.out.println(); - - if ( serverHandler.getHeartBeatCount() > 0 ) { - System.out.printf( "Server receives %d heartbeats", - serverHandler.getHeartBeatCount() ); - } else { - throw new Exception( "Client heartbeat does not work." ); - } - - exchangeClient.close(); - exchangeServer.close(); - - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatConsumer.java deleted file mode 100644 index 229ecf35f18..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatConsumer.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.heartbeat; - -import com.alibaba.dubbo.examples.heartbeat.api.HelloService; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * @author kimi - */ -public class HeartbeatConsumer { - - public static void main(String[] args) throws Exception { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( - HeartbeatConsumer.class.getPackage().getName().replace('.', '/') + "/heartbeat-consumer.xml"); - context.start(); - HelloService hello = (HelloService) context.getBean("helloService"); - for (int i = 0; i < Integer.MAX_VALUE; i++) { - System.out.println(hello.sayHello("kimi-" + i)); - Thread.sleep(10000); - } - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatProvider.java deleted file mode 100644 index cec2ab9fd49..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatProvider.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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.heartbeat; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * @author kimi - */ -public class HeartbeatProvider { - - public static void main(String[] args) throws Exception { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( - HeartbeatProvider.class.getPackage().getName().replace( '.', '/' ) + "/heartbeat-provider.xml" ); - context.start(); - System.in.read(); - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatServer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatServer.java deleted file mode 100644 index 2792add1601..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/HeartbeatServer.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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.heartbeat; - -import com.alibaba.dubbo.common.Constants; -import com.alibaba.dubbo.common.URL; -import com.alibaba.dubbo.common.utils.NetUtils; -import com.alibaba.dubbo.remoting.Transporters; -import com.alibaba.dubbo.remoting.exchange.ExchangeClient; -import com.alibaba.dubbo.remoting.exchange.ExchangeHandler; -import com.alibaba.dubbo.remoting.exchange.ExchangeServer; -import com.alibaba.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeClient; -import com.alibaba.dubbo.remoting.exchange.support.header.HeaderExchangeServer; - -/** - * @author kimi - */ -public class HeartbeatServer { - - private static final URL clientUrl = URL.valueOf( - new StringBuilder( 32 ) - .append( "netty://" ) - .append( NetUtils.getLocalHost() ) - .append( ":9999" ).toString() ) - .addParameter( Constants.CODEC_KEY, "exchange" ); - - private static final ExchangeHandler handler = new ExchangeHandlerAdapter() { - - }; - - private static ExchangeServer exchangeServer; - - private static volatile boolean serverStarted = false; - - public static void main( String[] args ) throws Exception { - - final HeartBeatExchangeHandler serverHandler = new HeartBeatExchangeHandler( handler ); - - Thread serverThread = new Thread( new Runnable() { - - public void run() { - try { - exchangeServer = new HeaderExchangeServer( - Transporters.bind( - clientUrl.addParameter( Constants.HEARTBEAT_KEY, 1000 ), - serverHandler ) ); - serverStarted = true; - } catch ( Exception e ) { - e.printStackTrace(); - } - } - } ); - - serverThread.setDaemon( true ); - serverThread.start(); - - while ( !serverStarted ) { - Thread.sleep( 1000 ); - } - - HeartBeatExchangeHandler clientHandler = new HeartBeatExchangeHandler( handler ); - ExchangeClient exchangeClient = new HeaderExchangeClient( - Transporters.connect( clientUrl, clientHandler ) ); - - for ( int i = 0; i < 10; i++ ) { - Thread.sleep( 1000 ); - System.out.print( "." ); - } - - System.out.println(); - - if ( clientHandler.getHeartBeatCount() > 0 ) { - System.out.printf( "Client receives %d heartbeats", - clientHandler.getHeartBeatCount() ); - } else { - throw new Exception( "Server heartbeat does not work." ); - } - - exchangeClient.close(); - exchangeServer.close(); - - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/api/HelloService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/api/HelloService.java deleted file mode 100644 index 6da33245439..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/api/HelloService.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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.heartbeat.api; - -/** - * @author kimi - */ -public interface HelloService { - - public String sayHello(String name); - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/heartbeat-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/heartbeat-consumer.xml deleted file mode 100644 index 6d293bcb2bc..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/heartbeat-consumer.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/heartbeat-provider.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/heartbeat-provider.xml deleted file mode 100644 index 49577bdd313..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/heartbeat-provider.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/impl/HelloServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/impl/HelloServiceImpl.java deleted file mode 100644 index a7f4cf6ce2f..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/heartbeat/impl/HelloServiceImpl.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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.heartbeat.impl; - -import com.alibaba.dubbo.examples.heartbeat.api.HelloService; - -/** - * @author kimi - */ -public class HelloServiceImpl implements HelloService { - - public String sayHello(String name) { - return new StringBuilder(32).append("Hello, ").append(name).append("!").toString(); - } -} 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 deleted file mode 100644 index e13847d690d..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonConsumer.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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.*; -import com.google.common.collect.Lists; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import java.util.Arrays; -import java.util.List; - -/** - * 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"); - 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/JacksonProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonProvider.java deleted file mode 100644 index dfa097fce18..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/JacksonProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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/AbstractInheritBean.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/AbstractInheritBean.java deleted file mode 100644 index 70ee7e17eb4..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/AbstractInheritBean.java +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index e57b13bba98..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/Inherit.java +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 6bccb8e909c..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/InheritBean.java +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 4bd51b074c5..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/InheritBean2.java +++ /dev/null @@ -1,25 +0,0 @@ -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/JacksonBean.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonBean.java deleted file mode 100644 index f42ec812105..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonBean.java +++ /dev/null @@ -1,110 +0,0 @@ -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 deleted file mode 100644 index 1a44907c8d0..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonInnerBean.java +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 836eb8e3b7f..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/api/JacksonService.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 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); - - 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 deleted file mode 100644 index f13528bc8ba..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/impl/JacksonServiceImpl.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 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.*; - -/** - * @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; - } - - @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"); - } -} 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 deleted file mode 100644 index f4a05eb5ac3..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jackson-consumer.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - \ 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 deleted file mode 100644 index 93a9d2a6212..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jackson-provider.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - \ 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 deleted file mode 100644 index b6f1c2de4d2..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/jackson/jacksonprovider/CustomJacksonObjectMapperProvider.java +++ /dev/null @@ -1,15 +0,0 @@ -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/java/com/alibaba/dubbo/examples/memcached/MemcachedConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/memcached/MemcachedConsumer.java deleted file mode 100644 index 27f90a8a6e5..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/memcached/MemcachedConsumer.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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.memcached; - -import java.util.Map; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * GenericConsumer - * - * @author chao.liuc - */ -public class MemcachedConsumer { - - @SuppressWarnings("unchecked") - public static void main(String[] args) throws Exception { - String config = MemcachedConsumer.class.getPackage().getName().replace('.', '/') + "/memcached-consumer.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - Map cache = (Map) context.getBean("cache"); - cache.remove("hello"); - Object value = cache.get("hello"); - System.out.println(value); - if (value != null) { - throw new IllegalStateException(value + " != null"); - } - cache.put("hello", "world"); - value = cache.get("hello"); - System.out.println(value); - if (! "world".equals(value)) { - throw new IllegalStateException(value + " != world"); - } - System.in.read(); - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/memcached/memcached-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/memcached/memcached-consumer.xml deleted file mode 100644 index d83410fa20d..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/memcached/memcached-consumer.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/MergeConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/MergeConsumer.java deleted file mode 100644 index e67024ddc7e..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/MergeConsumer.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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.merge; - -import java.util.List; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.merge.api.MergeService; - -/** - * MergeConsumer - * - * @author william.liangf - */ -public class MergeConsumer { - - public static void main(String[] args) throws Exception { - String config = MergeConsumer.class.getPackage().getName().replace('.', '/') + "/merge-consumer.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - MergeService mergeService = (MergeService)context.getBean("mergeService"); - for (int i = 0; i < Integer.MAX_VALUE; i ++) { - try { - List result = mergeService.mergeResult(); - System.out.println("(" + i + ") " + result); - Thread.sleep(1000); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/MergeConsumer2.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/MergeConsumer2.java deleted file mode 100644 index ca5016a002c..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/MergeConsumer2.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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.merge; - -import java.util.List; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.merge.api.MergeService; - -/** - * MergeConsumer2 - * - * @author william.liangf - */ -public class MergeConsumer2 { - - public static void main(String[] args) throws Exception { - String config = MergeConsumer2.class.getPackage().getName().replace('.', '/') + "/merge-consumer2.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - MergeService mergeService = (MergeService)context.getBean("mergeService"); - for (int i = 0; i < Integer.MAX_VALUE; i ++) { - try { - List result = mergeService.mergeResult(); - System.out.println("(" + i + ") " + result); - Thread.sleep(1000); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/MergeProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/MergeProvider.java deleted file mode 100644 index ee49b697c6f..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/MergeProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.merge; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * MergeProvider - * - * @author william.liangf - */ -public class MergeProvider { - - public static void main(String[] args) throws Exception { - String config = MergeProvider.class.getPackage().getName().replace('.', '/') + "/merge-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/merge/MergeProvider2.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/MergeProvider2.java deleted file mode 100644 index bf1bd804993..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/MergeProvider2.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.merge; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * MergeProvider2 - * - * @author william.liangf - */ -public class MergeProvider2 { - - public static void main(String[] args) throws Exception { - String config = MergeProvider2.class.getPackage().getName().replace('.', '/') + "/merge-provider2.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/merge/api/MergeService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/api/MergeService.java deleted file mode 100644 index eb8197f0c74..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/api/MergeService.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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.merge.api; - -import java.util.List; - -/** - * MergeService - * - * @author william.liangf - */ -public interface MergeService { - - List mergeResult(); - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/impl/MergeServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/impl/MergeServiceImpl.java deleted file mode 100644 index c1e56110c85..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/impl/MergeServiceImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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.merge.impl; - -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.dubbo.examples.merge.api.MergeService; - -/** - * MenuServiceImpl - * - * @author william.liangf - */ -public class MergeServiceImpl implements MergeService { - - public List mergeResult() { - List menus = new ArrayList(); - menus.add("group-1.1"); - menus.add("group-1.2"); - return menus; - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/impl/MergeServiceImpl2.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/impl/MergeServiceImpl2.java deleted file mode 100644 index a8f2c06270f..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/impl/MergeServiceImpl2.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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.merge.impl; - -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.dubbo.examples.merge.api.MergeService; - -/** - * MenuServiceImpl - * - * @author william.liangf - */ -public class MergeServiceImpl2 implements MergeService { - - public List mergeResult() { - List menus = new ArrayList(); - menus.add("group-2.1"); - menus.add("group-2.2"); - return menus; - } - -} \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/impl/MergeServiceImpl3.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/impl/MergeServiceImpl3.java deleted file mode 100644 index 3185da82791..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/impl/MergeServiceImpl3.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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.merge.impl; - -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.dubbo.examples.merge.api.MergeService; - -/** - * MenuServiceImpl - * - * @author william.liangf - */ -public class MergeServiceImpl3 implements MergeService { - - public List mergeResult() { - List menus = new ArrayList(); - menus.add("group-3.1"); - menus.add("group-3.2"); - return menus; - } - -} \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-consumer.xml deleted file mode 100644 index 05f7339a730..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-consumer.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-consumer2.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-consumer2.xml deleted file mode 100644 index d9673dbe83b..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-consumer2.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-provider.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-provider.xml deleted file mode 100644 index bdcaa7138ef..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-provider.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-provider2.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-provider2.xml deleted file mode 100644 index b525e2485e6..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/merge/merge-provider2.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/redis/RedisConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/redis/RedisConsumer.java deleted file mode 100644 index e3f22541994..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/redis/RedisConsumer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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.redis; - -import java.util.Map; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * GenericConsumer - * - * @author chao.liuc - */ -public class RedisConsumer { - - @SuppressWarnings("unchecked") - public static void main(String[] args) throws Exception { - String config = RedisConsumer.class.getPackage().getName().replace('.', '/') + "/redis-consumer.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - Map cache = (Map) context.getBean("cache"); - cache.remove("hello"); - Object value = cache.get("hello"); - System.out.println(value); - if (value != null) { - throw new IllegalStateException(value + " != null"); - } - cache.put("hello", "world"); - value = cache.get("hello"); - System.out.println(value); - if (! "world".equals(value)) { - throw new IllegalStateException(value + " != world"); - } - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/redis/redis-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/redis/redis-consumer.xml deleted file mode 100644 index fc0558c4722..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/redis/redis-consumer.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/ValidationConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/ValidationConsumer.java deleted file mode 100644 index 6333638ecf9..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/ValidationConsumer.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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.validation; - -import java.util.Date; -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.validation.api.ValidationParameter; -import com.alibaba.dubbo.examples.validation.api.ValidationService; -import com.alibaba.dubbo.rpc.RpcException; - -/** - * ValidationConsumer - * - * @author william.liangf - */ -public class ValidationConsumer { - - public static void main(String[] args) throws Exception { - String config = ValidationConsumer.class.getPackage().getName().replace('.', '/') + "/validation-consumer.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - - ValidationService validationService = (ValidationService)context.getBean("validationService"); - - // Save OK - ValidationParameter parameter = new ValidationParameter(); - parameter.setName("liangfei"); - parameter.setEmail("liangfei@liang.fei"); - parameter.setAge(50); - parameter.setLoginDate(new Date(System.currentTimeMillis() - 1000000)); - parameter.setExpiryDate(new Date(System.currentTimeMillis() + 1000000)); - validationService.save(parameter); - System.out.println("Validation Save OK"); - - // Save Error - try { - parameter = new ValidationParameter(); - validationService.save(parameter); - System.err.println("Validation Save ERROR"); - } catch (RpcException e) { - ConstraintViolationException ve = (ConstraintViolationException)e.getCause(); - Set> violations = ve.getConstraintViolations(); - System.out.println(violations); - } - - // Delete OK - validationService.delete(2, "abc"); - System.out.println("Validation Delete OK"); - - // Delete Error - try { - validationService.delete(0, "abc"); - System.err.println("Validation Delete ERROR"); - } catch (RpcException e) { - ConstraintViolationException ve = (ConstraintViolationException)e.getCause(); - Set> violations = ve.getConstraintViolations(); - System.out.println(violations); - } - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/ValidationProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/ValidationProvider.java deleted file mode 100644 index a20f247c6d0..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/ValidationProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.validation; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * ValidationProvider - * - * @author william.liangf - */ -public class ValidationProvider { - - public static void main(String[] args) throws Exception { - String config = ValidationProvider.class.getPackage().getName().replace('.', '/') + "/validation-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/validation/api/ValidationParameter.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/api/ValidationParameter.java deleted file mode 100644 index fea9dc6c210..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/api/ValidationParameter.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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.validation.api; - -import java.io.Serializable; -import java.util.Date; - -import javax.validation.constraints.Future; -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Past; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; - -/** - * ValidationParameter - * - * @author william.liangf - */ -public class ValidationParameter implements Serializable { - - private static final long serialVersionUID = 7158911668568000392L; - - @NotNull // 不允许为空 - @Size(min = 2, max = 20) // 长度或大小范围 - private String name; - - @NotNull(groups = ValidationService.Save.class) // 保存时不允许为空,更新时允许为空 ,表示不更新该字段 - @Pattern(regexp = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$") - private String email; - - @Min(18) // 最小值 - @Max(100) // 最大值 - private int age; - - @Past // 必须为一个过去的时间 - private Date loginDate; - - @Future // 必须为一个未来的时间 - private Date expiryDate; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public Date getLoginDate() { - return loginDate; - } - - public void setLoginDate(Date loginDate) { - this.loginDate = loginDate; - } - - public Date getExpiryDate() { - return expiryDate; - } - - public void setExpiryDate(Date expiryDate) { - this.expiryDate = expiryDate; - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/api/ValidationService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/api/ValidationService.java deleted file mode 100644 index 73e24fd97f4..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/api/ValidationService.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.validation.api; - -import javax.validation.constraints.Min; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Pattern; -import javax.validation.constraints.Size; - - -/** - * ValidationService - * - * @author william.liangf - */ -public interface ValidationService { // 缺省可按服务接口区分验证场景,如:@NotNull(groups = ValidationService.class) - - @interface Save{} // 与方法同名接口,首字母大写,用于区分验证场景,如:@NotNull(groups = ValidationService.Save.class),可选 - void save(ValidationParameter parameter); - - @interface Update{} // 与方法同名接口,首字母大写,用于区分验证场景,如:@NotNull(groups = ValidationService.Update.class),可选 - void update(ValidationParameter parameter); - - void delete(@Min(1) long id, @NotNull @Size(min = 2, max = 16) @Pattern(regexp = "^[a-zA-Z]+$") String operator); - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/impl/ValidationServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/impl/ValidationServiceImpl.java deleted file mode 100644 index f420aafa121..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/impl/ValidationServiceImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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.validation.impl; - -import com.alibaba.dubbo.examples.validation.api.ValidationParameter; -import com.alibaba.dubbo.examples.validation.api.ValidationService; - -/** - * ValidationServiceImpl - * - * @author william.liangf - */ -public class ValidationServiceImpl implements ValidationService { - - public void save(ValidationParameter parameter) { - } - - public void update(ValidationParameter parameter) { - } - - public void delete(long id, String operator) { - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/validation-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/validation-consumer.xml deleted file mode 100644 index 0e437e61e43..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/validation-consumer.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/validation-provider.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/validation-provider.xml deleted file mode 100644 index cf92eb59526..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/validation/validation-provider.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/VersionConsumer.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/VersionConsumer.java deleted file mode 100644 index f0afd803405..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/VersionConsumer.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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.version; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.version.api.VersionService; - -/** - * VersionConsumer - * - * @author william.liangf - */ -public class VersionConsumer { - - public static void main(String[] args) throws Exception { - String config = VersionConsumer.class.getPackage().getName().replace('.', '/') + "/version-consumer.xml"; - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config); - context.start(); - VersionService versionService = (VersionService) context.getBean("versionService"); - for (int i = 0; i < 10000; i ++) { - String hello = versionService.sayHello("world"); - System.out.println(hello); - Thread.sleep(2000); - } - System.in.read(); - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/VersionProvider.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/VersionProvider.java deleted file mode 100644 index 5050ca97c37..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/VersionProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.version; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * VersionProvider - * - * @author william.liangf - */ -public class VersionProvider { - - public static void main(String[] args) throws Exception { - String config = VersionProvider.class.getPackage().getName().replace('.', '/') + "/version-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/version/VersionProvider2.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/VersionProvider2.java deleted file mode 100644 index be253a57a36..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/VersionProvider2.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.version; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * VersionProvider2 - * - * @author william.liangf - */ -public class VersionProvider2 { - - public static void main(String[] args) throws Exception { - String config = VersionProvider2.class.getPackage().getName().replace('.', '/') + "/version-provider2.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/version/api/VersionService.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/api/VersionService.java deleted file mode 100644 index c3d28f0913b..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/api/VersionService.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * 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.version.api; - -/** - * @author william.liangf - */ -public interface VersionService { - - String sayHello(String name); - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/impl/VersionServiceImpl.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/impl/VersionServiceImpl.java deleted file mode 100644 index 52542a08ea2..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/impl/VersionServiceImpl.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 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.version.impl; - -import com.alibaba.dubbo.examples.version.api.VersionService; - -/** - * @author william.liangf - */ -public class VersionServiceImpl implements VersionService { - - public String sayHello(String name) { - return "hello, " + name; - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/impl/VersionServiceImpl2.java b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/impl/VersionServiceImpl2.java deleted file mode 100644 index 86b7c222d1d..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/impl/VersionServiceImpl2.java +++ /dev/null @@ -1,29 +0,0 @@ -/** - * 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.version.impl; - -import com.alibaba.dubbo.examples.version.api.VersionService; - -/** - * @author william.liangf - */ -public class VersionServiceImpl2 implements VersionService { - - public String sayHello(String name) { - return "hello2, " + name; - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/version-consumer.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/version-consumer.xml deleted file mode 100644 index 1687f844b5c..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/version-consumer.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/version-provider.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/version-provider.xml deleted file mode 100644 index c8b2e88f863..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/version-provider.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/version-provider2.xml b/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/version-provider2.xml deleted file mode 100644 index be829bbc376..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/java/com/alibaba/dubbo/examples/version/version-provider2.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider b/dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider deleted file mode 100644 index b14abca92d2..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.common.json.JacksonObjectMapperProvider +++ /dev/null @@ -1 +0,0 @@ -default=com.alibaba.dubbo.examples.jackson.jacksonprovider.CustomJacksonObjectMapperProvider \ No newline at end of file diff --git a/dubbo-test/dubbo-test-examples/src/main/resources/log4j.xml b/dubbo-test/dubbo-test-examples/src/main/resources/log4j.xml deleted file mode 100644 index 69ed180b230..00000000000 --- a/dubbo-test/dubbo-test-examples/src/main/resources/log4j.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - - - - - - diff --git a/dubbo-test/dubbo-test-examples/src/test/java/com/alibaba/dubbo/examples/annotation/AnnotationTest.java b/dubbo-test/dubbo-test-examples/src/test/java/com/alibaba/dubbo/examples/annotation/AnnotationTest.java deleted file mode 100644 index 8a5c4786ed1..00000000000 --- a/dubbo-test/dubbo-test-examples/src/test/java/com/alibaba/dubbo/examples/annotation/AnnotationTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.annotation; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.annotation.action.AnnotationAction; - -/** - * AnnotationTest - * - * @author william.liangf - */ -public class AnnotationTest { - - @Test - public void testAnnotation() { - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(AnnotationTest.class.getPackage().getName().replace('.', '/') + "/annotation-provider.xml"); - providerContext.start(); - try { - ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(AnnotationTest.class.getPackage().getName().replace('.', '/') + "/annotation-consumer.xml"); - consumerContext.start(); - try { - AnnotationAction annotationAction = (AnnotationAction) consumerContext.getBean("annotationAction"); - String hello = annotationAction.doSayHello("world"); - assertEquals("annotation: hello, world", hello); - } finally { - consumerContext.stop(); - consumerContext.close(); - } - } finally { - providerContext.stop(); - providerContext.close(); - } - } - -} diff --git a/dubbo-test/dubbo-test-examples/src/test/java/com/alibaba/dubbo/examples/validation/ValidationTest.java b/dubbo-test/dubbo-test-examples/src/test/java/com/alibaba/dubbo/examples/validation/ValidationTest.java deleted file mode 100644 index 34c3ab2edbf..00000000000 --- a/dubbo-test/dubbo-test-examples/src/test/java/com/alibaba/dubbo/examples/validation/ValidationTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * 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.validation; - -import java.util.Date; -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; - -import junit.framework.Assert; - -import org.junit.Test; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.alibaba.dubbo.examples.validation.api.ValidationParameter; -import com.alibaba.dubbo.examples.validation.api.ValidationService; -import com.alibaba.dubbo.rpc.RpcException; - -/** - * ValidationTest - * - * @author william.liangf - */ -public class ValidationTest { - - @Test - public void testValidation() { - ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(ValidationTest.class.getPackage().getName().replace('.', '/') + "/validation-provider.xml"); - providerContext.start(); - try { - ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(ValidationTest.class.getPackage().getName().replace('.', '/') + "/validation-consumer.xml"); - consumerContext.start(); - try { - ValidationService validationService = (ValidationService) consumerContext.getBean("validationService"); - - // Save OK - ValidationParameter parameter = new ValidationParameter(); - parameter.setName("liangfei"); - parameter.setEmail("liangfei@liang.fei"); - parameter.setAge(50); - parameter.setLoginDate(new Date(System.currentTimeMillis() - 1000000)); - parameter.setExpiryDate(new Date(System.currentTimeMillis() + 1000000)); - validationService.save(parameter); - - try { - parameter = new ValidationParameter(); - parameter.setName("l"); - parameter.setEmail("liangfei@liang.fei"); - parameter.setAge(50); - parameter.setLoginDate(new Date(System.currentTimeMillis() - 1000000)); - parameter.setExpiryDate(new Date(System.currentTimeMillis() + 1000000)); - validationService.save(parameter); - Assert.fail(); - } catch (RpcException e) { - ConstraintViolationException ve = (ConstraintViolationException)e.getCause(); - Set> violations = ve.getConstraintViolations(); - Assert.assertNotNull(violations); - } - - // Save Error - try { - parameter = new ValidationParameter(); - validationService.save(parameter); - Assert.fail(); - } catch (RpcException e) { - ConstraintViolationException ve = (ConstraintViolationException)e.getCause(); - Set> violations = ve.getConstraintViolations(); - Assert.assertNotNull(violations); - } - - // Delete OK - validationService.delete(2, "abc"); - - // Delete Error - try { - validationService.delete(2, "a"); - Assert.fail(); - } catch (RpcException e) { - ConstraintViolationException ve = (ConstraintViolationException)e.getCause(); - Set> violations = ve.getConstraintViolations(); - Assert.assertNotNull(violations); - Assert.assertEquals(1, violations.size()); - } - - // Delete Error - try { - validationService.delete(0, "abc"); - Assert.fail(); - } catch (RpcException e) { - ConstraintViolationException ve = (ConstraintViolationException)e.getCause(); - Set> violations = ve.getConstraintViolations(); - Assert.assertNotNull(violations); - Assert.assertEquals(1, violations.size()); - } - try { - validationService.delete(2, null); - Assert.fail(); - } catch (RpcException e) { - ConstraintViolationException ve = (ConstraintViolationException)e.getCause(); - Set> violations = ve.getConstraintViolations(); - Assert.assertNotNull(violations); - Assert.assertEquals(1, violations.size()); - } - try { - validationService.delete(0, null); - Assert.fail(); - } catch (RpcException e) { - ConstraintViolationException ve = (ConstraintViolationException)e.getCause(); - Set> violations = ve.getConstraintViolations(); - Assert.assertNotNull(violations); - Assert.assertEquals(2, violations.size()); - } - } finally { - consumerContext.stop(); - consumerContext.close(); - } - } finally { - providerContext.stop(); - providerContext.close(); - } - } - -} diff --git a/dubbo-test/dubbo-test-integration/pom.xml b/dubbo-test/dubbo-test-integration/pom.xml deleted file mode 100644 index cbf43a6836a..00000000000 --- a/dubbo-test/dubbo-test-integration/pom.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-test - 2.8.4 - - dubbo-test-integration - jar - ${project.artifactId} - The showcase test module of dubbo project - - true - - - - com.alibaba - dubbo-config-api - ${project.parent.version} - - - com.alibaba - dubbo-config-spring - ${project.parent.version} - - - com.alibaba - dubbo-remoting-netty - ${project.parent.version} - - - com.alibaba - dubbo-remoting-mina - ${project.parent.version} - - - com.alibaba - dubbo-remoting-grizzly - ${project.parent.version} - - - com.alibaba - dubbo-remoting-p2p - ${project.parent.version} - - - com.alibaba - dubbo-remoting-http - ${project.parent.version} - - - 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.alibaba - dubbo-registry-default - ${project.parent.version} - - - com.alibaba - dubbo-registry-multicast - ${project.parent.version} - - - com.alibaba - dubbo-registry-zookeeper - ${project.parent.version} - - - com.alibaba - dubbo-monitor-default - ${project.parent.version} - - - javax.validation - validation-api - - - org.hibernate - hibernate-validator - - - - - - - ${basedir}/src/main/java - - **/*.java - - - - ${basedir}/src/main/resources - - - - - \ No newline at end of file diff --git a/dubbo-test/pom.xml b/dubbo-test/pom.xml deleted file mode 100644 index 8ccfec26d31..00000000000 --- a/dubbo-test/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-parent - 2.8.4 - - dubbo-test - pom - ${project.artifactId} - The test module of dubbo project - - true - - - dubbo-test-benchmark - dubbo-test-compatibility - dubbo-test-integration - dubbo-test-examples - dubbo-test-benchmark-api - dubbo-test-benchmark-server - dubbo-test-benchmark-client - - diff --git a/dubbo-tool/dubbo-demo-lite-archetype/pom.xml b/dubbo-tool/dubbo-demo-lite-archetype/pom.xml deleted file mode 100644 index 844d9844dbd..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/pom.xml +++ /dev/null @@ -1,114 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-demo-lite-archetype - 2.8.4 - 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/dubbo-tool/dubbo-demo-lite-archetype/readme.md b/dubbo-tool/dubbo-demo-lite-archetype/readme.md deleted file mode 100644 index 0d5494bc0b3..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/readme.md +++ /dev/null @@ -1,86 +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 - - -使用示例列举: - -
-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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index b610f8b1764..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml
+++ /dev/null
@@ -1,80 +0,0 @@
-
-
-  
-    
-      
-        
-          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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index 51c2ea26f9a..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/SerializationOptimizerImpl.java
+++ /dev/null
@@ -1,40 +0,0 @@
-#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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index b626753c5d0..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/ClientTraceFilter.java
+++ /dev/null
@@ -1,39 +0,0 @@
-#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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index a2ed960e38b..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/CustomExceptionMapper.java
+++ /dev/null
@@ -1,37 +0,0 @@
-#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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index ae97a785da7..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceBinding.java
+++ /dev/null
@@ -1,33 +0,0 @@
-#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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index 8418dcd253c..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/DynamicTraceInterceptor.java
+++ /dev/null
@@ -1,45 +0,0 @@
-#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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index e760d90bc66..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceFilter.java
+++ /dev/null
@@ -1,42 +0,0 @@
-#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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index 2c969205eec..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/extension/TraceInterceptor.java
+++ /dev/null
@@ -1,45 +0,0 @@
-#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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index 556de6f4380..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/User.java
+++ /dev/null
@@ -1,80 +0,0 @@
-#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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index 240260c533a..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/UserService.java
+++ /dev/null
@@ -1,28 +0,0 @@
-#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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index bff9e83fd9c..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/RegistrationResult.java
+++ /dev/null
@@ -1,48 +0,0 @@
-#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/dubbo-tool/dubbo-demo-lite-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
deleted file mode 100644
index 9118713a3a4..00000000000
--- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-api/src/main/java/user/facade/UserRestService.java
+++ /dev/null
@@ -1,51 +0,0 @@
-#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/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 deleted file mode 100644 index 8a771dd82f2..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/pom.xml +++ /dev/null @@ -1,179 +0,0 @@ - - - 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 - - - io.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/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index 3516e43dc66..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/assembly.xml +++ /dev/null @@ -1,42 +0,0 @@ -#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/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index f6e6daa4122..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/assembly/conf/dubbo.properties +++ /dev/null @@ -1,28 +0,0 @@ -#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/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index 3ebc5e7f8cd..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/java/consumer/DemoAction.java +++ /dev/null @@ -1,52 +0,0 @@ -#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/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index ce672ebbeee..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml +++ /dev/null @@ -1,30 +0,0 @@ -#set( $symbol_pound = '#' ) -#set( $symbol_dollar = '$' ) -#set( $symbol_escape = '\' ) - - - - - - - - - - - diff --git a/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index 63a302ba7e9..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml +++ /dev/null @@ -1,24 +0,0 @@ -#set( $symbol_pound = '#' ) -#set( $symbol_dollar = '$' ) -#set( $symbol_escape = '\' ) - - - - - - - - - - - - - - - - - diff --git a/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index 01ca2d6aa46..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/DemoConsumer.java +++ /dev/null @@ -1,27 +0,0 @@ -#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/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index 8512b023465..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/java/consumer/RestClient.java +++ /dev/null @@ -1,92 +0,0 @@ -#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/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index 77898f221fd..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-consumer/src/test/resources/log4j.xml +++ /dev/null @@ -1,31 +0,0 @@ -#set( $symbol_pound = '#' ) -#set( $symbol_dollar = '$' ) -#set( $symbol_escape = '\' ) - - - - - - - - - - - - - - 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 deleted file mode 100644 index 3c40d825868..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/pom.xml +++ /dev/null @@ -1,193 +0,0 @@ - - - 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 - - - io.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/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index b084730140a..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/UserServiceImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -#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/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index 3bf9cf567cb..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/java/user/facade/UserRestServiceImpl.java +++ /dev/null @@ -1,66 +0,0 @@ -#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/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index bee031cc66a..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml +++ /dev/null @@ -1,80 +0,0 @@ -#set( $symbol_pound = '#' ) -#set( $symbol_dollar = '$' ) -#set( $symbol_escape = '\' ) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index 77898f221fd..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/resources/log4j.xml +++ /dev/null @@ -1,31 +0,0 @@ -#set( $symbol_pound = '#' ) -#set( $symbol_dollar = '$' ) -#set( $symbol_escape = '\' ) - - - - - - - - - - - - - - diff --git a/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index f9cf14fa676..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,33 +0,0 @@ -#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/dubbo-tool/dubbo-demo-lite-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 deleted file mode 100644 index 258856f9e56..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/__rootArtifactId__-provider/src/test/java/provider/DemoProvider.java +++ /dev/null @@ -1,37 +0,0 @@ -#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/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 deleted file mode 100644 index 561a683e509..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/main/resources/archetype-resources/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-parent - 2.8.4 - - ${artifactId} - ${groupId} - pom - ${project.artifactId} - The demo lite module of dubbo project - ${version} - - true - - - - - - com.alibaba - dubbo - 2.8.4 - - - - diff --git a/dubbo-tool/dubbo-demo-lite-archetype/src/test/resources/projects/basic/archetype.properties b/dubbo-tool/dubbo-demo-lite-archetype/src/test/resources/projects/basic/archetype.properties deleted file mode 100644 index dc09b753b73..00000000000 --- a/dubbo-tool/dubbo-demo-lite-archetype/src/test/resources/projects/basic/archetype.properties +++ /dev/null @@ -1,5 +0,0 @@ -#Thu Dec 11 15:57:06 CST 2014 -package=it.pkg -version=0.1-SNAPSHOT -groupId=archetype.it -artifactId=basic 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 deleted file mode 100644 index fb06b640479..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-demo-lite - 2.8.4 - - 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/dubbo-tool/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 deleted file mode 100644 index f82006a14c6..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/SerializationOptimizerImpl.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index 108b09fbc2b..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/ClientTraceFilter.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index d73838a18ec..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/CustomExceptionMapper.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index eaf81d4d557..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceBinding.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index 8f6a249e1fa..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/DynamicTraceInterceptor.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index 457a28fde86..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceFilter.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index 4354f90850f..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/extension/TraceInterceptor.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index 005ff3794a5..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/User.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index c58f7d73d19..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/RegistrationResult.java +++ /dev/null @@ -1,45 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index b753eea68bd..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestService.java +++ /dev/null @@ -1,48 +0,0 @@ -/** - * 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/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml b/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml deleted file mode 100644 index e59c2df0903..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/pom.xml +++ /dev/null @@ -1,180 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-demo-lite - 2.8.4 - - 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 - - - io.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/dubbo-tool/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 deleted file mode 100644 index 1bdbe518dcd..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/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 - - - diff --git a/dubbo-tool/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 deleted file mode 100644 index 8d1835e8f0b..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/assembly/conf/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-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/dubbo-tool/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 deleted file mode 100644 index 32699c7b51a..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/java/com/alibaba/dubbo/demolite/consumer/DemoAction.java +++ /dev/null @@ -1,50 +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.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/dubbo-tool/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 deleted file mode 100644 index c0aa4f9b6e8..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-action.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - diff --git a/dubbo-tool/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 deleted file mode 100644 index 88f5164cbde..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/main/resources/META-INF/spring/dubbo-demo-lite-consumer.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/dubbo-tool/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 deleted file mode 100644 index e87a3f3acc6..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/DemoConsumer.java +++ /dev/null @@ -1,24 +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.demolite.consumer; - -public class DemoConsumer { - - public static void main(String[] args) { - com.alibaba.dubbo.container.Main.main(args); - } - -} diff --git a/dubbo-tool/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 deleted file mode 100644 index 5e4942160b7..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/java/com/alibaba/dubbo/demolite/consumer/RestClient.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index 5375cc32f39..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-consumer/src/test/resources/log4j.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - 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 deleted file mode 100644 index ab2cead41cd..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/pom.xml +++ /dev/null @@ -1,195 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-demo-lite - 2.8.4 - - 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 - - - io.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/dubbo-tool/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 deleted file mode 100644 index 837a0bc8bec..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/UserServiceImpl.java +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index ccbaa904ce1..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/java/com/alibaba/dubbo/demolite/user/facade/UserRestServiceImpl.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 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/dubbo-tool/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 deleted file mode 100644 index 3d4f93e308c..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/META-INF/spring/dubbo-demo-lite-provider.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/dubbo-tool/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 deleted file mode 100644 index 33bf5d8a725..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/resources/log4j.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-tool/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 deleted file mode 100644 index 242c3741c52..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - 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/dubbo-tool/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 deleted file mode 100644 index eaa78d67af2..00000000000 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-provider/src/test/java/com/alibaba/dubbo/demolite/provider/DemoProvider.java +++ /dev/null @@ -1,34 +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.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/dubbo-tool/dubbo-demo-lite/pom.xml b/dubbo-tool/dubbo-demo-lite/pom.xml deleted file mode 100644 index b43142ae691..00000000000 --- a/dubbo-tool/dubbo-demo-lite/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - 4.0.0 - - com.alibaba - dubbo-parent - 2.8.4 - - 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.4 - - - - diff --git a/dubbo/pom.xml b/dubbo/pom.xml index 1ff4074b884..7ef07e59934 100644 --- a/dubbo/pom.xml +++ b/dubbo/pom.xml @@ -19,7 +19,7 @@ com.alibaba dubbo-parent - 2.8.4 + 2.8.5-SNAPSHOT dubbo jar @@ -28,6 +28,7 @@ false + com.alibaba @@ -156,17 +157,6 @@ - - com.alibaba - dubbo-rpc-thrift - ${project.parent.version} - - - org.apache.thrift - libthrift - - - com.alibaba dubbo-rpc-memcached @@ -256,7 +246,7 @@ zookeeper - com.github.sgroschupf + com.alibaba zkclient @@ -318,6 +308,51 @@ + + com.alibaba + dubbo-rpc-thrift2 + ${project.parent.version} + + + org.apache.thrift + libthrift + + + + + com.alibaba + dubbo-rpc-grpc + ${project.parent.version} + + + io.grpc + grpc-netty + + + io.grpc + grpc-protobuf + + + io.grpc + grpc-stub + + + + + com.alibaba + dubbo-rpc-avro + ${project.parent.version} + + + org.apache.avro + avro + + + org.apache.avro + avro-ipc + + + @@ -335,6 +370,7 @@ maven-javadoc-plugin + 2.10.3 attach-javadoc @@ -380,13 +416,15 @@ com.alibaba:dubbo-remoting-http com.alibaba:dubbo-remoting-zookeeper com.alibaba:dubbo-rpc-api + com.alibaba:dubbo-rpc-avro 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-thrift2 + com.alibaba:dubbo-rpc-grpc com.alibaba:dubbo-rpc-memcached com.alibaba:dubbo-rpc-redis com.alibaba:dubbo-rpc-rest @@ -413,23 +451,29 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.common.compiler.Compiler + 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.extension.ExtensionFactory + - META-INF/dubbo/internal/com.alibaba.dubbo.common.serialize.Serialization + 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.status.StatusChecker + - META-INF/dubbo/internal/com.alibaba.dubbo.common.threadpool.ThreadPool + META-INF/dubbo/internal/com.alibaba.dubbo.common.threadpool.ThreadPool + @@ -445,23 +489,29 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.exchange.Exchanger + 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.http.HttpBinder + - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.p2p.Networker + 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.telnet.TelnetHandler + - META-INF/dubbo/internal/com.alibaba.dubbo.remoting.zookeeper.ZookeeperTransporter + + META-INF/dubbo/internal/com.alibaba.dubbo.remoting.zookeeper.ZookeeperTransporter + @@ -489,7 +539,8 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.LoadBalance + META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.LoadBalance + @@ -497,11 +548,14 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.rpc.cluster.RouterFactory + 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.rpc.cluster.ConfiguratorFactory + @@ -509,15 +563,18 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.container.page.PageHandler + 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.monitor.MonitorFactory + - META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory + META-INF/dubbo/internal/com.alibaba.dubbo.registry.RegistryFactory + @@ -529,11 +586,13 @@ - META-INF/dubbo/internal/com.alibaba.dubbo.common.store.DataStore + META-INF/dubbo/internal/com.alibaba.dubbo.common.store.DataStore + - META-INF/dubbo/internal/com.alibaba.dubbo.common.logger.LoggerAdapter + META-INF/dubbo/internal/com.alibaba.dubbo.common.logger.LoggerAdapter + diff --git a/hessian-lite/pom.xml b/hessian-lite/pom.xml index c377884a45e..6f122372527 100644 --- a/hessian-lite/pom.xml +++ b/hessian-lite/pom.xml @@ -6,7 +6,7 @@ com.alibaba dubbo-parent - 2.8.4 + 2.8.5-SNAPSHOT hessian-lite jar diff --git a/pom.xml b/pom.xml index f4e69f74a4b..cb4f6d18b65 100644 --- a/pom.xml +++ b/pom.xml @@ -16,11 +16,9 @@ 4.0.0 - com.alibaba dubbo-parent - 2.8.4 + 2.8.5-SNAPSHOT pom ${project.artifactId} The parent project of dubbo @@ -39,6 +37,7 @@ http://www.alibaba.com + zkclient dubbo-common dubbo-container dubbo-remoting @@ -49,24 +48,12 @@ dubbo-monitor dubbo-config dubbo - dubbo-simple - dubbo-admin + + dubbo-demo hessian-lite - - - test - - - .project - - - - dubbo-test - - hudson @@ -84,47 +71,67 @@ - 3.2.9.RELEASE + 4.2.4.RELEASE 3.15.0-GA - 3.7.0.Final + 3.9.9.Final 1.1.7 2.1.4 - 4.2.1 + 4.3.4 3.2.1-fixed-2 - 1.4.1 - 1.1.39 + 1.4.8 + 1.2.6 3.1 0.8 - 3.4.6 - 0.1 + 3.4.8 2.5.0 2.1.0 1.3.6 - 2.6.1 + 3.1.5 0.8.0 + 0.9.3 + 1.8.0 1.0.13 4.0.7 3.1.0 6.1.26 - 1.0.0.GA - 4.2.0.Final + 1.1.0.Final + 5.2.4.Final + 2.2.4 + 2.2.4 + 1.7 0.4 2.0-M5.1 3.0 2.2 - 3.0.8 - 2.3.3 + 3.1.6 + 2.7.1 + 1.6 + 2.6 8.0.11 - 1.6.2 + 1.7.15 1.1 - 1.2.16 - 1.0.6 + 1.2.17 + 1.1.5 + 2.5 4.10 3.0 0.999.8 + + + 2.0.1 + 3.0.9.Final + 3.0.16.Final + 3.0.14.Final + 3.0.14.Final + 3.0.14.Final + 3.0.16.Final + 2.24.0 + 0.37 + 2.44 + false @@ -145,9 +152,9 @@ oss - 2.3.2 - 1.6 - 1.6 + 3.6.0 + 1.8 + 1.8 UTF-8 2.1.1 @@ -157,6 +164,9 @@ 2.7 2.17 + 8.1.15.v20140411 + 1.8.0 + @@ -223,11 +233,6 @@ zookeeper ${zookeeper_version} - - com.github.sgroschupf - zkclient - ${zkclient_version} - org.apache.curator curator-framework @@ -256,7 +261,17 @@ org.apache.thrift libthrift - ${thrift_version} + ${thrift2_version} + + + org.apache.avro + avro + ${avro_version} + + + org.apache.avro + avro-ipc + ${avro_version} jfree @@ -288,11 +303,26 @@ hibernate-validator ${hibernate_validator_version} + + javax.el + javax.el-api + ${javax.el-api_version} + + + org.glassfish.web + javax.el + ${javax.el_version} + javax.cache cache-api ${jcache_version} + + org.apache.velocity + velocity + ${velocity_version} + org.apache.tuscany.sca tuscany-sca-api @@ -344,6 +374,16 @@ logback-classic ${logback_version} + + org.apache.logging.log4j + log4j-core + ${log4j2_version} + + + org.apache.logging.log4j + log4j-slf4j-impl + ${log4j2_version} + junit @@ -374,6 +414,11 @@ cglib-nodep ${cglib_version} + + commons-lang + commons-lang + ${commons-lang_version} + commons-pool commons-pool @@ -389,42 +434,40 @@ tomcat-embed-logging-juli ${tomcat_embed_version} - - javax.ws.rs javax.ws.rs-api - 2.0 + ${rs-api_version} org.jboss.resteasy resteasy-jaxrs - 3.0.7.Final + ${resteasy-jaxrs_version} org.jboss.resteasy resteasy-client - 3.0.7.Final + ${resteasy-jaxrs_version} org.jboss.resteasy resteasy-netty - 3.0.7.Final + ${resteasy-netty_version} org.jboss.resteasy resteasy-jdk-http - 3.0.7.Final + ${resteasy-jdk-http_version} org.jboss.resteasy resteasy-jackson-provider - 3.0.7.Final + ${resteasy-jackson-provider_version} org.jboss.resteasy resteasy-jaxb-provider - 3.0.7.Final + ${resteasy-jaxb-provider_version} com.esotericsoftware.kryo @@ -434,12 +477,12 @@ de.javakaffee kryo-serializers - 0.26 + ${kryo-serializers_version} de.ruedigermoeller fst - 1.55 + ${fst_version} @@ -479,6 +522,7 @@ maven-source-plugin + 3.0.1 attach-sources @@ -489,77 +533,6 @@ - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin_version} - - true - once - ${argline} - - - - transporter - ${transporter} - - - serialization - ${serialization} - - - - port - ${port} - - - threadpool - ${threadpool} - - - threads - ${threads} - - - iothreads - ${iothreads} - - - - server - ${server} - - - timeout - ${timeout} - - - length - ${length} - - - connections - ${connections} - - - base - ${base} - - - concurrent - ${concurrent} - - - runs - ${runs} - - - onerror - ${onerror} - - - - org.apache.maven.plugins maven-deploy-plugin @@ -600,9 +573,9 @@ ${java_source_version} ${java_target_version} ${file_encoding} - - -XX:MaxPermSize=512M - + + + + + + 9now + http://114.80.88.52:9001/nexus/content/repositories/jichu-snapshots/ + + + diff --git a/zkclient/pom.xml b/zkclient/pom.xml new file mode 100644 index 00000000000..9acece11a15 --- /dev/null +++ b/zkclient/pom.xml @@ -0,0 +1,40 @@ + + + 4.0.0 + + com.alibaba + dubbo-parent + 2.8.5-SNAPSHOT + + zkclient + jar + 0.8.1 + + + + org.apache.zookeeper + zookeeper + 3.4.8 + + + commons-io + commons-io + 1.4 + test + + + org.mockito + mockito-core + 1.8.0 + test + + + org.assertj + assertj-core + 2.0.0 + test + + + diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/ContentWatcher.java b/zkclient/src/main/java/org/I0Itec/zkclient/ContentWatcher.java new file mode 100644 index 00000000000..7e42fd98043 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/ContentWatcher.java @@ -0,0 +1,101 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import org.I0Itec.zkclient.exception.ZkNoNodeException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +//import org.apache.log4j.Logger; + +/** + * @param + * The data type that is being watched. + */ +public final class ContentWatcher implements IZkDataListener { + + //private static final Logger LOG = Logger.getLogger(ContentWatcher.class); + private static final Logger LOG = LoggerFactory.getLogger(ContentWatcher.class); + + private Lock _contentLock = new ReentrantLock(true); + private Condition _contentAvailable = _contentLock.newCondition(); + + private Holder _content; + private String _fileName; + private ZkClient _zkClient; + + public ContentWatcher(ZkClient zkClient, String fileName) { + _fileName = fileName; + _zkClient = zkClient; + } + + public void start() { + _zkClient.subscribeDataChanges(_fileName, this); + readData(); + LOG.debug("Started ContentWatcher"); + } + + @SuppressWarnings("unchecked") + private void readData() { + try { + setContent((T) _zkClient.readData(_fileName)); + } catch (ZkNoNodeException e) { + // ignore if the node has not yet been created + } + } + + public void stop() { + _zkClient.unsubscribeDataChanges(_fileName, this); + } + + public void setContent(T data) { + LOG.debug("Received new data: " + data); + _contentLock.lock(); + try { + _content = new Holder(data); + _contentAvailable.signalAll(); + } finally { + _contentLock.unlock(); + } + } + + @SuppressWarnings("unchecked") + @Override + public void handleDataChange(String dataPath, Object data) { + setContent((T) data); + } + + @Override + public void handleDataDeleted(String dataPath) { + // ignore + } + + public T getContent() throws InterruptedException { + _contentLock.lock(); + try { + while (_content == null) { + _contentAvailable.await(); + } + return _content.get(); + } finally { + _contentLock.unlock(); + } + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/DataUpdater.java b/zkclient/src/main/java/org/I0Itec/zkclient/DataUpdater.java new file mode 100644 index 00000000000..2395f3c7235 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/DataUpdater.java @@ -0,0 +1,34 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +/** + * Updates the data of a znode. This is used together with {@link ZkClient#updateDataSerialized(String, DataUpdater)}. + * + * @param + */ +public interface DataUpdater { + + /** + * Updates the current data of a znode. + * + * @param currentData + * The current contents. + * @return the new data that should be written back to ZooKeeper. + */ + public T update(T currentData); + +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/DistributedQueue.java b/zkclient/src/main/java/org/I0Itec/zkclient/DistributedQueue.java new file mode 100644 index 00000000000..ac2588c3957 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/DistributedQueue.java @@ -0,0 +1,125 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import java.io.Serializable; +import java.util.List; + +import org.I0Itec.zkclient.exception.ZkNoNodeException; + +public class DistributedQueue { + + private static class Element { + private String _name; + private T _data; + + public Element(String name, T data) { + _name = name; + _data = data; + } + + public String getName() { + return _name; + } + + public T getData() { + return _data; + } + } + + private ZkClient _zkClient; + private String _root; + + private static final String ELEMENT_NAME = "element"; + + public DistributedQueue(ZkClient zkClient, String root) { + _zkClient = zkClient; + _root = root; + } + + public boolean offer(T element) { + try { + _zkClient.createPersistentSequential(_root + "/" + ELEMENT_NAME + "-", element); + } catch (Exception e) { + throw ExceptionUtil.convertToRuntimeException(e); + } + return true; + } + + public T poll() { + while (true) { + Element element = getFirstElement(); + if (element == null) { + return null; + } + + try { + _zkClient.delete(element.getName()); + return element.getData(); + } catch (ZkNoNodeException e) { + // somebody else picked up the element first, so we have to + // retry with the new first element + } catch (Exception e) { + throw ExceptionUtil.convertToRuntimeException(e); + } + } + } + + private String getSmallestElement(List list) { + String smallestElement = list.get(0); + for (String element : list) { + if (element.compareTo(smallestElement) < 0) { + smallestElement = element; + } + } + + return smallestElement; + } + + public boolean isEmpty() { + return _zkClient.getChildren(_root).size() == 0; + } + + @SuppressWarnings("unchecked") + private Element getFirstElement() { + try { + while (true) { + List list = _zkClient.getChildren(_root); + if (list.size() == 0) { + return null; + } + String elementName = getSmallestElement(list); + + try { + return new Element(_root + "/" + elementName, (T) _zkClient.readData(_root + "/" + elementName)); + } catch (ZkNoNodeException e) { + // somebody else picked up the element first, so we have to + // retry with the new first element + } + } + } catch (Exception e) { + throw ExceptionUtil.convertToRuntimeException(e); + } + } + + public T peek() { + Element element = getFirstElement(); + if (element == null) { + return null; + } + return element.getData(); + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/ExceptionUtil.java b/zkclient/src/main/java/org/I0Itec/zkclient/ExceptionUtil.java new file mode 100644 index 00000000000..f72e3ea10aa --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/ExceptionUtil.java @@ -0,0 +1,51 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import org.I0Itec.zkclient.exception.ZkInterruptedException; + +public class ExceptionUtil { + + public static RuntimeException convertToRuntimeException(Throwable e) { + if (e instanceof RuntimeException) { + return (RuntimeException) e; + } + retainInterruptFlag(e); + return new RuntimeException(e); + } + + /** + * This sets the interrupt flag if the catched exception was an {@link InterruptedException}. Catching such an + * exception always clears the interrupt flag. + * + * @param catchedException + * The catched exception. + */ + public static void retainInterruptFlag(Throwable catchedException) { + if (catchedException instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + } + + public static void rethrowInterruptedException(Throwable e) throws InterruptedException { + if (e instanceof InterruptedException) { + throw (InterruptedException) e; + } + if (e instanceof ZkInterruptedException) { + throw (ZkInterruptedException) e; + } + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/Gateway.java b/zkclient/src/main/java/org/I0Itec/zkclient/Gateway.java new file mode 100644 index 00000000000..a6f59109dc3 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/Gateway.java @@ -0,0 +1,48 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +public class Gateway { + + private GatewayThread _thread; + private final int _port; + private final int _destinationPort; + + public Gateway(int port, int destinationPort) { + _port = port; + _destinationPort = destinationPort; + } + + public synchronized void start() { + if (_thread != null) { + throw new IllegalStateException("Gateway already running"); + } + _thread = new GatewayThread(_port, _destinationPort); + _thread.start(); + _thread.awaitUp(); + } + + public synchronized void stop() { + if (_thread != null) { + try { + _thread.interruptAndJoin(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + _thread = null; + } + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/GatewayThread.java b/zkclient/src/main/java/org/I0Itec/zkclient/GatewayThread.java new file mode 100644 index 00000000000..4263e1205a6 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/GatewayThread.java @@ -0,0 +1,191 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.List; +import java.util.Vector; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + + + +public class GatewayThread extends Thread { + + protected final static Logger LOG = LoggerFactory.getLogger(GatewayThread.class); + + private final int _port; + private final int _destinationPort; + private ServerSocket _serverSocket; + private Lock _lock = new ReentrantLock(); + private Condition _runningCondition = _lock.newCondition(); + private boolean _running = false; + + public GatewayThread(int port, int destinationPort) { + _port = port; + _destinationPort = destinationPort; + setDaemon(true); + } + + @Override + public void run() { + final List runningThreads = new Vector(); + try { + LOG.info("Starting gateway on port " + _port + " pointing to port " + _destinationPort); + _serverSocket = new ServerSocket(_port); + _lock.lock(); + try { + _running = true; + _runningCondition.signalAll(); + } finally { + _lock.unlock(); + } + while (true) { + final Socket socket = _serverSocket.accept(); + LOG.info("new client is connected " + socket.getInetAddress()); + final InputStream incomingInputStream = socket.getInputStream(); + final OutputStream incomingOutputStream = socket.getOutputStream(); + + final Socket outgoingSocket; + try { + outgoingSocket = new Socket("localhost", _destinationPort); + } catch (Exception e) { + LOG.warn("could not connect to " + _destinationPort); + continue; + } + final InputStream outgoingInputStream = outgoingSocket.getInputStream(); + final OutputStream outgoingOutputStream = outgoingSocket.getOutputStream(); + + Thread writeThread = new Thread() { + @Override + public void run() { + runningThreads.add(this); + try { + int read = -1; + while ((read = incomingInputStream.read()) != -1) { + outgoingOutputStream.write(read); + } + } catch (IOException e) { + // ignore + } finally { + closeQuietly(outgoingOutputStream); + runningThreads.remove(this); + } + } + + @Override + public void interrupt() { + try { + socket.close(); + outgoingSocket.close(); + } catch (IOException e) { + LOG.error("error on stopping closing sockets", e); + } + + super.interrupt(); + } + }; + + Thread readThread = new Thread() { + @Override + public void run() { + runningThreads.add(this); + try { + int read = -1; + while ((read = outgoingInputStream.read()) != -1) { + incomingOutputStream.write(read); + } + } catch (IOException e) { + // ignore + } finally { + closeQuietly(incomingOutputStream); + runningThreads.remove(this); + } + } + }; + + writeThread.setDaemon(true); + readThread.setDaemon(true); + + writeThread.start(); + readThread.start(); + } + } catch (SocketException e) { + if (!_running) { + throw ExceptionUtil.convertToRuntimeException(e); + } + LOG.info("Stopping gateway"); + } catch (Exception e) { + LOG.error("error on gateway execution", e); + } + + for (Thread thread : new ArrayList(runningThreads)) { + thread.interrupt(); + try { + thread.join(); + } catch (InterruptedException e) { + // ignore + } + } + } + + protected void closeQuietly(Closeable closable) { + try { + closable.close(); + } catch (IOException e) { + // ignore + } + } + + @Override + public void interrupt() { + try { + _serverSocket.close(); + } catch (Exception cE) { + LOG.error("error on stopping gateway", cE); + } + super.interrupt(); + } + + public void interruptAndJoin() throws InterruptedException { + interrupt(); + join(); + } + + public void awaitUp() { + _lock.lock(); + try { + while (!_running) { + _runningCondition.await(); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + _lock.unlock(); + } + } +} diff --git a/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigConsumer.java b/zkclient/src/main/java/org/I0Itec/zkclient/Holder.java similarity index 57% rename from dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigConsumer.java rename to zkclient/src/main/java/org/I0Itec/zkclient/Holder.java index afbe0704394..afebabba3ff 100644 --- a/dubbo-demo/dubbo-demo-consumer/src/test/java/com/alibaba/dubbo/demo/consumer/DemoJavaConfigConsumer.java +++ b/zkclient/src/main/java/org/I0Itec/zkclient/Holder.java @@ -1,11 +1,11 @@ -/* - * Copyright 2006-2014 handu.com. +/** + * Copyright 2010 the original author or authors. * * 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 + * 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, @@ -13,15 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.demo.consumer; +package org.I0Itec.zkclient; -/** - * @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); +public class Holder { + + private T _value; + + public Holder() { + // do nothing + } + + public Holder(T value) { + _value = value; + } + + public T get() { + return _value; + } + + public void set(T value) { + _value = value; } } diff --git a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java b/zkclient/src/main/java/org/I0Itec/zkclient/IDefaultNameSpace.java similarity index 58% rename from dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java rename to zkclient/src/main/java/org/I0Itec/zkclient/IDefaultNameSpace.java index 43b50306756..9ef652169fe 100644 --- a/dubbo-tool/dubbo-demo-lite/dubbo-demo-lite-api/src/main/java/com/alibaba/dubbo/demolite/user/UserService.java +++ b/zkclient/src/main/java/org/I0Itec/zkclient/IDefaultNameSpace.java @@ -1,11 +1,11 @@ /** - * Copyright 1999-2014 dangdang.com. + * Copyright 2010 the original author or authors. * * 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 + * 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, @@ -13,13 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.demolite.user; +package org.I0Itec.zkclient; -/** - * @author lishen - */ -public interface UserService { - User getUser(Long id); +public interface IDefaultNameSpace { - Long registerUser(User user); + /** + * Creates a set of default folder structure within a zookeeper . + * + * @param zkClient + * The zkclient. + */ + public void createDefaultNameSpace(ZkClient zkClient); } diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/IZkChildListener.java b/zkclient/src/main/java/org/I0Itec/zkclient/IZkChildListener.java new file mode 100644 index 00000000000..1e953678986 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/IZkChildListener.java @@ -0,0 +1,41 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import java.util.List; + +/** + * An {@link IZkChildListener} can be registered at a {@link ZkClient} for listening on zk child changes for a given + * path. + * + * Node: Also this listener re-subscribes it watch for the path on each zk event (zk watches are one-timers) is is not + * guaranteed that events on the path are missing (see http://zookeeper.wiki.sourceforge.net/ZooKeeperWatches). An + * implementation of this class should take that into account. + * + */ +public interface IZkChildListener { + + /** + * Called when the children of the given path changed. + * + * @param parentPath + * The parent path + * @param currentChilds + * The children or null if the root node (parent path) was deleted. + * @throws Exception + */ + public void handleChildChange(String parentPath, List currentChilds) throws Exception; +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/IZkConnection.java b/zkclient/src/main/java/org/I0Itec/zkclient/IZkConnection.java new file mode 100644 index 00000000000..28dd89f3f8b --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/IZkConnection.java @@ -0,0 +1,65 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import java.util.List; +import java.util.Map; + +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.Op; +import org.apache.zookeeper.OpResult; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.ZooKeeper.States; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Stat; + +public interface IZkConnection { + + public void connect(Watcher watcher); + + void close() throws InterruptedException; + + public String create(String path, byte[] data, CreateMode mode) throws KeeperException, InterruptedException; + + public String create(String path, byte[] data, List acl, CreateMode mode) throws KeeperException, InterruptedException; + + public void delete(String path) throws InterruptedException, KeeperException; + + boolean exists(final String path, final boolean watch) throws KeeperException, InterruptedException; + + List getChildren(final String path, final boolean watch) throws KeeperException, InterruptedException; + + public byte[] readData(String path, Stat stat, boolean watch) throws KeeperException, InterruptedException; + + public void writeData(String path, byte[] data, int expectedVersion) throws KeeperException, InterruptedException; + + public Stat writeDataReturnStat(String path, byte[] data, int expectedVersion) throws KeeperException, InterruptedException; + + public States getZookeeperState(); + + public long getCreateTime(String path) throws KeeperException, InterruptedException; + + public String getServers(); + + public List multi(Iterable ops) throws KeeperException, InterruptedException; + + public void addAuthInfo(String scheme, byte[] auth); + + public void setAcl(final String path, List acl, int version) throws KeeperException, InterruptedException; + + public Map.Entry, Stat> getAcl(final String path) throws KeeperException, InterruptedException; +} \ No newline at end of file diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/IZkDataListener.java b/zkclient/src/main/java/org/I0Itec/zkclient/IZkDataListener.java new file mode 100644 index 00000000000..eeffbad1bb3 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/IZkDataListener.java @@ -0,0 +1,30 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +/** + * An {@link IZkDataListener} can be registered at a {@link ZkClient} for listening on zk data changes for a given path. + * + * Node: Also this listener re-subscribes it watch for the path on each zk event (zk watches are one-timers) is is not + * guaranteed that events on the path are missing (see http://zookeeper.wiki.sourceforge.net/ZooKeeperWatches). An + * implementation of this class should take that into account. + */ +public interface IZkDataListener { + + public void handleDataChange(String dataPath, Object data) throws Exception; + + public void handleDataDeleted(String dataPath) throws Exception; +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/IZkStateListener.java b/zkclient/src/main/java/org/I0Itec/zkclient/IZkStateListener.java new file mode 100644 index 00000000000..3657dba21cc --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/IZkStateListener.java @@ -0,0 +1,52 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import org.apache.zookeeper.Watcher.Event.KeeperState; + +public interface IZkStateListener { + + /** + * Called when the zookeeper connection state has changed. + * + * @param state + * The new state. + * @throws Exception + * On any error. + */ + public void handleStateChanged(KeeperState state) throws Exception; + + /** + * Called after the zookeeper session has expired and a new session has been created. You would have to re-create + * any ephemeral nodes here. + * + * @throws Exception + * On any error. + */ + public void handleNewSession() throws Exception; + + /** + * Called when a session cannot be re-established. This should be used to implement connection + * failure handling e.g. retry to connect or pass the error up + * + * @param error + * The error that prevents a session from being established + * @throws Exception + * On any error. + */ + public void handleSessionEstablishmentError(final Throwable error) throws Exception; + +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/InMemoryConnection.java b/zkclient/src/main/java/org/I0Itec/zkclient/InMemoryConnection.java new file mode 100644 index 00000000000..4f8c8d4d0cc --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/InMemoryConnection.java @@ -0,0 +1,453 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import java.util.*; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import org.I0Itec.zkclient.exception.ZkException; +import org.I0Itec.zkclient.exception.ZkInterruptedException; +import org.I0Itec.zkclient.exception.ZkNoNodeException; +import org.I0Itec.zkclient.util.ZkPathUtil; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.KeeperException.Code; +import org.apache.zookeeper.Op; +import org.apache.zookeeper.OpResult; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.Watcher.Event.EventType; +import org.apache.zookeeper.Watcher.Event.KeeperState; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.ZooKeeper.States; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Id; +import org.apache.zookeeper.data.Stat; +import org.apache.zookeeper.proto.CheckVersionRequest; +import org.apache.zookeeper.proto.CreateRequest; +import org.apache.zookeeper.proto.DeleteRequest; +import org.apache.zookeeper.proto.SetDataRequest; + +/** + * Emulating a ZooKeeper server with few hash tables. Basically a mock class used for testing. Please avoid using this + * as your ZK in production :) + * + * Note that the addAuth is even more mocked than usual Since we have no authentication provider (i.e. Kerberos) around + * we simply take the auth byte[] and convert it to string to get the Id scheme remains the same + */ +public class InMemoryConnection implements IZkConnection { + + public static class DataAndVersion { + private byte[] _data; + private int _version; + private List _acl; + + public DataAndVersion(byte[] data, int version, List acl) { + _data = data; + _version = version; + _acl = acl; + } + + public DataAndVersion(byte[] data, int version) { + this(data, version, null); + } + + public byte[] getData() { + return _data; + } + + public int getVersion() { + return _version; + } + + public List getAcl() { + return _acl; + } + } + + private Lock _lock = new ReentrantLock(true); + private Map _data = new HashMap(); + private Map _creationTime = new HashMap(); + private List _ids = new ArrayList(); + private final AtomicInteger sequence = new AtomicInteger(0); + + private Set _dataWatches = new HashSet(); + private Set _nodeWatches = new HashSet(); + private EventThread _eventThread; + + private class EventThread extends Thread { + + private Watcher _watcher; + private BlockingQueue _blockingQueue = new LinkedBlockingDeque(); + + public EventThread(Watcher watcher) { + _watcher = watcher; + } + + @Override + public void run() { + try { + while (true) { + _watcher.process(_blockingQueue.take()); + } + } catch (InterruptedException e) { + // stop event thread + } + } + + public void send(WatchedEvent event) { + _blockingQueue.add(event); + } + } + + public InMemoryConnection() { + try { + create("/", null, CreateMode.PERSISTENT); + } catch (KeeperException e) { + throw ZkException.create(e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ZkInterruptedException(e); + } + } + + @Override + public void close() throws InterruptedException { + _lock.lockInterruptibly(); + try { + if (_eventThread != null) { + _eventThread.interrupt(); + _eventThread.join(); + _eventThread = null; + } + } finally { + _lock.unlock(); + } + } + + @Override + public void connect(Watcher watcher) { + _lock.lock(); + try { + if (_eventThread != null) { + throw new IllegalStateException("Already connected."); + } + _eventThread = new EventThread(watcher); + _eventThread.start(); + _eventThread.send(new WatchedEvent(null, KeeperState.SyncConnected, null)); + } finally { + _lock.unlock(); + } + } + + @Override + public String create(String path, byte[] data, List acl, CreateMode mode) throws KeeperException, InterruptedException { + _lock.lock(); + try { + + if (mode.isSequential()) { + final int newSequence = sequence.getAndIncrement(); + path = path + ZkPathUtil.leadingZeros(newSequence, 10); + } + + if (exists(path, false)) { + throw new KeeperException.NodeExistsException(); + } + String parentPath = getParentPath(path); + checkACL(parentPath, ZooDefs.Perms.CREATE); + + _data.put(path, new DataAndVersion(data, 0, acl)); + _creationTime.put(path, System.currentTimeMillis()); + checkWatch(_nodeWatches, path, EventType.NodeCreated); + // we also need to send a child change event for the parent + if (parentPath != null) { + checkWatch(_nodeWatches, parentPath, EventType.NodeChildrenChanged); + } + return path; + } finally { + _lock.unlock(); + } + } + + @Override + public String create(String path, byte[] data, CreateMode mode) throws KeeperException, InterruptedException { + return create(path, data, null, mode); + } + + private String getParentPath(String path) { + int lastIndexOf = path.lastIndexOf("/"); + if (lastIndexOf == -1 || lastIndexOf == 0) { + return null; + } + return path.substring(0, lastIndexOf); + } + + @Override + public void delete(String path) throws InterruptedException, KeeperException { + _lock.lock(); + try { + if (!exists(path, false)) { + throw new KeeperException.NoNodeException(); + } + String parentPath = getParentPath(path); + checkACL(parentPath, ZooDefs.Perms.DELETE); + _data.remove(path); + _creationTime.remove(path); + checkWatch(_nodeWatches, path, EventType.NodeDeleted); + if (parentPath != null) { + checkWatch(_nodeWatches, parentPath, EventType.NodeChildrenChanged); + } + } finally { + _lock.unlock(); + } + } + + @Override + public boolean exists(String path, boolean watch) throws KeeperException, InterruptedException { + _lock.lock(); + try { + if (watch) { + installWatch(_nodeWatches, path); + } + return _data.containsKey(path); + } finally { + _lock.unlock(); + } + } + + private void installWatch(Set watches, String path) { + watches.add(path); + } + + @Override + public List getChildren(String path, boolean watch) throws KeeperException, InterruptedException { + if (!exists(path, false)) { + throw KeeperException.create(Code.NONODE, path); + } + if (exists(path, false) && watch) { + installWatch(_nodeWatches, path); + } + + checkACL(path, ZooDefs.Perms.READ); + ArrayList children = new ArrayList(); + String[] directoryStack = path.split("/"); + Set keySet = _data.keySet(); + + for (String string : keySet) { + if (string.startsWith(path)) { + String[] stack = string.split("/"); + // is one folder level below the one we loockig for and starts + // with path... + if (stack.length == directoryStack.length + 1) { + children.add(stack[stack.length - 1]); + } + } + + } + return children; + } + + @Override + public States getZookeeperState() { + _lock.lock(); + try { + if (_eventThread == null) { + return States.CLOSED; + } + return States.CONNECTED; + } finally { + _lock.unlock(); + } + } + + @Override + public byte[] readData(String path, Stat stat, boolean watch) throws KeeperException, InterruptedException { + if (watch) { + installWatch(_dataWatches, path); + } + _lock.lock(); + try { + DataAndVersion dataAndVersion = _data.get(path); + if (dataAndVersion == null) { + throw new ZkNoNodeException(new KeeperException.NoNodeException()); + } + checkACL(path, ZooDefs.Perms.READ); + byte[] bs = dataAndVersion.getData(); + if (stat != null) + stat.setVersion(dataAndVersion.getVersion()); + return bs; + } finally { + _lock.unlock(); + } + } + + @Override + public void writeData(String path, byte[] data, int expectedVersion) throws KeeperException, InterruptedException { + writeDataReturnStat(path, data, expectedVersion); + } + + @Override + public Stat writeDataReturnStat(String path, byte[] data, int expectedVersion) throws KeeperException, InterruptedException { + int newVersion = -1; + _lock.lock(); + try { + checkWatch(_dataWatches, path, EventType.NodeDataChanged); + if (!exists(path, false)) { + throw new KeeperException.NoNodeException(); + } + checkACL(path, ZooDefs.Perms.WRITE); + newVersion = _data.get(path).getVersion() + 1; + _data.put(path, new DataAndVersion(data, newVersion)); + String parentPath = getParentPath(path); + if (parentPath != null) { + checkWatch(_nodeWatches, parentPath, EventType.NodeChildrenChanged); + } + } finally { + _lock.unlock(); + } + Stat stat = new Stat(); + stat.setVersion(newVersion); + return stat; + } + + private void checkWatch(Set watches, String path, EventType eventType) { + if (watches.contains(path)) { + watches.remove(path); + _eventThread.send(new WatchedEvent(eventType, KeeperState.SyncConnected, path)); + } + } + + @Override + public long getCreateTime(String path) { + Long time = _creationTime.get(path); + if (time == null) { + return -1; + } + return time; + } + + @Override + public String getServers() { + return "mem"; + } + + public List multi(Iterable ops) throws KeeperException, InterruptedException { + List opResults = new ArrayList(); + for (Op op : ops) { + if (Op.Check.class.isAssignableFrom(op.getClass())) { + CheckVersionRequest check = (CheckVersionRequest) op.toRequestRecord(); + exists(check.getPath(), false); + opResults.add(new OpResult.CheckResult()); + } else if (Op.Create.class.isAssignableFrom(op.getClass())) { + CreateRequest create = (CreateRequest) op.toRequestRecord(); + String path = create(create.getPath(), create.getData(), CreateMode.fromFlag(create.getFlags())); + opResults.add(new OpResult.CreateResult(path)); + } else if (Op.Delete.class.isAssignableFrom(op.getClass())) { + DeleteRequest delete = (DeleteRequest) op.toRequestRecord(); + delete(delete.getPath()); + opResults.add(new OpResult.DeleteResult()); + } else if (Op.SetData.class.isAssignableFrom(op.getClass())) { + SetDataRequest setData = (SetDataRequest) op.toRequestRecord(); + writeData(setData.getPath(), setData.getData(), setData.getVersion()); + opResults.add(new OpResult.SetDataResult(null)); + } + } + return opResults; + } + + @Override + public void addAuthInfo(String scheme, byte[] auth) { + _ids.add(new Id(scheme, new String(auth))); + } + + @Override + public void setAcl(String path, List acl, int version) throws KeeperException, InterruptedException { + if (!exists(path, false)) { + throw new KeeperException.NoNodeException(); + } + + DataAndVersion dataAndVersion = _data.get(path); + if(version != dataAndVersion._version) { + throw new KeeperException.BadVersionException(); + } + + checkACL(path, ZooDefs.Perms.ADMIN); + + _lock.lock(); + try { + _data.put(path, new DataAndVersion(dataAndVersion.getData(), dataAndVersion.getVersion() + 1, acl)); + } finally { + _lock.unlock(); + } + } + + @Override + public Map.Entry, Stat> getAcl(String path) throws KeeperException, InterruptedException { + if (!exists(path, false)) { + throw new KeeperException.NoNodeException(); + } + + DataAndVersion dataAndVersion = _data.get(path); + + Stat stat = new Stat(); + stat.setVersion(dataAndVersion.getVersion()); + stat.setCtime(_creationTime.get(path)); + + return new AbstractMap.SimpleEntry, Stat>(dataAndVersion.getAcl(), stat); + } + + /*** + * + * @param path + * - path of znode we are accessing + * @param perm + * - Privileges required for the action + * @throws KeeperException.NoAuthException + */ + private void checkACL(String path, int perm) throws KeeperException.NoAuthException { + DataAndVersion node = _data.get(path); + if (node == null) { + return; + } + List acl = node.getAcl(); + if (acl == null || acl.size() == 0) { + return; + } + for (Id authId : _ids) { + if (authId.getScheme().equals("super")) { + return; + } + } + for (ACL a : acl) { + Id id = a.getId(); + if ((a.getPerms() & perm) != 0) { + if (id.getScheme().equals("world") && id.getId().equals("anyone")) { + return; + } + for (Id authId : _ids) { + if (authId.getScheme().equals(id.getScheme()) && authId.getId().equals(id.getId())) { + return; + } + } + } + } + throw new KeeperException.NoAuthException(); + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/NetworkUtil.java b/zkclient/src/main/java/org/I0Itec/zkclient/NetworkUtil.java new file mode 100644 index 00000000000..a129c15db11 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/NetworkUtil.java @@ -0,0 +1,122 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import java.io.IOException; +import java.net.ConnectException; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.Socket; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Set; + +public class NetworkUtil { + + public final static String OVERWRITE_HOSTNAME_SYSTEM_PROPERTY = "zkclient.hostname.overwritten"; + + public static String[] getLocalHostNames() { + final Set hostNames = new HashSet(); + // we add localhost to this set manually, because if the ip 127.0.0.1 is + // configured with more than one name in the /etc/hosts, only the first + // name + // is returned + hostNames.add("localhost"); + try { + final Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); + for (final Enumeration ifaces = networkInterfaces; ifaces.hasMoreElements();) { + final NetworkInterface iface = ifaces.nextElement(); + InetAddress ia = null; + for (final Enumeration ips = iface.getInetAddresses(); ips.hasMoreElements();) { + ia = ips.nextElement(); + hostNames.add(ia.getCanonicalHostName()); + hostNames.add(ipToString(ia.getAddress())); + } + } + } catch (final SocketException e) { + throw new RuntimeException("unable to retrieve host names of localhost"); + } + return hostNames.toArray(new String[hostNames.size()]); + } + + private static String ipToString(final byte[] bytes) { + final StringBuffer addrStr = new StringBuffer(); + for (int cnt = 0; cnt < bytes.length; cnt++) { + final int uByte = bytes[cnt] < 0 ? bytes[cnt] + 256 : bytes[cnt]; + addrStr.append(uByte); + if (cnt < 3) + addrStr.append('.'); + } + return addrStr.toString(); + } + + public static int hostNamesInList(final String serverList, final String[] hostNames) { + final String[] serverNames = serverList.split(","); + for (int i = 0; i < hostNames.length; i++) { + final String hostname = hostNames[i]; + for (int j = 0; j < serverNames.length; j++) { + final String serverNameAndPort = serverNames[j]; + final String serverName = serverNameAndPort.split(":")[0]; + if (serverName.equalsIgnoreCase(hostname)) { + return j; + } + } + } + return -1; + } + + public static boolean hostNameInArray(final String[] hostNames, final String hostName) { + for (final String name : hostNames) { + if (name.equalsIgnoreCase(hostName)) { + return true; + } + } + return false; + } + + public static boolean isPortFree(int port) { + try { + Socket socket = new Socket("localhost", port); + socket.close(); + return false; + } catch (ConnectException e) { + return true; + } catch (SocketException e) { + if (e.getMessage().equals("Connection reset by peer")) { + return true; + } + throw new RuntimeException(e); + } catch (UnknownHostException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static String getLocalhostName() { + String property = System.getProperty(OVERWRITE_HOSTNAME_SYSTEM_PROPERTY); + if (property != null && property.trim().length() > 0) { + return property; + } + try { + return InetAddress.getLocalHost().getHostName(); + } catch (final UnknownHostException e) { + throw new RuntimeException("unable to retrieve localhost name"); + } + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/ZkClient.java b/zkclient/src/main/java/org/I0Itec/zkclient/ZkClient.java new file mode 100644 index 00000000000..e3ff80994fa --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/ZkClient.java @@ -0,0 +1,1222 @@ +/** + * Copyright 2010 the original author or authors. + *

+ * 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 org.I0Itec.zkclient; + +import org.I0Itec.zkclient.ZkEventThread.ZkEvent; +import org.I0Itec.zkclient.exception.*; +import org.I0Itec.zkclient.serialize.SerializableSerializer; +import org.I0Itec.zkclient.serialize.ZkSerializer; +import org.I0Itec.zkclient.util.ZkPathUtil; +import org.apache.zookeeper.*; +import org.apache.zookeeper.KeeperException.ConnectionLossException; +import org.apache.zookeeper.KeeperException.SessionExpiredException; +import org.apache.zookeeper.Watcher.Event.EventType; +import org.apache.zookeeper.Watcher.Event.KeeperState; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Stat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.security.auth.login.Configuration; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.TimeUnit; + +/** + * Abstracts the interaction with zookeeper and allows permanent (not just one time) watches on nodes in ZooKeeper + */ +public class ZkClient implements Watcher { + + //private final static Logger LOG = Logger.getLogger(ZkClient.class); + private final static Logger LOG = LoggerFactory.getLogger(ZkClient.class); + protected static final String JAVA_LOGIN_CONFIG_PARAM = "java.security.auth.login.config"; + protected static final String ZK_SASL_CLIENT = "zookeeper.sasl.client"; + protected static final String ZK_LOGIN_CONTEXT_NAME_KEY = "zookeeper.sasl.clientconfig"; + + protected final IZkConnection _connection; + protected final long operationRetryTimeoutInMillis; + private final Map> _childListener = new ConcurrentHashMap>(); + private final ConcurrentHashMap> _dataListener = new ConcurrentHashMap>(); + private final Set _stateListener = new CopyOnWriteArraySet(); + private KeeperState _currentState; + private final ZkLock _zkEventLock = new ZkLock(); + private boolean _shutdownTriggered; + private ZkEventThread _eventThread; + // TODO PVo remove this later + private Thread _zookeeperEventThread; + private ZkSerializer _zkSerializer; + private volatile boolean _closed; + private boolean _isZkSaslEnabled; + + public ZkClient(String serverstring) { + this(serverstring, Integer.MAX_VALUE); + } + + public ZkClient(String zkServers, int connectionTimeout) { + this(new ZkConnection(zkServers), connectionTimeout); + } + + public ZkClient(String zkServers, int sessionTimeout, int connectionTimeout) { + this(new ZkConnection(zkServers, sessionTimeout), connectionTimeout); + } + + public ZkClient(String zkServers, int sessionTimeout, int connectionTimeout, ZkSerializer zkSerializer) { + this(new ZkConnection(zkServers, sessionTimeout), connectionTimeout, zkSerializer); + } + + /** + * @param zkServers The Zookeeper servers + * @param sessionTimeout The session timeout in milli seconds + * @param connectionTimeout The connection timeout in milli seconds + * @param zkSerializer The Zookeeper data serializer + * @param operationRetryTimeout Most operations done through this {@link org.I0Itec.zkclient.ZkClient} are retried in cases like + * connection loss with the Zookeeper servers. During such failures, this + * operationRetryTimeout decides the maximum amount of time, in milli seconds, each + * operation is retried. A value lesser than 0 is considered as + * "retry forever until a connection has been reestablished". + */ + public ZkClient(final String zkServers, final int sessionTimeout, final int connectionTimeout, final ZkSerializer zkSerializer, final long operationRetryTimeout) { + this(new ZkConnection(zkServers, sessionTimeout), connectionTimeout, zkSerializer, operationRetryTimeout); + } + + public ZkClient(IZkConnection connection) { + this(connection, Integer.MAX_VALUE); + } + + public ZkClient(IZkConnection connection, int connectionTimeout) { + this(connection, connectionTimeout, new SerializableSerializer()); + } + + public ZkClient(IZkConnection zkConnection, int connectionTimeout, ZkSerializer zkSerializer) { + this(zkConnection, connectionTimeout, zkSerializer, -1); + } + + /** + * @param zkConnection The Zookeeper servers + * @param connectionTimeout The connection timeout in milli seconds + * @param zkSerializer The Zookeeper data serializer + * @param operationRetryTimeout Most operations done through this {@link org.I0Itec.zkclient.ZkClient} are retried in cases like + * connection loss with the Zookeeper servers. During such failures, this + * operationRetryTimeout decides the maximum amount of time, in milli seconds, each + * operation is retried. A value lesser than 0 is considered as + * "retry forever until a connection has been reestablished". + */ + public ZkClient(final IZkConnection zkConnection, final int connectionTimeout, final ZkSerializer zkSerializer, final long operationRetryTimeout) { + if (zkConnection == null) { + throw new NullPointerException("Zookeeper connection is null!"); + } + _connection = zkConnection; + _zkSerializer = zkSerializer; + this.operationRetryTimeoutInMillis = operationRetryTimeout; + _isZkSaslEnabled = isZkSaslEnabled(); + connect(connectionTimeout, this); + } + + public void setZkSerializer(ZkSerializer zkSerializer) { + _zkSerializer = zkSerializer; + } + + public List subscribeChildChanges(String path, IZkChildListener listener) { + synchronized (_childListener) { + Set listeners = _childListener.get(path); + if (listeners == null) { + listeners = new CopyOnWriteArraySet(); + _childListener.put(path, listeners); + } + listeners.add(listener); + } + return watchForChilds(path); + } + + public void unsubscribeChildChanges(String path, IZkChildListener childListener) { + synchronized (_childListener) { + final Set listeners = _childListener.get(path); + if (listeners != null) { + listeners.remove(childListener); + } + } + } + + public void subscribeDataChanges(String path, IZkDataListener listener) { + Set listeners; + synchronized (_dataListener) { + listeners = _dataListener.get(path); + if (listeners == null) { + listeners = new CopyOnWriteArraySet(); + _dataListener.put(path, listeners); + } + listeners.add(listener); + } + watchForData(path); + LOG.debug("Subscribed data changes for " + path); + } + + public void unsubscribeDataChanges(String path, IZkDataListener dataListener) { + synchronized (_dataListener) { + final Set listeners = _dataListener.get(path); + if (listeners != null) { + listeners.remove(dataListener); + } + if (listeners == null || listeners.isEmpty()) { + _dataListener.remove(path); + } + } + } + + public void subscribeStateChanges(final IZkStateListener listener) { + synchronized (_stateListener) { + _stateListener.add(listener); + } + } + + public void unsubscribeStateChanges(IZkStateListener stateListener) { + synchronized (_stateListener) { + _stateListener.remove(stateListener); + } + } + + public void unsubscribeAll() { + synchronized (_childListener) { + _childListener.clear(); + } + synchronized (_dataListener) { + _dataListener.clear(); + } + synchronized (_stateListener) { + _stateListener.clear(); + } + } + + // + + /** + * Create a persistent node. + * + * @param path + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public void createPersistent(String path) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + createPersistent(path, false); + } + + /** + * Create a persistent node and set its ACLs. + * + * @param path + * @param createParents if true all parent dirs are created as well and no {@link ZkNodeExistsException} is thrown in case the + * path already exists + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public void createPersistent(String path, boolean createParents) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + createPersistent(path, createParents, ZooDefs.Ids.OPEN_ACL_UNSAFE); + } + + /** + * Create a persistent node and set its ACLs. + * + * @param path + * @param acl List of ACL permissions to assign to the node + * @param createParents if true all parent dirs are created as well and no {@link ZkNodeExistsException} is thrown in case the + * path already exists + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public void createPersistent(String path, boolean createParents, List acl) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + try { + create(path, null, acl, CreateMode.PERSISTENT); + } catch (ZkNodeExistsException e) { + if (!createParents) { + throw e; + } + } catch (ZkNoNodeException e) { + if (!createParents) { + throw e; + } + String parentDir = path.substring(0, path.lastIndexOf('/')); + createPersistent(parentDir, createParents, acl); + createPersistent(path, createParents, acl); + } + } + + /** + * Sets the acl on path + * + * @param path + * @param acl List of ACL permissions to assign to the path. + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public void setAcl(final String path, final List acl) throws ZkException { + if (path == null) { + throw new NullPointerException("Missing value for path"); + } + + if (acl == null || acl.size() == 0) { + throw new NullPointerException("Missing value for ACL"); + } + + if (!exists(path)) { + throw new RuntimeException("trying to set acls on non existing node " + path); + } + + retryUntilConnected(new Callable() { + @Override + public Void call() throws Exception { + Stat stat = new Stat(); + _connection.readData(path, stat, false); + _connection.setAcl(path, acl, stat.getAversion()); + return null; + } + }); + } + + /** + * Gets the acl on path + * + * @param path + * @return an entry instance with key = list of acls on node and value = stats. + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public Map.Entry, Stat> getAcl(final String path) throws ZkException { + if (path == null) { + throw new NullPointerException("Missing value for path"); + } + + if (!exists(path)) { + throw new RuntimeException("trying to get acls on non existing node " + path); + } + + return retryUntilConnected(new Callable, Stat>>() { + @Override + public Map.Entry, Stat> call() throws Exception { + return _connection.getAcl(path); + } + }); + } + + /** + * Create a persistent node. + * + * @param path + * @param data + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public void createPersistent(String path, Object data) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + create(path, data, CreateMode.PERSISTENT); + } + + /** + * Create a persistent node. + * + * @param path + * @param data + * @param acl + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public void createPersistent(String path, Object data, List acl) { + create(path, data, acl, CreateMode.PERSISTENT); + } + + /** + * Create a persistent, sequental node. + * + * @param path + * @param data + * @return create node's path + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public String createPersistentSequential(String path, Object data) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + return create(path, data, CreateMode.PERSISTENT_SEQUENTIAL); + } + + /** + * Create a persistent, sequential node and set its ACL. + * + * @param path + * @param acl + * @param data + * @return create node's path + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public String createPersistentSequential(String path, Object data, List acl) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + return create(path, data, acl, CreateMode.PERSISTENT_SEQUENTIAL); + } + + /** + * Create an ephemeral node. + * + * @param path + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public void createEphemeral(final String path) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + create(path, null, CreateMode.EPHEMERAL); + } + + /** + * Create an ephemeral node and set its ACL. + * + * @param path + * @param acl + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public void createEphemeral(final String path, final List acl) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + create(path, null, acl, CreateMode.EPHEMERAL); + } + + /** + * Create a node. + * + * @param path + * @param data + * @param mode + * @return create node's path + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public String create(final String path, Object data, final CreateMode mode) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + return create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, mode); + } + + /** + * Create a node with ACL. + * + * @param path + * @param data + * @param acl + * @param mode + * @return create node's path + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public String create(final String path, Object data, final List acl, final CreateMode mode) { + if (path == null) { + throw new NullPointerException("Missing value for path"); + } + if (acl == null || acl.size() == 0) { + throw new NullPointerException("Missing value for ACL"); + } + final byte[] bytes = data == null ? null : serialize(data); + + return retryUntilConnected(new Callable() { + @Override + public String call() throws Exception { + return _connection.create(path, bytes, acl, mode); + } + }); + + } + + /** + * Create an ephemeral node. + * + * @param path + * @param data + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public void createEphemeral(final String path, final Object data) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + create(path, data, CreateMode.EPHEMERAL); + } + + /** + * Create an ephemeral node. + * + * @param path + * @param data + * @param acl + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public void createEphemeral(final String path, final Object data, final List acl) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + create(path, data, acl, CreateMode.EPHEMERAL); + } + + /** + * Create an ephemeral, sequential node. + * + * @param path + * @param data + * @return created path + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public String createEphemeralSequential(final String path, final Object data) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + return create(path, data, CreateMode.EPHEMERAL_SEQUENTIAL); + } + + /** + * Create an ephemeral, sequential node with ACL. + * + * @param path + * @param data + * @param acl + * @return created path + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs + */ + public String createEphemeralSequential(final String path, final Object data, final List acl) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + return create(path, data, acl, CreateMode.EPHEMERAL_SEQUENTIAL); + } + + @Override + public void process(WatchedEvent event) { + LOG.debug("Received event: " + event); + _zookeeperEventThread = Thread.currentThread(); + + boolean stateChanged = event.getPath() == null; + boolean znodeChanged = event.getPath() != null; + boolean dataChanged = event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated + || event.getType() == EventType.NodeChildrenChanged; + + getEventLock().lock(); + try { + + // We might have to install child change event listener if a new node was created + if (getShutdownTrigger()) { + LOG.debug("ignoring event '{" + event.getType() + " | " + event.getPath() + "}' since shutdown triggered"); + return; + } + if (stateChanged) { + processStateChanged(event); + } + if (dataChanged) { + processDataOrChildChange(event); + } + } finally { + if (stateChanged) { + getEventLock().getStateChangedCondition().signalAll(); + + // If the session expired we have to signal all conditions, because watches might have been removed and + // there is no guarantee that those + // conditions will be signaled at all after an Expired event + // TODO PVo write a test for this + if (event.getState() == KeeperState.Expired) { + getEventLock().getZNodeEventCondition().signalAll(); + getEventLock().getDataChangedCondition().signalAll(); + // We also have to notify all listeners that something might have changed + fireAllEvents(); + } + } + if (znodeChanged) { + getEventLock().getZNodeEventCondition().signalAll(); + } + if (dataChanged) { + getEventLock().getDataChangedCondition().signalAll(); + } + getEventLock().unlock(); + LOG.debug("Leaving process event"); + } + } + + private void fireAllEvents() { + for (Entry> entry : _childListener.entrySet()) { + fireChildChangedEvents(entry.getKey(), entry.getValue()); + } + for (Entry> entry : _dataListener.entrySet()) { + fireDataChangedEvents(entry.getKey(), entry.getValue()); + } + } + + public List getChildren(String path) { + return getChildren(path, hasListeners(path)); + } + + protected List getChildren(final String path, final boolean watch) { + return retryUntilConnected(new Callable>() { + @Override + public List call() throws Exception { + return _connection.getChildren(path, watch); + } + }); + } + + /** + * Counts number of children for the given path. + * + * @param path + * @return number of children or 0 if path does not exist. + */ + public int countChildren(String path) { + try { + return getChildren(path).size(); + } catch (ZkNoNodeException e) { + return 0; + } + } + + protected boolean exists(final String path, final boolean watch) { + return retryUntilConnected(new Callable() { + @Override + public Boolean call() throws Exception { + return _connection.exists(path, watch); + } + }); + } + + public boolean exists(final String path) { + return exists(path, hasListeners(path)); + } + + private void processStateChanged(WatchedEvent event) { + LOG.info("zookeeper state changed (" + event.getState() + ")"); + setCurrentState(event.getState()); + if (getShutdownTrigger()) { + return; + } + fireStateChangedEvent(event.getState()); + if (event.getState() == KeeperState.Expired) { + try { + reconnect(); + fireNewSessionEvents(); + } catch (final Exception e) { + LOG.info("Unable to re-establish connection. Notifying consumer of the following exception: ", e); + fireSessionEstablishmentError(e); + } + } + } + + private void fireNewSessionEvents() { + for (final IZkStateListener stateListener : _stateListener) { + _eventThread.send(new ZkEvent("New session event sent to " + stateListener) { + + @Override + public void run() throws Exception { + stateListener.handleNewSession(); + } + }); + } + } + + private void fireStateChangedEvent(final KeeperState state) { + for (final IZkStateListener stateListener : _stateListener) { + _eventThread.send(new ZkEvent("State changed to " + state + " sent to " + stateListener) { + + @Override + public void run() throws Exception { + stateListener.handleStateChanged(state); + } + }); + } + } + + private void fireSessionEstablishmentError(final Throwable error) { + for (final IZkStateListener stateListener : _stateListener) { + _eventThread.send(new ZkEvent("Session establishment error(" + error + ") sent to " + stateListener) { + + @Override + public void run() throws Exception { + stateListener.handleSessionEstablishmentError(error); + } + }); + } + } + + private boolean hasListeners(String path) { + Set dataListeners = _dataListener.get(path); + if (dataListeners != null && dataListeners.size() > 0) { + return true; + } + Set childListeners = _childListener.get(path); + if (childListeners != null && childListeners.size() > 0) { + return true; + } + return false; + } + + public boolean deleteRecursive(String path) { + List children; + try { + children = getChildren(path, false); + } catch (ZkNoNodeException e) { + return true; + } + + for (String subPath : children) { + if (!deleteRecursive(path + "/" + subPath)) { + return false; + } + } + + return delete(path); + } + + private void processDataOrChildChange(WatchedEvent event) { + final String path = event.getPath(); + + if (event.getType() == EventType.NodeChildrenChanged || event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeDeleted) { + Set childListeners = _childListener.get(path); + if (childListeners != null && !childListeners.isEmpty()) { + fireChildChangedEvents(path, childListeners); + } + } + + if (event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated) { + Set listeners = _dataListener.get(path); + if (listeners != null && !listeners.isEmpty()) { + fireDataChangedEvents(event.getPath(), listeners); + } + } + } + + private void fireDataChangedEvents(final String path, Set listeners) { + for (final IZkDataListener listener : listeners) { + _eventThread.send(new ZkEvent("Data of " + path + " changed sent to " + listener) { + + @Override + public void run() throws Exception { + // reinstall watch + exists(path, true); + try { + Object data = readData(path, null, true); + listener.handleDataChange(path, data); + } catch (ZkNoNodeException e) { + listener.handleDataDeleted(path); + } + } + }); + } + } + + private void fireChildChangedEvents(final String path, Set childListeners) { + try { + // reinstall the watch + for (final IZkChildListener listener : childListeners) { + _eventThread.send(new ZkEvent("Children of " + path + " changed sent to " + listener) { + + @Override + public void run() throws Exception { + try { + // if the node doesn't exist we should listen for the root node to reappear + exists(path); + List children = getChildren(path); + listener.handleChildChange(path, children); + } catch (ZkNoNodeException e) { + listener.handleChildChange(path, null); + } + } + }); + } + } catch (Exception e) { + LOG.error("Failed to fire child changed event. Unable to getChildren. ", e); + } + } + + public boolean waitUntilExists(String path, TimeUnit timeUnit, long time) throws ZkInterruptedException { + Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time)); + LOG.debug("Waiting until znode '" + path + "' becomes available."); + if (exists(path)) { + return true; + } + acquireEventLock(); + try { + while (!exists(path, true)) { + boolean gotSignal = getEventLock().getZNodeEventCondition().awaitUntil(timeout); + if (!gotSignal) { + return false; + } + } + return true; + } catch (InterruptedException e) { + throw new ZkInterruptedException(e); + } finally { + getEventLock().unlock(); + } + } + + protected Set getDataListener(String path) { + return _dataListener.get(path); + } + + public void showFolders(OutputStream output) { + try { + output.write(ZkPathUtil.toString(this).getBytes()); + } catch (final IOException e) { + e.printStackTrace(); + } + } + + private boolean isZkSaslEnabled() { + boolean isSecurityEnabled = false; + boolean zkSaslEnabled = Boolean.parseBoolean(System.getProperty(ZK_SASL_CLIENT, "true")); + String zkLoginContextName = System.getProperty(ZK_LOGIN_CONTEXT_NAME_KEY, "Client"); + + if (!zkSaslEnabled) { + LOG.warn("Client SASL has been explicitly disabled with " + ZK_SASL_CLIENT); + return false; + } + + String loginConfigFile = System.getProperty(JAVA_LOGIN_CONFIG_PARAM); + if (loginConfigFile != null && loginConfigFile.length() > 0) { + LOG.info("JAAS File name: " + loginConfigFile); + File configFile = new File(loginConfigFile); + if (!configFile.canRead()) { + throw new IllegalArgumentException("File " + loginConfigFile + "cannot be read."); + } + + try { + Configuration loginConf = Configuration.getConfiguration(); + isSecurityEnabled = loginConf.getAppConfigurationEntry(zkLoginContextName) != null; + } catch (Exception e) { + throw new ZkException(e); + } + } + return isSecurityEnabled; + } + + public void waitUntilConnected() throws ZkInterruptedException { + waitUntilConnected(Integer.MAX_VALUE, TimeUnit.MILLISECONDS); + } + + public boolean waitUntilConnected(long time, TimeUnit timeUnit) throws ZkInterruptedException { + if (_isZkSaslEnabled) { + return waitForKeeperState(KeeperState.SaslAuthenticated, time, timeUnit); + } else { + return waitForKeeperState(KeeperState.SyncConnected, time, timeUnit); + } + } + + public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit) throws ZkInterruptedException { + if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) { + throw new IllegalArgumentException("Must not be done in the zookeeper event thread."); + } + Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time)); + + LOG.info("Waiting for keeper state " + keeperState); + acquireEventLock(); + try { + boolean stillWaiting = true; + while (_currentState != keeperState) { + if (!stillWaiting) { + return false; + } + stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeout); + } + LOG.debug("State is " + _currentState); + return true; + } catch (InterruptedException e) { + throw new ZkInterruptedException(e); + } finally { + getEventLock().unlock(); + } + } + + private void acquireEventLock() { + try { + getEventLock().lockInterruptibly(); + } catch (InterruptedException e) { + throw new ZkInterruptedException(e); + } + } + + /** + * @param + * @param callable + * @return result of Callable + * @throws ZkInterruptedException if operation was interrupted, or a required reconnection got interrupted + * @throws IllegalArgumentException if called from anything except the ZooKeeper event thread + * @throws ZkException if any ZooKeeper exception occurred + * @throws RuntimeException if any other exception occurs from invoking the Callable + */ + public T retryUntilConnected(Callable callable) throws ZkInterruptedException, IllegalArgumentException, ZkException, RuntimeException { + if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) { + throw new IllegalArgumentException("Must not be done in the zookeeper event thread."); + } + final long operationStartTime = System.currentTimeMillis(); + while (true) { + if (_closed) { + throw new IllegalStateException("ZkClient already closed!"); + } + try { + return callable.call(); + } catch (ConnectionLossException e) { + // we give the event thread some time to update the status to 'Disconnected' + Thread.yield(); + waitForRetry(); + } catch (SessionExpiredException e) { + // we give the event thread some time to update the status to 'Expired' + Thread.yield(); + waitForRetry(); + } catch (KeeperException e) { + throw ZkException.create(e); + } catch (InterruptedException e) { + throw new ZkInterruptedException(e); + } catch (Exception e) { + throw ExceptionUtil.convertToRuntimeException(e); + } + // before attempting a retry, check whether retry timeout has elapsed + if (this.operationRetryTimeoutInMillis > -1 && (System.currentTimeMillis() - operationStartTime) >= this.operationRetryTimeoutInMillis) { + throw new ZkTimeoutException("Operation cannot be retried because of retry timeout (" + this.operationRetryTimeoutInMillis + " milli seconds)"); + } + } + } + + private void waitForRetry() { + if (this.operationRetryTimeoutInMillis < 0) { + this.waitUntilConnected(); + return; + } + this.waitUntilConnected(this.operationRetryTimeoutInMillis, TimeUnit.MILLISECONDS); + } + + public void setCurrentState(KeeperState currentState) { + getEventLock().lock(); + try { + _currentState = currentState; + } finally { + getEventLock().unlock(); + } + } + + /** + * Returns a mutex all zookeeper events are synchronized aginst. So in case you need to do something without getting + * any zookeeper event interruption synchronize against this mutex. Also all threads waiting on this mutex object + * will be notified on an event. + * + * @return the mutex. + */ + public ZkLock getEventLock() { + return _zkEventLock; + } + + public boolean delete(final String path) { + try { + retryUntilConnected(new Callable() { + + @Override + public Object call() throws Exception { + _connection.delete(path); + return null; + } + }); + + return true; + } catch (ZkNoNodeException e) { + return false; + } + } + + private byte[] serialize(Object data) { + return _zkSerializer.serialize(data); + } + + @SuppressWarnings("unchecked") + private T derializable(byte[] data) { + if (data == null) { + return null; + } + return (T) _zkSerializer.deserialize(data); + } + + @SuppressWarnings("unchecked") + public T readData(String path) { + return (T) readData(path, false); + } + + @SuppressWarnings("unchecked") + public T readData(String path, boolean returnNullIfPathNotExists) { + T data = null; + try { + data = (T) readData(path, null); + } catch (ZkNoNodeException e) { + if (!returnNullIfPathNotExists) { + throw e; + } + } + return data; + } + + @SuppressWarnings("unchecked") + public T readData(String path, Stat stat) { + return (T) readData(path, stat, hasListeners(path)); + } + + @SuppressWarnings("unchecked") + protected T readData(final String path, final Stat stat, final boolean watch) { + byte[] data = retryUntilConnected(new Callable() { + + @Override + public byte[] call() throws Exception { + return _connection.readData(path, stat, watch); + } + }); + return (T) derializable(data); + } + + public void writeData(String path, Object object) { + writeData(path, object, -1); + } + + /** + * Updates data of an existing znode. The current content of the znode is passed to the {@link DataUpdater} that is + * passed into this method, which returns the new content. The new content is only written back to ZooKeeper if + * nobody has modified the given znode in between. If a concurrent change has been detected the new data of the + * znode is passed to the updater once again until the new contents can be successfully written back to ZooKeeper. + * + * @param + * @param path The path of the znode. + * @param updater Updater that creates the new contents. + */ + @SuppressWarnings("unchecked") + public void updateDataSerialized(String path, DataUpdater updater) { + Stat stat = new Stat(); + boolean retry; + do { + retry = false; + try { + T oldData = (T) readData(path, stat); + T newData = updater.update(oldData); + writeData(path, newData, stat.getVersion()); + } catch (ZkBadVersionException e) { + retry = true; + } + } while (retry); + } + + public void writeData(final String path, Object datat, final int expectedVersion) { + writeDataReturnStat(path, datat, expectedVersion); + } + + public Stat writeDataReturnStat(final String path, Object datat, final int expectedVersion) { + final byte[] data = serialize(datat); + return (Stat) retryUntilConnected(new Callable() { + + @Override + public Object call() throws Exception { + Stat stat = _connection.writeDataReturnStat(path, data, expectedVersion); + return stat; + } + }); + } + + public void watchForData(final String path) { + retryUntilConnected(new Callable() { + @Override + public Object call() throws Exception { + _connection.exists(path, true); + return null; + } + }); + } + + /** + * Installs a child watch for the given path. + * + * @param path + * @return the current children of the path or null if the zk node with the given path doesn't exist. + */ + public List watchForChilds(final String path) { + if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) { + throw new IllegalArgumentException("Must not be done in the zookeeper event thread."); + } + return retryUntilConnected(new Callable>() { + @Override + public List call() throws Exception { + exists(path, true); + try { + return getChildren(path, true); + } catch (ZkNoNodeException e) { + // ignore, the "exists" watch will listen for the parent node to appear + } + return null; + } + }); + } + + /** + * Add authentication information to the connection. This will be used to identify the user and check access to + * nodes protected by ACLs + * + * @param scheme + * @param auth + */ + public void addAuthInfo(final String scheme, final byte[] auth) { + retryUntilConnected(new Callable() { + @Override + public Object call() throws Exception { + _connection.addAuthInfo(scheme, auth); + return null; + } + }); + } + + /** + * Connect to ZooKeeper. + * + * @param maxMsToWaitUntilConnected + * @param watcher + * @throws ZkInterruptedException if the connection timed out due to thread interruption + * @throws ZkTimeoutException if the connection timed out + * @throws IllegalStateException if the connection timed out due to thread interruption + */ + public void connect(final long maxMsToWaitUntilConnected, Watcher watcher) throws ZkInterruptedException, ZkTimeoutException, IllegalStateException { + boolean started = false; + acquireEventLock(); + try { + setShutdownTrigger(false); + _eventThread = new ZkEventThread(_connection.getServers()); + _eventThread.start(); + _connection.connect(watcher); + + LOG.debug("Awaiting connection to Zookeeper server"); + boolean waitSuccessful = waitUntilConnected(maxMsToWaitUntilConnected, TimeUnit.MILLISECONDS); + if (!waitSuccessful) { + throw new ZkTimeoutException("Unable to connect to zookeeper server within timeout: " + maxMsToWaitUntilConnected); + } + started = true; + } finally { + getEventLock().unlock(); + + // we should close the zookeeper instance, otherwise it would keep + // on trying to connect + if (!started) { + close(); + } + } + } + + public long getCreationTime(String path) { + acquireEventLock(); + try { + return _connection.getCreateTime(path); + } catch (KeeperException e) { + throw ZkException.create(e); + } catch (InterruptedException e) { + throw new ZkInterruptedException(e); + } finally { + getEventLock().unlock(); + } + } + + /** + * Close the client. + * + * @throws ZkInterruptedException + */ + public void close() throws ZkInterruptedException { + if (_closed) { + return; + } + LOG.debug("Closing ZkClient..."); + getEventLock().lock(); + try { + setShutdownTrigger(true); + _eventThread.interrupt(); + _eventThread.join(2000); + _connection.close(); + _closed = true; + } catch (InterruptedException e) { + throw new ZkInterruptedException(e); + } finally { + getEventLock().unlock(); + } + LOG.debug("Closing ZkClient...done"); + } + + private void reconnect() { + getEventLock().lock(); + try { + _connection.close(); + _connection.connect(this); + } catch (InterruptedException e) { + throw new ZkInterruptedException(e); + } finally { + getEventLock().unlock(); + } + } + + public void setShutdownTrigger(boolean triggerState) { + _shutdownTriggered = triggerState; + } + + public boolean getShutdownTrigger() { + return _shutdownTriggered; + } + + public int numberOfListeners() { + int listeners = 0; + for (Set childListeners : _childListener.values()) { + listeners += childListeners.size(); + } + for (Set dataListeners : _dataListener.values()) { + listeners += dataListeners.size(); + } + listeners += _stateListener.size(); + + return listeners; + } + + public List multi(final Iterable ops) throws ZkException { + if (ops == null) { + throw new NullPointerException("ops must not be null."); + } + + return retryUntilConnected(new Callable>() { + + @Override + public List call() throws Exception { + return _connection.multi(ops); + } + }); + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/ZkConnection.java b/zkclient/src/main/java/org/I0Itec/zkclient/ZkConnection.java new file mode 100644 index 00000000000..7a3bc2ee8be --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/ZkConnection.java @@ -0,0 +1,177 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import org.I0Itec.zkclient.exception.ZkException; +import org.apache.zookeeper.*; +import org.apache.zookeeper.ZooDefs.Ids; +import org.apache.zookeeper.ZooKeeper.States; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Stat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.util.AbstractMap.SimpleEntry; +import java.util.List; +import java.util.Map; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +public class ZkConnection implements IZkConnection { + + //private static final Logger LOG = Logger.getLogger(ZkConnection.class); + + private static final Logger LOG = LoggerFactory.getLogger(ZkConnection.class); + /** It is recommended to use quite large sessions timeouts for ZooKeeper. */ + private static final int DEFAULT_SESSION_TIMEOUT = 30000; + + private ZooKeeper _zk = null; + private Lock _zookeeperLock = new ReentrantLock(); + + private final String _servers; + private final int _sessionTimeOut; + + public ZkConnection(String zkServers) { + this(zkServers, DEFAULT_SESSION_TIMEOUT); + } + + public ZkConnection(String zkServers, int sessionTimeOut) { + _servers = zkServers; + _sessionTimeOut = sessionTimeOut; + } + + @Override + public void connect(Watcher watcher) { + _zookeeperLock.lock(); + try { + if (_zk != null) { + throw new IllegalStateException("zk client has already been started"); + } + try { + LOG.debug("Creating new ZookKeeper instance to connect to " + _servers + "."); + _zk = new ZooKeeper(_servers, _sessionTimeOut, watcher); + } catch (IOException e) { + throw new ZkException("Unable to connect to " + _servers, e); + } + } finally { + _zookeeperLock.unlock(); + } + } + + @Override + public void close() throws InterruptedException { + _zookeeperLock.lock(); + try { + if (_zk != null) { + LOG.debug("Closing ZooKeeper connected to " + _servers); + _zk.close(); + _zk = null; + } + } finally { + _zookeeperLock.unlock(); + } + } + + @Override + public String create(String path, byte[] data, CreateMode mode) throws KeeperException, InterruptedException { + return _zk.create(path, data, Ids.OPEN_ACL_UNSAFE, mode); + } + + @Override + public String create(String path, byte[] data, List acl, CreateMode mode) throws KeeperException, InterruptedException { + return _zk.create(path, data, acl, mode); + } + + @Override + public void delete(String path) throws InterruptedException, KeeperException { + _zk.delete(path, -1); + } + + @Override + public boolean exists(String path, boolean watch) throws KeeperException, InterruptedException { + return _zk.exists(path, watch) != null; + } + + @Override + public List getChildren(final String path, final boolean watch) throws KeeperException, InterruptedException { + return _zk.getChildren(path, watch); + } + + @Override + public byte[] readData(String path, Stat stat, boolean watch) throws KeeperException, InterruptedException { + return _zk.getData(path, watch, stat); + } + + public void writeData(String path, byte[] data) throws KeeperException, InterruptedException { + writeData(path, data, -1); + } + + @Override + public void writeData(String path, byte[] data, int version) throws KeeperException, InterruptedException { + _zk.setData(path, data, version); + } + + @Override + public Stat writeDataReturnStat(String path, byte[] data, int version) throws KeeperException, InterruptedException { + return _zk.setData(path, data, version); + } + + @Override + public States getZookeeperState() { + return _zk != null ? _zk.getState() : null; + } + + public ZooKeeper getZookeeper() { + return _zk; + } + + @Override + public long getCreateTime(String path) throws KeeperException, InterruptedException { + Stat stat = _zk.exists(path, false); + if (stat != null) { + return stat.getCtime(); + } + return -1; + } + + @Override + public String getServers() { + return _servers; + } + + @Override + public List multi(Iterable ops) throws KeeperException, InterruptedException { + return _zk.multi(ops); + } + + @Override + public void addAuthInfo(String scheme, byte[] auth) { + _zk.addAuthInfo(scheme, auth); + } + + @Override + public void setAcl(String path, List acl, int version) throws KeeperException, InterruptedException { + _zk.setACL(path, acl, version); + } + + @Override + public Map.Entry, Stat> getAcl(String path) throws KeeperException, InterruptedException { + Stat stat = new Stat(); + List acl = _zk.getACL(path, stat); + return new SimpleEntry(acl, stat); + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/ZkEventThread.java b/zkclient/src/main/java/org/I0Itec/zkclient/ZkEventThread.java new file mode 100644 index 00000000000..03b07616139 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/ZkEventThread.java @@ -0,0 +1,96 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import org.I0Itec.zkclient.exception.ZkInterruptedException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.atomic.AtomicInteger; + + +/** + * All listeners registered at the {@link ZkClient} will be notified from this event thread. This is to prevent + * dead-lock situations. The {@link ZkClient} pulls some information out of the {@link ZooKeeper} events to signal + * {@link ZkLock} conditions. Re-using the {@link ZooKeeper} event thread to also notify {@link ZkClient} listeners, + * would stop the ZkClient from receiving events from {@link ZooKeeper} as soon as one of the listeners blocks (because + * it is waiting for something). {@link ZkClient} would then for instance not be able to maintain it's connection state + * anymore. + */ +class ZkEventThread extends Thread { + + //private static final Logger LOG = Logger.getLogger(ZkEventThread.class); + + private static final Logger LOG = LoggerFactory.getLogger(ZkEventThread.class); + + private BlockingQueue _events = new LinkedBlockingQueue(); + + private static AtomicInteger _eventId = new AtomicInteger(0); + + static abstract class ZkEvent { + + private String _description; + + public ZkEvent(String description) { + _description = description; + } + + public abstract void run() throws Exception; + + @Override + public String toString() { + return "ZkEvent[" + _description + "]"; + } + } + + ZkEventThread(String name) { + setDaemon(true); + setName("ZkClient-EventThread-" + getId() + "-" + name); + } + + @Override + public void run() { + LOG.info("Starting ZkClient event thread."); + try { + while (!isInterrupted()) { + ZkEvent zkEvent = _events.take(); + int eventId = _eventId.incrementAndGet(); + LOG.debug("Delivering event #" + eventId + " " + zkEvent); + try { + zkEvent.run(); + } catch (InterruptedException e) { + interrupt(); + } catch (ZkInterruptedException e) { + interrupt(); + } catch (Throwable e) { + LOG.error("Error handling event " + zkEvent, e); + } + LOG.debug("Delivering event #" + eventId + " done"); + } + } catch (InterruptedException e) { + LOG.info("Terminate ZkClient event thread."); + } + } + + public void send(ZkEvent event) { + if (!isInterrupted()) { + LOG.debug("New event: " + event); + _events.add(event); + } + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/ZkLock.java b/zkclient/src/main/java/org/I0Itec/zkclient/ZkLock.java new file mode 100644 index 00000000000..ad20b39752e --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/ZkLock.java @@ -0,0 +1,56 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; + +public class ZkLock extends ReentrantLock { + + private static final long serialVersionUID = 1L; + + private Condition _dataChangedCondition = newCondition(); + private Condition _stateChangedCondition = newCondition(); + private Condition _zNodeEventCondition = newCondition(); + + /** + * This condition will be signaled if a zookeeper event was processed and the event contains a data/child change. + * + * @return the condition. + */ + public Condition getDataChangedCondition() { + return _dataChangedCondition; + } + + /** + * This condition will be signaled if a zookeeper event was processed and the event contains a state change + * (connected, disconnected, session expired, etc ...). + * + * @return the condition. + */ + public Condition getStateChangedCondition() { + return _stateChangedCondition; + } + + /** + * This condition will be signaled if any znode related zookeeper event was received. + * + * @return the condition. + */ + public Condition getZNodeEventCondition() { + return _zNodeEventCondition; + } +} \ No newline at end of file diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/ZkServer.java b/zkclient/src/main/java/org/I0Itec/zkclient/ZkServer.java new file mode 100644 index 00000000000..21612471b64 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/ZkServer.java @@ -0,0 +1,182 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import org.I0Itec.zkclient.exception.ZkException; +import org.I0Itec.zkclient.exception.ZkInterruptedException; +import org.apache.zookeeper.server.NIOServerCnxnFactory; +import org.apache.zookeeper.server.ZooKeeperServer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import java.io.File; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.Arrays; + +public class ZkServer { + + //private final static Logger LOG = Logger.getLogger(ZkServer.class); + private final static Logger LOG = LoggerFactory.getLogger(ZkServer.class); + + public static final int DEFAULT_PORT = 2181; + public static final int DEFAULT_TICK_TIME = 5000; + public static final int DEFAULT_MIN_SESSION_TIMEOUT = 2 * DEFAULT_TICK_TIME; + + private String _dataDir; + private String _logDir; + + private IDefaultNameSpace _defaultNameSpace; + + private ZooKeeperServer _zk; + private NIOServerCnxnFactory _nioFactory; + private ZkClient _zkClient; + private int _port; + private int _tickTime; + private int _minSessionTimeout; + + public ZkServer(String dataDir, String logDir, IDefaultNameSpace defaultNameSpace) { + this(dataDir, logDir, defaultNameSpace, DEFAULT_PORT); + } + + public ZkServer(String dataDir, String logDir, IDefaultNameSpace defaultNameSpace, int port) { + this(dataDir, logDir, defaultNameSpace, port, DEFAULT_TICK_TIME); + } + + public ZkServer(String dataDir, String logDir, IDefaultNameSpace defaultNameSpace, int port, int tickTime) { + this(dataDir, logDir, defaultNameSpace, port, tickTime, DEFAULT_MIN_SESSION_TIMEOUT); + } + + public ZkServer(String dataDir, String logDir, IDefaultNameSpace defaultNameSpace, int port, int tickTime, int minSessionTimeout) { + _dataDir = dataDir; + _logDir = logDir; + _defaultNameSpace = defaultNameSpace; + _port = port; + _tickTime = tickTime; + _minSessionTimeout = minSessionTimeout; + } + + public int getPort() { + return _port; + } + + @PostConstruct + public void start() { + final String[] localHostNames = NetworkUtil.getLocalHostNames(); + String names = ""; + for (int i = 0; i < localHostNames.length; i++) { + final String name = localHostNames[i]; + names += " " + name; + if (i + 1 != localHostNames.length) { + names += ","; + } + } + LOG.info("Starting ZkServer on: [" + names + "] port " + _port + "..."); + try { + startZooKeeperServer(); + _zkClient = new ZkClient("localhost:" + _port, 10000); + _defaultNameSpace.createDefaultNameSpace(_zkClient); + } catch (RuntimeException e) { + shutdown(); + throw e; + } + } + + private void startZooKeeperServer() { + final String[] localhostHostNames = NetworkUtil.getLocalHostNames(); + final String servers = "localhost:" + _port; + // check if this server needs to start a _client server. + int pos = -1; + LOG.debug("check if hostNames " + servers + " is in list: " + Arrays.asList(localhostHostNames)); + if ((pos = NetworkUtil.hostNamesInList(servers, localhostHostNames)) != -1) { + // yes this server needs to start a zookeeper server + final String[] hosts = servers.split(","); + final String[] hostSplitted = hosts[pos].split(":"); + int port = _port; + if (hostSplitted.length > 1) { + port = Integer.parseInt(hostSplitted[1]); + } + // check if this machine is already something running.. + if (NetworkUtil.isPortFree(port)) { + final File dataDir = new File(_dataDir); + final File dataLogDir = new File(_logDir); + dataDir.mkdirs(); + dataLogDir.mkdirs(); + + if (hosts.length > 1) { + // multiple zk servers + LOG.info("Start distributed zookeeper server..."); + throw new IllegalArgumentException("Unable to start distributed zookeeper server"); + } + // single zk server + LOG.info("Start single zookeeper server..."); + LOG.info("data dir: " + dataDir.getAbsolutePath()); + LOG.info("data log dir: " + dataLogDir.getAbsolutePath()); + LOG.info("JAAS login file: " + System.getProperty("java.security.auth.login.config", "none")); + startSingleZkServer(_tickTime, dataDir, dataLogDir, port); + } else { + throw new IllegalStateException("Zookeeper port " + port + " was already in use. Running in single machine mode?"); + } + } + } + + private void startSingleZkServer(final int tickTime, final File dataDir, final File dataLogDir, final int port) { + try { + _zk = new ZooKeeperServer(dataDir, dataLogDir, tickTime); + _zk.setMinSessionTimeout(_minSessionTimeout); + _nioFactory = new NIOServerCnxnFactory(); + int maxClientConnections = 0; // 0 means unlimited + _nioFactory.configure(new InetSocketAddress(port), maxClientConnections); + _nioFactory.startup(_zk); + } catch (IOException e) { + throw new ZkException("Unable to start single ZooKeeper server.", e); + } catch (InterruptedException e) { + throw new ZkInterruptedException(e); + } + } + + @PreDestroy + public void shutdown() { + LOG.info("Shutting down ZkServer..."); + try { + if(_zkClient != null) { + _zkClient.close(); + } + } catch (ZkException e) { + LOG.warn("Error on closing zkclient: " + e.getClass().getName()); + } + if (_nioFactory != null) { + _nioFactory.shutdown(); + try { + _nioFactory.join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + _nioFactory = null; + } + if (_zk != null) { + _zk.shutdown(); + _zk = null; + } + LOG.info("Shutting down ZkServer...done"); + } + + public ZkClient getZkClient() { + return _zkClient; + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkBadVersionException.java b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkBadVersionException.java new file mode 100644 index 00000000000..fb69e8348a4 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkBadVersionException.java @@ -0,0 +1,39 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient.exception; + +import org.apache.zookeeper.KeeperException; + +public class ZkBadVersionException extends ZkException { + + private static final long serialVersionUID = 1L; + + public ZkBadVersionException() { + super(); + } + + public ZkBadVersionException(KeeperException cause) { + super(cause); + } + + public ZkBadVersionException(String message, KeeperException cause) { + super(message, cause); + } + + public ZkBadVersionException(String message) { + super(message); + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkException.java b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkException.java new file mode 100644 index 00000000000..e8cf5b4e4dd --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkException.java @@ -0,0 +1,71 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient.exception; + +import org.apache.zookeeper.KeeperException; + +public class ZkException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public ZkException() { + super(); + } + + public ZkException(String message, Throwable cause) { + super(message, cause); + } + + public ZkException(String message) { + super(message); + } + + public ZkException(Throwable cause) { + super(cause); + } + + public static ZkException create(KeeperException e) { + switch (e.code()) { + // case DATAINCONSISTENCY: + // return new DataInconsistencyException(); + // case CONNECTIONLOSS: + // return new ConnectionLossException(); + case NONODE: + return new ZkNoNodeException(e); + // case NOAUTH: + // return new ZkNoAuthException(); + case BADVERSION: + return new ZkBadVersionException(e); + // case NOCHILDRENFOREPHEMERALS: + // return new NoChildrenForEphemeralsException(); + case NODEEXISTS: + return new ZkNodeExistsException(e); + // case INVALIDACL: + // return new ZkInvalidACLException(); + // case AUTHFAILED: + // return new AuthFailedException(); + // case NOTEMPTY: + // return new NotEmptyException(); + // case SESSIONEXPIRED: + // return new SessionExpiredException(); + // case INVALIDCALLBACK: + // return new InvalidCallbackException(); + + default: + return new ZkException(e); + } + } +} diff --git a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/hello/HelloServiceImpl.java b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkInterruptedException.java similarity index 58% rename from dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/hello/HelloServiceImpl.java rename to zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkInterruptedException.java index 80fcf24fc56..19d6f30f957 100644 --- a/dubbo-demo/dubbo-demo-provider/src/main/java/com/alibaba/dubbo/demo/hello/HelloServiceImpl.java +++ b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkInterruptedException.java @@ -1,11 +1,11 @@ /** - * Copyright 1999-2014 dangdang.com. + * Copyright 2010 the original author or authors. * * 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 + * 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, @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.demo.hello; +package org.I0Itec.zkclient.exception; -/** - * @author lishen - */ -public class HelloServiceImpl implements HelloService { +public class ZkInterruptedException extends ZkException { + + private static final long serialVersionUID = 1L; - public String hello(String name) { - return "hello " + name; + public ZkInterruptedException(InterruptedException e) { + super(e); + Thread.currentThread().interrupt(); } } diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Impression.java b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkMarshallingError.java similarity index 50% rename from dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Impression.java rename to zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkMarshallingError.java index 2b4cddfc559..cff949e0489 100644 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/Impression.java +++ b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkMarshallingError.java @@ -1,11 +1,11 @@ /** - * Copyright 1999-2014 dangdang.com. + * Copyright 2010 the original author or authors. * * 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 + * 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, @@ -13,31 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.demo.bid; +package org.I0Itec.zkclient.exception; -import java.io.Serializable; +public class ZkMarshallingError extends ZkException { -/** - * @author lishen - */ -public class Impression implements Serializable { - - private String id; - private double bidFloor; + private static final long serialVersionUID = 1L; - public String getId() { - return id; + public ZkMarshallingError() { + super(); } - public void setId(String id) { - this.id = id; + public ZkMarshallingError(Throwable cause) { + super(cause); } - public double getBidFloor() { - return bidFloor; + public ZkMarshallingError(String message, Throwable cause) { + super(message, cause); } - public void setBidFloor(double bidFloor) { - this.bidFloor = bidFloor; + public ZkMarshallingError(String message) { + super(message); } } diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkNoNodeException.java b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkNoNodeException.java new file mode 100644 index 00000000000..1dc2abb32e5 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkNoNodeException.java @@ -0,0 +1,39 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient.exception; + +import org.apache.zookeeper.KeeperException; + +public class ZkNoNodeException extends ZkException { + + private static final long serialVersionUID = 1L; + + public ZkNoNodeException() { + super(); + } + + public ZkNoNodeException(KeeperException cause) { + super(cause); + } + + public ZkNoNodeException(String message, KeeperException cause) { + super(message, cause); + } + + public ZkNoNodeException(String message) { + super(message); + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkNodeExistsException.java b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkNodeExistsException.java new file mode 100644 index 00000000000..cc900d07043 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkNodeExistsException.java @@ -0,0 +1,39 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient.exception; + +import org.apache.zookeeper.KeeperException; + +public class ZkNodeExistsException extends ZkException { + + private static final long serialVersionUID = 1L; + + public ZkNodeExistsException() { + super(); + } + + public ZkNodeExistsException(KeeperException cause) { + super(cause); + } + + public ZkNodeExistsException(String message, KeeperException cause) { + super(message, cause); + } + + public ZkNodeExistsException(String message) { + super(message); + } +} diff --git a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/SeatBid.java b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkTimeoutException.java similarity index 50% rename from dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/SeatBid.java rename to zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkTimeoutException.java index 8e852e657b5..ecb1ad922b4 100644 --- a/dubbo-demo/dubbo-demo-api/src/main/java/com/alibaba/dubbo/demo/bid/SeatBid.java +++ b/zkclient/src/main/java/org/I0Itec/zkclient/exception/ZkTimeoutException.java @@ -1,11 +1,11 @@ /** - * Copyright 1999-2014 dangdang.com. + * Copyright 2010 the original author or authors. * * 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 + * 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, @@ -13,32 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.demo.bid; +package org.I0Itec.zkclient.exception; -import java.io.Serializable; +public class ZkTimeoutException extends ZkException { -/** - * @author lishen - */ -public class SeatBid implements Serializable { - - private String seat; - - private String group; + private static final long serialVersionUID = 1L; - public String getSeat() { - return seat; + public ZkTimeoutException() { + super(); } - public void setSeat(String seat) { - this.seat = seat; + public ZkTimeoutException(String message, Throwable cause) { + super(message, cause); } - public String getGroup() { - return group; + public ZkTimeoutException(String message) { + super(message); } - public void setGroup(String group) { - this.group = group; + public ZkTimeoutException(Throwable cause) { + super(cause); } } diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/serialize/BytesPushThroughSerializer.java b/zkclient/src/main/java/org/I0Itec/zkclient/serialize/BytesPushThroughSerializer.java new file mode 100644 index 00000000000..dcf5c74bf98 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/serialize/BytesPushThroughSerializer.java @@ -0,0 +1,35 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient.serialize; + +import org.I0Itec.zkclient.exception.ZkMarshallingError; + +/** + * A {@link ZkSerializer} which simply passes byte arrays to zk and back. + */ +public class BytesPushThroughSerializer implements ZkSerializer { + + @Override + public Object deserialize(byte[] bytes) throws ZkMarshallingError { + return bytes; + } + + @Override + public byte[] serialize(Object bytes) throws ZkMarshallingError { + return (byte[]) bytes; + } + +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/serialize/SerializableSerializer.java b/zkclient/src/main/java/org/I0Itec/zkclient/serialize/SerializableSerializer.java new file mode 100644 index 00000000000..005ab7a067e --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/serialize/SerializableSerializer.java @@ -0,0 +1,54 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient.serialize; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import org.I0Itec.zkclient.exception.ZkMarshallingError; + +public class SerializableSerializer implements ZkSerializer { + + @Override + public Object deserialize(byte[] bytes) throws ZkMarshallingError { + try { + ObjectInputStream inputStream = new TcclAwareObjectIputStream(new ByteArrayInputStream(bytes)); + Object object = inputStream.readObject(); + return object; + } catch (ClassNotFoundException e) { + throw new ZkMarshallingError("Unable to find object class.", e); + } catch (IOException e) { + throw new ZkMarshallingError(e); + } + } + + @Override + public byte[] serialize(Object serializable) throws ZkMarshallingError { + try { + ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream(); + ObjectOutputStream stream = new ObjectOutputStream(byteArrayOS); + stream.writeObject(serializable); + stream.close(); + return byteArrayOS.toByteArray(); + } catch (IOException e) { + throw new ZkMarshallingError(e); + } + } + +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/serialize/TcclAwareObjectIputStream.java b/zkclient/src/main/java/org/I0Itec/zkclient/serialize/TcclAwareObjectIputStream.java new file mode 100644 index 00000000000..2bc2e2cad43 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/serialize/TcclAwareObjectIputStream.java @@ -0,0 +1,82 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient.serialize; + +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectStreamClass; +import java.lang.reflect.Proxy; + +/** + * An ObjectInputStream that is aware of the TCCL. + */ +public class TcclAwareObjectIputStream extends ObjectInputStream { + + public TcclAwareObjectIputStream(InputStream in) throws IOException { + super(in); + } + + /** + * Load the local class equivalent of the specified stream class + * description. + * Uses the current class {@link ClassLoader} and falls back to the {@link Thread} context {@link ClassLoader}. + */ + protected Class resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException { + try { + return getClass().getClassLoader().loadClass(classDesc.getName()); + } catch (ClassNotFoundException ex) { + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + if (tccl != null) { + return tccl.loadClass(classDesc.getName()); + } else { + throw ex; + } + } + } + + /** + * Returns a proxy class that implements the interfaces named in a proxy + * class descriptor; subclasses may implement this method to read custom + * data from the stream along with the descriptors for dynamic proxy + * classes, allowing them to use an alternate loading mechanism for the + * interfaces and the proxy class. + * + * For each interface uses the current class {@link ClassLoader} and falls back to the {@link Thread} context {@link ClassLoader}. + */ + protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { + ClassLoader cl = getClass().getClassLoader(); + Class[] cinterfaces = new Class[interfaces.length]; + + for (int i = 0; i < interfaces.length; i++) { + try { + cinterfaces[i] = cl.loadClass(interfaces[i]); + } catch (ClassNotFoundException ex) { + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + if (tccl != null) { + return tccl.loadClass(interfaces[i]); + } else { + throw ex; + } + } + } + try { + return Proxy.getProxyClass(cinterfaces[0].getClassLoader(), cinterfaces); + } catch (IllegalArgumentException e) { + throw new ClassNotFoundException(null, e); + } + } +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/serialize/ZkSerializer.java b/zkclient/src/main/java/org/I0Itec/zkclient/serialize/ZkSerializer.java new file mode 100644 index 00000000000..b11c5e3737f --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/serialize/ZkSerializer.java @@ -0,0 +1,32 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient.serialize; + +import org.I0Itec.zkclient.exception.ZkMarshallingError; + +/** + * Zookeeper is able to store data in form of byte arrays. This interfacte is a bridge between those byte-array format + * and higher level objects. + * + * @see BytesPushThroughSerializer + * @see SerializableSerializer + */ +public interface ZkSerializer { + + public byte[] serialize(Object data) throws ZkMarshallingError; + + public Object deserialize(byte[] bytes) throws ZkMarshallingError; +} diff --git a/zkclient/src/main/java/org/I0Itec/zkclient/util/ZkPathUtil.java b/zkclient/src/main/java/org/I0Itec/zkclient/util/ZkPathUtil.java new file mode 100644 index 00000000000..98a3a0e9dd7 --- /dev/null +++ b/zkclient/src/main/java/org/I0Itec/zkclient/util/ZkPathUtil.java @@ -0,0 +1,79 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient.util; + +import java.util.List; + +import org.I0Itec.zkclient.ZkClient; + +public class ZkPathUtil { + + public static String leadingZeros(long number, int numberOfLeadingZeros) { + return String.format("%0" + numberOfLeadingZeros + "d", number); + } + + public static String toString(ZkClient zkClient) { + return toString(zkClient, "/", PathFilter.ALL); + } + + public static String toString(ZkClient zkClient, String startPath, PathFilter pathFilter) { + final int level = 1; + final StringBuilder builder = new StringBuilder("+ (" + startPath + ")"); + builder.append("\n"); + addChildrenToStringBuilder(zkClient, pathFilter, level, builder, startPath); + return builder.toString(); + } + + private static void addChildrenToStringBuilder(ZkClient zkClient, PathFilter pathFilter, final int level, final StringBuilder builder, final String startPath) { + final List children = zkClient.getChildren(startPath); + for (final String node : children) { + String nestedPath; + if (startPath.endsWith("/")) { + nestedPath = startPath + node; + } else { + nestedPath = startPath + "/" + node; + } + if (pathFilter.showChilds(nestedPath)) { + builder.append(getSpaces(level - 1) + "'-" + "+" + node + "\n"); + addChildrenToStringBuilder(zkClient, pathFilter, level + 1, builder, nestedPath); + } else { + builder.append(getSpaces(level - 1) + "'-" + "-" + node + " (contents hidden)\n"); + } + } + } + + private static String getSpaces(final int level) { + String s = ""; + for (int i = 0; i < level; i++) { + s += " "; + } + return s; + } + + public static interface PathFilter { + + public static PathFilter ALL = new PathFilter() { + + @Override + public boolean showChilds(String path) { + return true; + } + }; + + boolean showChilds(String path); + } + +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/AbstractAuthTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/AbstractAuthTest.java new file mode 100644 index 00000000000..6c61fa15e95 --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/AbstractAuthTest.java @@ -0,0 +1,72 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 org.I0Itec.zkclient; + +import org.I0Itec.zkclient.exception.ZkException; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Id; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.fail; + +public abstract class AbstractAuthTest { + protected ZkClient _client; + protected ZkServer _zkServer; + //protected static final Logger LOG = Logger.getLogger(AbstractAuthTest.class); + protected static final Logger LOG = LoggerFactory.getLogger(AbstractAuthTest.class); + + @Before + public void setUp() throws Exception { + LOG.info("------------ BEFORE -------------"); + + } + + @After + public void tearDown() throws Exception { + LOG.info("------------ AFTER -------------"); + } + + @Test + public void testBadAuth() { + try { + List acl = new ArrayList(); + acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest", "pat:pass"))); + _client.create("/path1", null, acl, CreateMode.EPHEMERAL); + _client.addAuthInfo("digest", "pat:pass2".getBytes()); + _client.readData("/path1"); + fail("Should get auth error"); + } catch (ZkException e) { + if (e.getCause() instanceof KeeperException && ((KeeperException) e.getCause()).code() == KeeperException.Code.NOAUTH) { + // do nothing, this is expected + } else { + fail("wrong exception"); + } + } + } + +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/AbstractBaseZkClientTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/AbstractBaseZkClientTest.java new file mode 100644 index 00000000000..71ed87dcfe3 --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/AbstractBaseZkClientTest.java @@ -0,0 +1,389 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import org.I0Itec.zkclient.exception.ZkTimeoutException; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; + +//import org.apache.log4j.Logger; + +public abstract class AbstractBaseZkClientTest { + + //protected static final Logger LOG = Logger.getLogger(AbstractBaseZkClientTest.class); + protected static final Logger LOG = LoggerFactory.getLogger(AbstractBaseZkClientTest.class); + protected ZkServer _zkServer; + protected ZkClient _client; + + @Before + public void setUp() throws Exception { + LOG.info("------------ BEFORE -------------"); + + } + + @After + public void tearDown() throws Exception { + LOG.info("------------ AFTER -------------"); + } + + @Test(expected = ZkTimeoutException.class, timeout = 15000) + public void testUnableToConnect() throws Exception { + LOG.info("--- testUnableToConnect"); + // we are using port 4711 to avoid conflicts with the zk server that is + // started by the Spring context + new ZkClient("localhost:4712", 5000); + } + + @Test + public void testWriteAndRead() throws Exception { + LOG.info("--- testWriteAndRead"); + String data = "something"; + String path = "/a"; + _client.createPersistent(path, data); + String data2 = _client.readData(path); + Assert.assertEquals(data, data2); + _client.delete(path); + } + + @Test + public void testDelete() throws Exception { + LOG.info("--- testDelete"); + String path = "/a"; + assertFalse(_client.delete(path)); + _client.createPersistent(path, null); + assertTrue(_client.delete(path)); + assertFalse(_client.delete(path)); + } + + @Test + public void testDeleteRecursive() throws Exception { + LOG.info("--- testDeleteRecursive"); + + // should be able to call this on a not existing directory + _client.deleteRecursive("/doesNotExist"); + } + + @Test + public void testWaitUntilExists() { + LOG.info("--- testWaitUntilExists"); + // create /gaga node asynchronously + new Thread() { + @Override + public void run() { + try { + Thread.sleep(100); + _client.createPersistent("/gaga"); + } catch (Exception e) { + // ignore + } + } + }.start(); + + // wait until this was created + assertTrue(_client.waitUntilExists("/gaga", TimeUnit.SECONDS, 5)); + assertTrue(_client.exists("/gaga")); + + // waiting for /neverCreated should timeout + assertFalse(_client.waitUntilExists("/neverCreated", TimeUnit.MILLISECONDS, 100)); + } + + @Test + public void testDataChanges1() throws Exception { + LOG.info("--- testDataChanges1"); + String path = "/a"; + final Holder holder = new Holder(); + + IZkDataListener listener = new IZkDataListener() { + + @Override + public void handleDataChange(String dataPath, Object data) throws Exception { + holder.set((String) data); + } + + @Override + public void handleDataDeleted(String dataPath) throws Exception { + holder.set(null); + } + }; + _client.subscribeDataChanges(path, listener); + _client.createPersistent(path, "aaa"); + + // wait some time to make sure the event was triggered + String contentFromHolder = TestUtil.waitUntil("b", new Callable() { + + @Override + public String call() throws Exception { + return holder.get(); + } + }, TimeUnit.SECONDS, 5); + + assertEquals("aaa", contentFromHolder); + } + + @Test + public void testDataChanges2() throws Exception { + LOG.info("--- testDataChanges2"); + String path = "/a"; + final AtomicInteger countChanged = new AtomicInteger(0); + final AtomicInteger countDeleted = new AtomicInteger(0); + + IZkDataListener listener = new IZkDataListener() { + + @Override + public void handleDataChange(String dataPath, Object data) throws Exception { + countChanged.incrementAndGet(); + } + + @Override + public void handleDataDeleted(String dataPath) throws Exception { + countDeleted.incrementAndGet(); + } + }; + _client.subscribeDataChanges(path, listener); + + // create node + _client.createPersistent(path, "aaa"); + + // wait some time to make sure the event was triggered + TestUtil.waitUntil(1, new Callable() { + + @Override + public Integer call() throws Exception { + return countChanged.get(); + } + }, TimeUnit.SECONDS, 5); + assertEquals(1, countChanged.get()); + assertEquals(0, countDeleted.get()); + + countChanged.set(0); + countDeleted.set(0); + // delete node, this should trigger a delete event + _client.delete(path); + // wait some time to make sure the event was triggered + TestUtil.waitUntil(1, new Callable() { + + @Override + public Integer call() throws Exception { + return countDeleted.get(); + } + }, TimeUnit.SECONDS, 5); + assertEquals(0, countChanged.get()); + assertEquals(1, countDeleted.get()); + + // test if watch was reinstalled after the file got deleted + countChanged.set(0); + _client.createPersistent(path, "aaa"); + + // wait some time to make sure the event was triggered + TestUtil.waitUntil(1, new Callable() { + + @Override + public Integer call() throws Exception { + return countChanged.get(); + } + }, TimeUnit.SECONDS, 5); + assertEquals(1, countChanged.get()); + + // test if changing the contents notifies the listener + _client.writeData(path, "bbb"); + + // wait some time to make sure the event was triggered + TestUtil.waitUntil(2, new Callable() { + + @Override + public Integer call() throws Exception { + return countChanged.get(); + } + }, TimeUnit.SECONDS, 5); + assertEquals(2, countChanged.get()); + } + + @Test(timeout = 15000) + public void testHandleChildChanges() throws Exception { + LOG.info("--- testHandleChildChanges"); + String path = "/a"; + final AtomicInteger count = new AtomicInteger(0); + final Holder> children = new Holder>(); + + IZkChildListener listener = new IZkChildListener() { + + @Override + public void handleChildChange(String parentPath, List currentChilds) throws Exception { + count.incrementAndGet(); + children.set(currentChilds); + } + }; + _client.subscribeChildChanges(path, listener); + + // ---- + // Create the root node should throw the first child change event + // ---- + _client.createPersistent(path); + + // wait some time to make sure the event was triggered + TestUtil.waitUntil(1, new Callable() { + + @Override + public Integer call() throws Exception { + return count.get(); + } + }, TimeUnit.SECONDS, 5); + assertEquals(1, count.get()); + assertEquals(0, children.get().size()); + + // ---- + // Creating a child node should throw another event + // ---- + count.set(0); + _client.createPersistent(path + "/child1"); + + // wait some time to make sure the event was triggered + TestUtil.waitUntil(1, new Callable() { + + @Override + public Integer call() throws Exception { + return count.get(); + } + }, TimeUnit.SECONDS, 5); + assertEquals(1, count.get()); + assertEquals(1, children.get().size()); + assertEquals("child1", children.get().get(0)); + + // ---- + // Creating another child and deleting the node should also throw an event + // ---- + count.set(0); + _client.createPersistent(path + "/child2"); + _client.deleteRecursive(path); + + // wait some time to make sure the event was triggered + Boolean eventReceived = TestUtil.waitUntil(true, new Callable() { + + @Override + public Boolean call() throws Exception { + return count.get() > 0 && children.get() == null; + } + }, TimeUnit.SECONDS, 5); + assertTrue(eventReceived); + assertNull(children.get()); + + // ---- + // Creating root again should throw an event + // ---- + count.set(0); + _client.createPersistent(path); + + // wait some time to make sure the event was triggered + eventReceived = TestUtil.waitUntil(true, new Callable() { + + @Override + public Boolean call() throws Exception { + return count.get() > 0 && children.get() != null; + } + }, TimeUnit.SECONDS, 5); + assertTrue(eventReceived); + assertEquals(0, children.get().size()); + + // ---- + // Creating child now should throw an event + // ---- + count.set(0); + _client.createPersistent(path + "/child"); + + // wait some time to make sure the event was triggered + eventReceived = TestUtil.waitUntil(true, new Callable() { + + @Override + public Boolean call() throws Exception { + return count.get() > 0; + } + }, TimeUnit.SECONDS, 5); + assertTrue(eventReceived); + assertEquals(1, children.get().size()); + assertEquals("child", children.get().get(0)); + + // ---- + // Deleting root node should throw an event + // ---- + count.set(0); + _client.deleteRecursive(path); + + // wait some time to make sure the event was triggered + eventReceived = TestUtil.waitUntil(true, new Callable() { + + @Override + public Boolean call() throws Exception { + return count.get() > 0 && children.get() == null; + } + }, TimeUnit.SECONDS, 5); + assertTrue(eventReceived); + assertNull(children.get()); + } + + @Test + public void testGetCreationTime() throws Exception { + long start = System.currentTimeMillis(); + Thread.sleep(100); + String path = "/a"; + _client.createPersistent(path); + Thread.sleep(100); + long end = System.currentTimeMillis(); + long creationTime = _client.getCreationTime(path); + assertTrue(start < creationTime && end > creationTime); + } + + @Test + public void testNumberOfListeners() { + IZkChildListener zkChildListener = mock(IZkChildListener.class); + _client.subscribeChildChanges("/", zkChildListener); + assertEquals(1, _client.numberOfListeners()); + + IZkDataListener zkDataListener = mock(IZkDataListener.class); + _client.subscribeDataChanges("/a", zkDataListener); + assertEquals(2, _client.numberOfListeners()); + + _client.subscribeDataChanges("/b", zkDataListener); + assertEquals(3, _client.numberOfListeners()); + + IZkStateListener zkStateListener = mock(IZkStateListener.class); + _client.subscribeStateChanges(zkStateListener); + assertEquals(4, _client.numberOfListeners()); + + _client.unsubscribeChildChanges("/", zkChildListener); + assertEquals(3, _client.numberOfListeners()); + + _client.unsubscribeDataChanges("/b", zkDataListener); + assertEquals(2, _client.numberOfListeners()); + + _client.unsubscribeDataChanges("/a", zkDataListener); + assertEquals(1, _client.numberOfListeners()); + + _client.unsubscribeStateChanges(zkStateListener); + assertEquals(0, _client.numberOfListeners()); + } +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/AbstractConnectionTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/AbstractConnectionTest.java new file mode 100644 index 00000000000..06d22c8ba24 --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/AbstractConnectionTest.java @@ -0,0 +1,54 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import java.util.List; + +import org.I0Itec.zkclient.util.ZkPathUtil; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public abstract class AbstractConnectionTest { + + private final IZkConnection _connection; + + public AbstractConnectionTest(IZkConnection connection) { + _connection = connection; + } + + @Test + public void testGetChildren_OnEmptyFileSystem() throws KeeperException, InterruptedException { + InMemoryConnection connection = new InMemoryConnection(); + List children = connection.getChildren("/", false); + assertEquals(0, children.size()); + } + + @Test + public void testSequentials() throws KeeperException, InterruptedException { + String sequentialPath = _connection.create("/a", new byte[0], CreateMode.EPHEMERAL_SEQUENTIAL); + int firstSequential = Integer.parseInt(sequentialPath.substring(2)); + assertEquals("/a" + ZkPathUtil.leadingZeros(firstSequential++, 10), sequentialPath); + assertEquals("/a" + ZkPathUtil.leadingZeros(firstSequential++, 10), _connection.create("/a", new byte[0], CreateMode.EPHEMERAL_SEQUENTIAL)); + assertEquals("/a" + ZkPathUtil.leadingZeros(firstSequential++, 10), _connection.create("/a", new byte[0], CreateMode.PERSISTENT_SEQUENTIAL)); + assertEquals("/b" + ZkPathUtil.leadingZeros(firstSequential++, 10), _connection.create("/b", new byte[0], CreateMode.EPHEMERAL_SEQUENTIAL)); + assertEquals("/b" + ZkPathUtil.leadingZeros(firstSequential++, 10), _connection.create("/b", new byte[0], CreateMode.PERSISTENT_SEQUENTIAL)); + assertEquals("/a" + ZkPathUtil.leadingZeros(firstSequential++, 10), _connection.create("/a", new byte[0], CreateMode.EPHEMERAL_SEQUENTIAL)); + } + +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/ContentWatcherTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/ContentWatcherTest.java new file mode 100644 index 00000000000..e4838a4c173 --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/ContentWatcherTest.java @@ -0,0 +1,159 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.assertEquals; + +//import org.apache.log4j.Logger; + +public class ContentWatcherTest { + + private static final Logger LOG = LoggerFactory.getLogger(ContentWatcherTest.class); + + + private static final String FILE_NAME = "/ContentWatcherTest"; + private ZkServer _zkServer; + private ZkClient _zkClient; + + @Before + public void setUp() throws Exception { + LOG.info("------------ BEFORE -------------"); + _zkServer = TestUtil.startZkServer("ContentWatcherTest", 4711); + _zkClient = _zkServer.getZkClient(); + } + + @After + public void tearDown() throws Exception { + if (_zkServer != null) { + _zkServer.shutdown(); + } + LOG.info("------------ AFTER -------------"); + } + + @Test + public void testGetContent() throws Exception { + LOG.info("--- testGetContent"); + _zkClient.createPersistent(FILE_NAME, "a"); + final ContentWatcher watcher = new ContentWatcher(_zkClient, FILE_NAME); + watcher.start(); + assertEquals("a", watcher.getContent()); + + // update the content + _zkClient.writeData(FILE_NAME, "b"); + + String contentFromWatcher = TestUtil.waitUntil("b", new Callable() { + + @Override + public String call() throws Exception { + return watcher.getContent(); + } + }, TimeUnit.SECONDS, 5); + + assertEquals("b", contentFromWatcher); + watcher.stop(); + } + + @Test + public void testGetContentWaitTillCreated() throws InterruptedException { + LOG.info("--- testGetContentWaitTillCreated"); + final Holder contentHolder = new Holder(); + + Thread thread = new Thread() { + @Override + public void run() { + ContentWatcher watcher = new ContentWatcher(_zkClient, FILE_NAME); + try { + watcher.start(); + contentHolder.set(watcher.getContent()); + watcher.stop(); + } catch (Exception e) { + e.printStackTrace(); + } + } + }; + + thread.start(); + + // create content after 200ms + Thread.sleep(200); + _zkClient.createPersistent(FILE_NAME, "aaa"); + + // we give the thread some time to pick up the change + thread.join(1000); + assertEquals("aaa", contentHolder.get()); + } + + @Test + public void testHandlingNullContent() throws InterruptedException { + LOG.info("--- testHandlingNullContent"); + _zkClient.createPersistent(FILE_NAME, null); + ContentWatcher watcher = new ContentWatcher(_zkClient, FILE_NAME); + watcher.start(); + assertEquals(null, watcher.getContent()); + watcher.stop(); + } + + @Test(timeout = 20000) + public void testHandlingOfConnectionLoss() throws Exception { + LOG.info("--- testHandlingOfConnectionLoss"); + final Gateway gateway = new Gateway(4712, 4711); + gateway.start(); + final ZkClient zkClient = new ZkClient("localhost:4712", 30000); + + // disconnect + gateway.stop(); + + // reconnect after 250ms and create file with content + new Thread() { + @Override + public void run() { + try { + Thread.sleep(250); + gateway.start(); + zkClient.createPersistent(FILE_NAME, "aaa"); + zkClient.writeData(FILE_NAME, "b"); + } catch (Exception e) { + // ignore + } + } + }.start(); + + final ContentWatcher watcher = new ContentWatcher(zkClient, FILE_NAME); + watcher.start(); + + TestUtil.waitUntil("b", new Callable() { + + @Override + public String call() throws Exception { + return watcher.getContent(); + } + }, TimeUnit.SECONDS, 5); + assertEquals("b", watcher.getContent()); + + watcher.stop(); + zkClient.close(); + gateway.stop(); + } +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/DeferredGatewayStarter.java b/zkclient/src/test/java/org/I0Itec/zkclient/DeferredGatewayStarter.java new file mode 100644 index 00000000000..bf615dfa92a --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/DeferredGatewayStarter.java @@ -0,0 +1,37 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +public class DeferredGatewayStarter extends Thread { + + private final Gateway _zkServer; + private int _delay; + + public DeferredGatewayStarter(Gateway gateway, int delay) { + _zkServer = gateway; + _delay = delay; + } + + @Override + public void run() { + try { + Thread.sleep(_delay); + _zkServer.start(); + } catch (Exception e) { + // ignore + } + } +} \ No newline at end of file diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/DistributedQueueTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/DistributedQueueTest.java new file mode 100644 index 00000000000..42311e9c147 --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/DistributedQueueTest.java @@ -0,0 +1,127 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.Vector; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class DistributedQueueTest { + + private ZkServer _zkServer; + private ZkClient _zkClient; + + @Before + public void setUp() throws IOException { + _zkServer = TestUtil.startZkServer("ZkClientTest-testDistributedQueue", 4711); + _zkClient = _zkServer.getZkClient(); + } + + @After + public void tearDown() { + if (_zkServer != null) { + _zkServer.shutdown(); + } + } + + @Test(timeout = 15000) + public void testDistributedQueue() { + _zkClient.createPersistent("/queue"); + + DistributedQueue distributedQueue = new DistributedQueue(_zkClient, "/queue"); + distributedQueue.offer(17L); + distributedQueue.offer(18L); + distributedQueue.offer(19L); + + assertEquals(Long.valueOf(17L), distributedQueue.poll()); + assertEquals(Long.valueOf(18L), distributedQueue.poll()); + assertEquals(Long.valueOf(19L), distributedQueue.poll()); + assertNull(distributedQueue.poll()); + } + + @Test(timeout = 15000) + public void testPeek() { + _zkClient.createPersistent("/queue"); + + DistributedQueue distributedQueue = new DistributedQueue(_zkClient, "/queue"); + distributedQueue.offer(17L); + distributedQueue.offer(18L); + + assertEquals(Long.valueOf(17L), distributedQueue.peek()); + assertEquals(Long.valueOf(17L), distributedQueue.peek()); + assertEquals(Long.valueOf(17L), distributedQueue.poll()); + assertEquals(Long.valueOf(18L), distributedQueue.peek()); + assertEquals(Long.valueOf(18L), distributedQueue.poll()); + assertNull(distributedQueue.peek()); + } + + @Test(timeout = 30000) + public void testMultipleReadingThreads() throws InterruptedException { + _zkClient.createPersistent("/queue"); + + final DistributedQueue distributedQueue = new DistributedQueue(_zkClient, "/queue"); + + // insert 100 elements + for (int i = 0; i < 100; i++) { + distributedQueue.offer(new Long(i)); + } + + // 3 reading threads + final Set readElements = Collections.synchronizedSet(new HashSet()); + List threads = new ArrayList(); + final List exceptions = new Vector(); + + for (int i = 0; i < 3; i++) { + Thread thread = new Thread() { + @Override + public void run() { + try { + while (true) { + Long value = distributedQueue.poll(); + if (value == null) { + return; + } + readElements.add(value); + } + } catch (Exception e) { + exceptions.add(e); + e.printStackTrace(); + } + } + }; + threads.add(thread); + thread.start(); + } + + for (Thread thread : threads) { + thread.join(); + } + + assertEquals(0, exceptions.size()); + assertEquals(100, readElements.size()); + } +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/InMemoryAuthTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/InMemoryAuthTest.java new file mode 100644 index 00000000000..8066b5ee5b4 --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/InMemoryAuthTest.java @@ -0,0 +1,51 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 org.I0Itec.zkclient; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Id; +import org.junit.Test; + +public class InMemoryAuthTest extends AbstractAuthTest { + + @Override + public void setUp() throws Exception { + super.setUp(); + _client = new ZkClient(new InMemoryConnection()); + } + + @Override + public void tearDown() throws Exception { + super.tearDown(); + _client.close(); + } + + @Test + public void testAuthorized() { + List acl = new ArrayList(); + acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest", "pat:pass"))); + _client.addAuthInfo("digest", "pat:pass".getBytes()); + _client.create("/path1", null, acl, CreateMode.PERSISTENT); + _client.readData("/path1"); + } +} diff --git a/dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/Main.java b/zkclient/src/test/java/org/I0Itec/zkclient/InMemoryConnectionTest.java similarity index 65% rename from dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/Main.java rename to zkclient/src/test/java/org/I0Itec/zkclient/InMemoryConnectionTest.java index 786d1b067b0..ec3cd65f61c 100644 --- a/dubbo-test/dubbo-test-benchmark-server/src/main/java/com/alibaba/dubbo/rpc/benchmark/Main.java +++ b/zkclient/src/test/java/org/I0Itec/zkclient/InMemoryConnectionTest.java @@ -1,11 +1,11 @@ /** - * Copyright 1999-2014 dangdang.com. + * Copyright 2010 the original author or authors. * * 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 + * 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, @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.dubbo.rpc.benchmark; +package org.I0Itec.zkclient; -public class Main { - public static void main(String[] args) { - com.alibaba.dubbo.container.Main.main(args); +public class InMemoryConnectionTest extends AbstractConnectionTest { + + public InMemoryConnectionTest() { + super(new InMemoryConnection()); } -} \ No newline at end of file +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/MemoryZkClientTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/MemoryZkClientTest.java new file mode 100644 index 00000000000..c05a41b159b --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/MemoryZkClientTest.java @@ -0,0 +1,49 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import org.apache.zookeeper.CreateMode; +import org.junit.Assert; +import org.junit.Test; + +public class MemoryZkClientTest extends AbstractBaseZkClientTest { + + @Override + public void setUp() throws Exception { + super.setUp(); + _client = new ZkClient(new InMemoryConnection()); + } + + @Override + public void tearDown() throws Exception { + super.tearDown(); + _client.close(); + } + + @Test + public void testGetChildren() throws Exception { + String path1 = "/a"; + String path2 = "/a/a"; + String path3 = "/a/a/a"; + + _client.create(path1, null, CreateMode.PERSISTENT); + _client.create(path2, null, CreateMode.PERSISTENT); + _client.create(path3, null, CreateMode.PERSISTENT); + Assert.assertEquals(1, _client.getChildren(path1).size()); + Assert.assertEquals(1, _client.getChildren(path2).size()); + Assert.assertEquals(0, _client.getChildren(path3).size()); + } +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/SaslAuthenticatedTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/SaslAuthenticatedTest.java new file mode 100644 index 00000000000..723080db57e --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/SaslAuthenticatedTest.java @@ -0,0 +1,175 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 org.I0Itec.zkclient; + +import org.I0Itec.zkclient.exception.ZkException; +import org.I0Itec.zkclient.exception.ZkTimeoutException; +import org.apache.zookeeper.ZooDefs.Ids; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.security.auth.login.Configuration; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +public class SaslAuthenticatedTest { + protected static final Logger LOG = LoggerFactory.getLogger(SaslAuthenticatedTest.class); + static final String ZK_AUTH_PROVIDER = "zookeeper.authProvider.1"; + static final String ZK_ALLOW_FAILED_SASL = "zookeeper.allowSaslFailedClients"; + + @Rule + public TemporaryFolder _temporaryFolder = new TemporaryFolder(); + private int _port = 4700; + private ZkClient _client; + private ZkServer _zkServer; + private String _zkServerContextName = "Server"; + private String _zkClientContextName = "Client"; + private String _userSuperPasswd = "adminpasswd"; + private String _userServerSide = "fpj"; + private String _userClientSide = "fpj"; + private String _userServerSidePasswd = "fpjsecret"; + private String _userClientSidePasswd = "fpjsecret"; + private String _zkModule = "org.apache.zookeeper.server.auth.DigestLoginModule"; + + private String createJaasFile() throws IOException { + File jaasFile = _temporaryFolder.newFile("jaas.conf"); + FileOutputStream jaasOutputStream = new java.io.FileOutputStream(jaasFile); + jaasOutputStream.write(String.format("%s {\n\t%s required\n", _zkServerContextName, _zkModule).getBytes()); + jaasOutputStream.write(String.format("\tuser_super=\"%s\"\n", _userSuperPasswd).getBytes()); + jaasOutputStream.write(String.format("\tuser_%s=\"%s\";\n};\n\n", _userServerSide, _userServerSidePasswd).getBytes()); + jaasOutputStream.write(String.format("%s {\n\t%s required\n", _zkClientContextName, _zkModule).getBytes()); + jaasOutputStream.write(String.format("\tusername=\"%s\"\n", _userClientSide).getBytes()); + jaasOutputStream.write(String.format("\tpassword=\"%s\";\n};", _userClientSidePasswd).getBytes()); + jaasOutputStream.close(); + return jaasFile.getAbsolutePath(); + } + + @Before + public void setUp() throws IOException { + // Reset all variables used for the jaas login file + _zkServerContextName = "Server"; + _zkClientContextName = "Client"; + _userSuperPasswd = "adminpasswd"; + _userServerSide = "fpj"; + _userClientSide = "fpj"; + _userServerSidePasswd = "fpjsecret"; + _userClientSidePasswd = "fpjsecret"; + _zkModule = "org.apache.zookeeper.server.auth.DigestLoginModule"; + } + + @After + public void tearDown() { + if (_client != null) { + _client.close(); + } + if (_zkServer != null) { + _zkServer.shutdown(); + } + System.clearProperty(ZK_AUTH_PROVIDER); + System.clearProperty(ZkClient.JAVA_LOGIN_CONFIG_PARAM); + Configuration.setConfiguration(null); + } + + private void bootstrap() throws IOException { + Configuration.setConfiguration(null); + String jaasFileName = createJaasFile(); + System.setProperty(ZK_AUTH_PROVIDER, "org.apache.zookeeper.server.auth.SASLAuthenticationProvider"); + System.setProperty(ZkClient.JAVA_LOGIN_CONFIG_PARAM, jaasFileName); + _zkServer = TestUtil.startZkServer(_temporaryFolder, _port); + _client = _zkServer.getZkClient(); + } + + private void bootstrapWithAuthFailure() throws IOException { + _userServerSide = "otheruser"; + bootstrap(); + } + + /** + * Tests that a connection authenticates successfully. + * + * @throws IOException + */ + @Test + public void testConnection() throws IOException { + bootstrap(); + _client.createPersistent("/test", new byte[0], Ids.CREATOR_ALL_ACL); + assertThat(_client.exists("/test")).isTrue(); + } + + /** + * Tests that ZkClient throws an exception in the case ZooKeeper keeps dropping the connection due to authentication + * failures. + * + * @throws IOException + */ + @Test + public void testAuthFailure() throws IOException { + try { + bootstrapWithAuthFailure(); + fail("Expected to fail!"); + } catch (ZkException e) { + assertThat(e).isInstanceOf(ZkTimeoutException.class); + } + } + + /** + * Tests that ZkClient spots the AuthFailed event in the case the property to allow failed SASL connections is + * enabled. + * + * @throws IOException + */ + @Test + public void testAuthFailure_AllowFailedSasl() throws IOException { + System.setProperty(ZK_ALLOW_FAILED_SASL, "true"); + try { + bootstrapWithAuthFailure(); + fail("Expected to fail!"); + } catch (ZkException e) { + assertThat(e).isInstanceOf(ZkTimeoutException.class); + } finally { + System.clearProperty(ZK_ALLOW_FAILED_SASL); + } + } + + /** + * Tests that ZkClient spots the AuthFailed event in the case the property to allow failed SASL connections is + * enabled. + * + * @throws IOException + */ + @Test + public void testAuthFailure_DisabledSasl() throws IOException { + System.setProperty(ZkClient.ZK_SASL_CLIENT, "false"); + try { + bootstrapWithAuthFailure(); + } finally { + System.clearProperty(ZkClient.ZK_SASL_CLIENT); + } + } + +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/ServerZkClientTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/ServerZkClientTest.java new file mode 100644 index 00000000000..b7e4dfdd634 --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/ServerZkClientTest.java @@ -0,0 +1,368 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; + +import org.I0Itec.zkclient.exception.ZkBadVersionException; +import org.I0Itec.zkclient.exception.ZkInterruptedException; +import org.I0Itec.zkclient.exception.ZkNoNodeException; +import org.I0Itec.zkclient.exception.ZkTimeoutException; +import org.I0Itec.zkclient.serialize.SerializableSerializer; +import org.apache.zookeeper.Watcher.Event.KeeperState; +import org.apache.zookeeper.data.Stat; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +public class ServerZkClientTest extends AbstractBaseZkClientTest { + + private static final int CONNECTION_TIMEOUT = 30000; + + @Rule + public TemporaryFolder _temporaryFolder = new TemporaryFolder(); + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + _zkServer = TestUtil.startZkServer(_temporaryFolder, 4711); + _client = new ZkClient("localhost:4711", CONNECTION_TIMEOUT); + } + + @Override + @After + public void tearDown() throws Exception { + super.tearDown(); + _client.close(); + _zkServer.shutdown(); + } + + @Test(timeout = 15000) + public void testRetryUntilConnected() throws Exception { + LOG.info("--- testRetryUntilConnected"); + Gateway gateway = new Gateway(4712, 4711); + gateway.start(); + final ZkConnection zkConnection = new ZkConnection("localhost:4712"); + final ZkClient zkClient = new ZkClient(zkConnection, CONNECTION_TIMEOUT); + + gateway.stop(); + + // start server in 250ms + new DeferredGatewayStarter(gateway, 250).start(); + + // this should work as soon as the connection is reestablished, if it + // fails it throws a ConnectionLossException + zkClient.retryUntilConnected(new Callable() { + + @Override + public Object call() throws Exception { + zkConnection.exists("/a", false); + return null; + } + }); + + zkClient.close(); + gateway.stop(); + } + + /** + * Test for reproducing #25 / https://issues.apache.org/jira/browse/KAFKA-824 + * + * @throws Exception + */ + @Test(timeout = 15000) + public void testOperationInRetryLoopWhileClientGetsClosed() throws Exception { + LOG.info("--- testRetryUntilConnected"); + Gateway gateway = new Gateway(4712, 4711); + gateway.start(); + final ZkConnection zkConnection = new ZkConnection("localhost:4712"); + final ZkClient zkClient = new ZkClient(zkConnection, CONNECTION_TIMEOUT); + + gateway.stop(); + final Holder exceptionHolder = new Holder(); + Thread actionThread = new Thread() { + @Override + public void run() { + try { + zkClient.createPersistent("/root"); + } catch (Exception e) { + exceptionHolder.set(e); + } + } + }; + actionThread.start(); + zkClient.close(); + actionThread.join(); + + assertThat(exceptionHolder.get()).isNotNull().isInstanceOf(IllegalStateException.class).hasMessageContaining("ZkClient already closed!"); + } + + @Test(timeout = 10000) + public void testReadWithTimeout() throws Exception { + final ZkClient zkClient = new ZkClient("localhost:4711", 5000, CONNECTION_TIMEOUT, new SerializableSerializer(), 5000); + // shutdown the server + LOG.info("Shutting down zookeeper server " + _zkServer); + _zkServer.shutdown(); + // now invoke read operation through the client + try { + LOG.info("Invoking read on ZkClient when ZK server is down"); + zkClient.readData("/b"); + fail("A timeout exception was expected while performing a read through ZkClient, when ZK server is down"); + } catch (ZkTimeoutException zkte) { + // expected + LOG.info("Received the *expected* timeout exception while doing an operation through ZkClient", zkte); + } + } + + @Test(timeout = 30000) + public void testRetryWithTimeout() throws Exception { + final ZkClient zkClient = new ZkClient("localhost:4711", CONNECTION_TIMEOUT, CONNECTION_TIMEOUT, new SerializableSerializer(), 5000); + // shutdown the server + LOG.info("Shutting down zookeeper server " + _zkServer); + _zkServer.shutdown(); + // test the retry method directly + try { + LOG.info("Invoking retryUntilConnected on ZkClient when ZK server is down"); + zkClient.retryUntilConnected(new Callable() { + @Override + public Boolean call() throws Exception { + return zkClient._connection.exists("/b", true); + } + }); + fail("A timeout exception was expected while performing an operation through ZkClient with the ZK server down"); + } catch (ZkTimeoutException zkte) { + // expected + LOG.info("Received the *expected* timeout exception from ZkClient.retryUntilConnected", zkte); + } + } + + @Test(timeout = 15000) + public void testWaitUntilConnected() throws Exception { + LOG.info("--- testWaitUntilConnected"); + ZkClient _client = new ZkClient("localhost:4711", CONNECTION_TIMEOUT); + + _zkServer.shutdown(); + + // the _client state should change to KeeperState.Disconnected + assertTrue(_client.waitForKeeperState(KeeperState.Disconnected, 1, TimeUnit.SECONDS)); + + // connection should not be possible and timeout after 100ms + assertFalse(_client.waitUntilConnected(100, TimeUnit.MILLISECONDS)); + } + + @Test(timeout = 15000) + public void testRetryUntilConnected_SessionExpiredException() { + LOG.info("--- testRetryUntilConnected_SessionExpiredException"); + + // Use a tick time of 100ms, because the minimum session timeout is 2 x tick-time. + // ZkServer zkServer = TestUtil.startZkServer("ZkClientTest-testSessionExpiredException", 4711, 100); + Gateway gateway = new Gateway(4712, 4711); + gateway.start(); + + // Use a session timeout of 200ms + final ZkClient zkClient = new ZkClient("localhost:4712", 200, CONNECTION_TIMEOUT); + + gateway.stop(); + + // Start server in 600ms, the session should have expired by then + new DeferredGatewayStarter(gateway, 600).start(); + + // This should work as soon as a new session has been created (and the connection is reestablished), if it fails + // it throws a SessionExpiredException + zkClient.retryUntilConnected(new Callable() { + + @Override + public Object call() throws Exception { + zkClient.exists("/a"); + return null; + } + }); + + zkClient.close(); + // zkServer.shutdown(); + gateway.stop(); + } + + @Test(timeout = 15000) + public void testChildListenerAfterSessionExpiredException() throws Exception { + LOG.info("--- testChildListenerAfterSessionExpiredException"); + + int sessionTimeout = 200; + ZkClient connectedClient = _zkServer.getZkClient(); + connectedClient.createPersistent("/root"); + + Gateway gateway = new Gateway(4712, 4711); + gateway.start(); + + final ZkClient disconnectedZkClient = new ZkClient("localhost:4712", sessionTimeout, CONNECTION_TIMEOUT); + final Holder> children = new Holder>(); + disconnectedZkClient.subscribeChildChanges("/root", new IZkChildListener() { + + @Override + public void handleChildChange(String parentPath, List currentChilds) throws Exception { + children.set(currentChilds); + } + }); + + gateway.stop(); + + // The connected client now created a new child node + connectedClient.createPersistent("/root/node"); + + // Wait for 3 x sessionTimeout, the session should have expired by then and start the gateway again + Thread.sleep(sessionTimeout * 3); + gateway.start(); + + Boolean hasOneChild = TestUtil.waitUntil(true, new Callable() { + + @Override + public Boolean call() throws Exception { + return children.get() != null && children.get().size() == 1; + } + }, TimeUnit.SECONDS, 30); + + assertTrue(hasOneChild); + + disconnectedZkClient.close(); + gateway.stop(); + } + + @Test(timeout = 10000) + public void testZkClientConnectedToGatewayClosesQuickly() throws Exception { + LOG.info("--- testZkClientConnectedToGatewayClosesQuickly"); + final Gateway gateway = new Gateway(4712, 4711); + gateway.start(); + + ZkClient zkClient = new ZkClient("localhost:4712", CONNECTION_TIMEOUT); + zkClient.close(); + + gateway.stop(); + } + + @Test + public void testCountChildren() throws InterruptedException { + assertEquals(0, _client.countChildren("/a")); + _client.createPersistent("/a"); + assertEquals(0, _client.countChildren("/a")); + _client.createPersistent("/a/b"); + assertEquals(1, _client.countChildren("/a")); + + // test concurrent access + Thread thread = new Thread() { + @Override + public void run() { + try { + while (!isInterrupted()) { + _client.createPersistent("/test"); + _client.delete("/test"); + } + } catch (ZkInterruptedException e) { + // ignore and finish + } + } + }; + + thread.start(); + for (int i = 0; i < 1000; i++) { + assertEquals(0, _client.countChildren("/test")); + } + thread.interrupt(); + thread.join(); + } + + @Test + public void testReadDataWithStat() { + _client.createPersistent("/a", "data"); + Stat stat = new Stat(); + _client.readData("/a", stat); + assertEquals(0, stat.getVersion()); + assertTrue(stat.getDataLength() > 0); + } + + @Test + public void testWriteDataWithExpectedVersion() { + _client.createPersistent("/a", "data"); + _client.writeData("/a", "data2", 0); + + try { + _client.writeData("/a", "data3", 0); + fail("expected exception"); + } catch (ZkBadVersionException e) { + // expected + } + } + + @Test + public void testCreateWithParentDirs() { + String path = "/a/b"; + try { + _client.createPersistent(path, false); + fail("should throw exception"); + } catch (ZkNoNodeException e) { + assertFalse(_client.exists(path)); + } + + _client.createPersistent(path, true); + assertTrue(_client.exists(path)); + } + + @Test + public void testUpdateSerialized() throws InterruptedException { + _client.createPersistent("/a", 0); + + int numberOfThreads = 2; + final int numberOfIncrementsPerThread = 100; + + List threads = new ArrayList(); + for (int i = 0; i < numberOfThreads; i++) { + Thread thread = new Thread() { + @Override + public void run() { + for (int j = 0; j < numberOfIncrementsPerThread; j++) { + _client.updateDataSerialized("/a", new DataUpdater() { + + @Override + public Integer update(Integer integer) { + return integer + 1; + } + }); + } + } + }; + thread.start(); + threads.add(thread); + } + + for (Thread thread : threads) { + thread.join(); + } + + Integer finalValue = _client.readData("/a"); + assertEquals(numberOfIncrementsPerThread * numberOfThreads, finalValue.intValue()); + } +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/TestUtil.java b/zkclient/src/test/java/org/I0Itec/zkclient/TestUtil.java new file mode 100644 index 00000000000..435083005da --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/TestUtil.java @@ -0,0 +1,115 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import static org.mockito.Mockito.mock; + +import java.io.File; +import java.io.IOException; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.io.FileUtils; +import org.junit.rules.TemporaryFolder; +import org.mockito.exceptions.base.MockitoAssertionError; + +public class TestUtil { + + /** + * This waits until the provided {@link Callable} returns an object that is equals to the given expected value or + * the timeout has been reached. In both cases this method will return the return value of the latest + * {@link Callable} execution. + * + * @param expectedValue + * The expected value of the callable. + * @param callable + * The callable. + * @param + * The return type of the callable. + * @param timeUnit + * The timeout timeunit. + * @param timeout + * The timeout. + * @return the return value of the latest {@link Callable} execution. + * @throws Exception + * @throws InterruptedException + */ + public static T waitUntil(T expectedValue, Callable callable, TimeUnit timeUnit, long timeout) throws Exception { + long startTime = System.currentTimeMillis(); + do { + T actual = callable.call(); + if (expectedValue.equals(actual)) { + return actual; + } + if (System.currentTimeMillis() > startTime + timeUnit.toMillis(timeout)) { + return actual; + } + Thread.sleep(50); + } while (true); + } + + /** + * This waits until a mockito verification passed (which is provided in the runnable). This waits until the + * virification passed or the timeout has been reached. If the timeout has been reached this method will rethrow the + * {@link MockitoAssertionError} that comes from the mockito verification code. + * + * @param runnable + * The runnable containing the mockito verification. + * @param timeUnit + * The timeout timeunit. + * @param timeout + * The timeout. + * @throws InterruptedException + */ + public static void waitUntilVerified(Runnable runnable, TimeUnit timeUnit, int timeout) throws InterruptedException { + long startTime = System.currentTimeMillis(); + do { + MockitoAssertionError exception = null; + try { + runnable.run(); + } catch (MockitoAssertionError e) { + exception = e; + } + if (exception == null) { + return; + } + if (System.currentTimeMillis() > startTime + timeUnit.toMillis(timeout)) { + throw exception; + } + Thread.sleep(50); + } while (true); + } + + public static ZkServer startZkServer(TemporaryFolder temporaryFolder, int port) throws IOException { + File dataFolder = temporaryFolder.newFolder("data"); + File logFolder = temporaryFolder.newFolder("log"); + return startServer(port, dataFolder.getAbsolutePath(), logFolder.getAbsolutePath()); + } + + public static ZkServer startZkServer(String testName, int port) throws IOException { + String dataPath = "./build/test/" + testName + "/data"; + String logPath = "./build/test/" + testName + "/log"; + FileUtils.deleteDirectory(new File(dataPath)); + FileUtils.deleteDirectory(new File(logPath)); + return startServer(port, dataPath, logPath); + } + + private static ZkServer startServer(int port, String dataPath, String logPath) { + ZkServer zkServer = new ZkServer(dataPath, logPath, mock(IDefaultNameSpace.class), port, ZkServer.DEFAULT_TICK_TIME, 100); + zkServer.start(); + return zkServer; + } +} \ No newline at end of file diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/ZkAuthTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/ZkAuthTest.java new file mode 100644 index 00000000000..b7da07e49c0 --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/ZkAuthTest.java @@ -0,0 +1,66 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 org.I0Itec.zkclient; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.ZooDefs; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ZkAuthTest extends AbstractAuthTest { + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + _zkServer = TestUtil.startZkServer("ZkClientTest", 4711); + _client = new ZkClient("localhost:4711", 25000); + } + + @Override + @After + public void tearDown() throws Exception { + super.tearDown(); + if (_client != null) { + _client.close(); + } + _zkServer.shutdown(); + } + + @Test + public void testAuthorized() { + _client.addAuthInfo("digest", "pat:pass".getBytes()); + _client.create("/path1", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); + _client.readData("/path1"); + } + + @Test + public void testSetAndGetAcls() { + _client.addAuthInfo("digest", "pat:pass".getBytes()); + + _client.create("/path1", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + assertThat(_client.getAcl("/path1").getKey()).isEqualTo(ZooDefs.Ids.OPEN_ACL_UNSAFE); + + for (int i = 0; i < 100; i++) { + _client.setAcl("/path1", ZooDefs.Ids.OPEN_ACL_UNSAFE); + assertThat(_client.getAcl("/path1").getKey()).isEqualTo(ZooDefs.Ids.OPEN_ACL_UNSAFE); + } + } +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/ZkClientSerializationTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/ZkClientSerializationTest.java new file mode 100644 index 00000000000..0536c7c85b2 --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/ZkClientSerializationTest.java @@ -0,0 +1,52 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.util.Random; + +import org.I0Itec.zkclient.serialize.BytesPushThroughSerializer; +import org.I0Itec.zkclient.serialize.SerializableSerializer; +import org.I0Itec.zkclient.testutil.ZkTestSystem; +import org.junit.Rule; +import org.junit.Test; + +public class ZkClientSerializationTest { + + @Rule + public ZkTestSystem _zk = ZkTestSystem.getInstance(); + + @Test + public void testBytes() throws Exception { + ZkClient zkClient = new ZkClient(_zk.getZkServerAddress(), 2000, 30000, new BytesPushThroughSerializer()); + byte[] bytes = new byte[100]; + new Random().nextBytes(bytes); + zkClient.createPersistent("/a", bytes); + byte[] readBytes = zkClient.readData("/a"); + assertArrayEquals(bytes, readBytes); + } + + @Test + public void testSerializables() throws Exception { + ZkClient zkClient = new ZkClient(_zk.getZkServerAddress(), 2000, 30000, new SerializableSerializer()); + String data = "hello world"; + zkClient.createPersistent("/a", data); + String readData = zkClient.readData("/a"); + assertEquals(data, readData); + } +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/ZkConnectionTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/ZkConnectionTest.java new file mode 100644 index 00000000000..5ace6f43520 --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/ZkConnectionTest.java @@ -0,0 +1,36 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient; + +import org.I0Itec.zkclient.testutil.ZkTestSystem; +import org.junit.Rule; + +public class ZkConnectionTest extends AbstractConnectionTest { + + @Rule + public ZkTestSystem _zk = ZkTestSystem.getInstance(); + + public ZkConnectionTest() { + super(establishConnection()); + } + + private static ZkConnection establishConnection() { + ZkConnection zkConnection = new ZkConnection("localhost:" + ZkTestSystem.getInstance().getZkServer().getPort()); + new ZkClient(zkConnection);// connect + return zkConnection; + } + +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/ZkStateChangeTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/ZkStateChangeTest.java new file mode 100644 index 00000000000..4bb0478905a --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/ZkStateChangeTest.java @@ -0,0 +1,230 @@ +package org.I0Itec.zkclient; + +import static org.junit.Assert.assertEquals; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; + +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.Watcher.Event.KeeperState; +import org.apache.zookeeper.ZooKeeper.States; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Stat; +import org.apache.zookeeper.Op; +import org.apache.zookeeper.OpResult; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class ZkStateChangeTest { + + private StateOnlyConnection zkConn; + private ZkClient client; + private TestStateListener listener; + + @Before + public void setUp() { + zkConn = new StateOnlyConnection(); + client = new ZkClient(zkConn); + listener = new TestStateListener(); + client.subscribeStateChanges(listener); + } + + @After + public void tearDown() { + client.close(); + } + + @Test + public void testNewSessionEvent() throws Exception { + zkConn.expireSession(); + assertTimed(1, new Callable() { + @Override + public Integer call() throws Exception { + return listener.expiredEvents; + } + }); + + assertTimed(0, new Callable() { + @Override + public Integer call() throws Exception { + return listener.sessionEstablishErrors; + } + }); + + assertTimed(1, new Callable() { + @Override + public Integer call() throws Exception { + return listener.newSessionEvent; + } + }); + } + + @Test + public void testFailConnectEvent() throws Exception { + zkConn.setFailOnConnect(true); + zkConn.expireSession(); + assertTimed(1, new Callable() { + @Override + public Integer call() throws Exception { + return listener.expiredEvents; + } + }); + + assertTimed(1, new Callable() { + @Override + public Integer call() throws Exception { + return listener.sessionEstablishErrors; + } + }); + + assertTimed(0, new Callable() { + @Override + public Integer call() throws Exception { + return listener.newSessionEvent; + } + }); + + client.close(); + } + + private void assertTimed(T expectedVal, Callable condition) throws Exception { + assertEquals(expectedVal, TestUtil.waitUntil(expectedVal, condition, TimeUnit.SECONDS, 5)); + } + + private static class StateOnlyConnection implements IZkConnection { + private Watcher _watcher; + private boolean failOnConnect = false; + + @Override + public void connect(Watcher w) { + _watcher = w; + if (failOnConnect) { + // As as example: + throw new RuntimeException("Testing connection failure"); + } + new Thread() { + @Override + public void run() { + _watcher.process(new WatchedEvent(null, KeeperState.SyncConnected, null)); + } + }.start(); + } + + public void expireSession() { + _watcher.process(new WatchedEvent(null, KeeperState.Expired, null)); + } + + public void setFailOnConnect(boolean failFlag) { + this.failOnConnect = failFlag; + } + + @Override + public void close() throws InterruptedException { + + } + + @Override + public String create(String path, byte[] data, CreateMode mode) throws KeeperException, InterruptedException { + throw new RuntimeException("not implemented"); + } + + @Override + public String create(String path, byte[] data, List acl, CreateMode mode) throws KeeperException, InterruptedException { + throw new RuntimeException("not implemented"); + } + + @Override + public void delete(String path) throws InterruptedException, KeeperException { + throw new RuntimeException("not implemented"); + } + + @Override + public boolean exists(final String path, final boolean watch) throws KeeperException, InterruptedException { + throw new RuntimeException("not implemented"); + } + + public List getChildren(final String path, final boolean watch) throws KeeperException, InterruptedException { + throw new RuntimeException("not implemented"); + } + + @Override + public byte[] readData(String path, Stat stat, boolean watch) throws KeeperException, InterruptedException { + throw new RuntimeException("not implemented"); + } + + @Override + public void writeData(String path, byte[] data, int expectedVersion) throws KeeperException, InterruptedException { + throw new RuntimeException("not implemented"); + } + + @Override + public Stat writeDataReturnStat(String path, byte[] data, int expectedVersion) throws KeeperException, InterruptedException { + throw new RuntimeException("not implemented"); + } + + @Override + public States getZookeeperState() { + throw new RuntimeException("not implemented"); + } + + @Override + public long getCreateTime(String path) throws KeeperException, InterruptedException { + throw new RuntimeException("not implemented"); + } + + @Override + public String getServers() { + return "test"; + } + + @Override + public List multi(Iterable ops) throws KeeperException, InterruptedException { + throw new UnsupportedOperationException(); + } + + @Override + public void addAuthInfo(String scheme, byte[] auth) { + throw new RuntimeException("not implemented"); + } + + @Override + public void setAcl(String path, List acl, int version) throws KeeperException, InterruptedException { + throw new UnsupportedOperationException(); + } + + @Override + public Map.Entry, Stat> getAcl(String path) throws KeeperException, InterruptedException { + throw new UnsupportedOperationException(); + } + } + + private static class TestStateListener implements IZkStateListener { + public int expiredEvents = 0; + public int newSessionEvent = 0; + public int sessionEstablishErrors = 0; + + @Override + public void handleStateChanged(KeeperState state) throws Exception { + if (state == KeeperState.Expired) { + expiredEvents++; + } + } + + @Override + public void handleNewSession() throws Exception { + newSessionEvent++; + } + + @Override + public void handleSessionEstablishmentError(final Throwable error) throws Exception { + sessionEstablishErrors++; + } + } + +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/testutil/ZkTestSystem.java b/zkclient/src/test/java/org/I0Itec/zkclient/testutil/ZkTestSystem.java new file mode 100644 index 00000000000..127fe32e6df --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/testutil/ZkTestSystem.java @@ -0,0 +1,120 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient.testutil; + +import org.I0Itec.zkclient.IDefaultNameSpace; +import org.I0Itec.zkclient.ZkClient; +import org.I0Itec.zkclient.ZkServer; +import org.apache.commons.io.FileUtils; +import org.junit.rules.ExternalResource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +import static org.mockito.Mockito.mock; + +public class ZkTestSystem extends ExternalResource { + + //protected static final Logger LOG = Logger.getLogger(ZkTestSystem.class); + + protected static final Logger LOG = LoggerFactory.getLogger(ZkTestSystem.class); + + private static int PORT = 10002; + private static ZkTestSystem _instance; + private ZkServer _zkServer; + + private ZkTestSystem() { + LOG.info("~~~~~~~~~~~~~~~ starting zk system ~~~~~~~~~~~~~~~"); + String baseDir = "build/zkdata"; + try { + FileUtils.deleteDirectory(new File(baseDir)); + } catch (IOException e) { + throw new RuntimeException(e); + } + String dataDir = baseDir + "/data"; + String logDir = baseDir + "/log"; + _zkServer = new ZkServer(dataDir, logDir, mock(IDefaultNameSpace.class), PORT); + _zkServer.start(); + LOG.info("~~~~~~~~~~~~~~~ zk system started ~~~~~~~~~~~~~~~"); + } + + @Override + // executed before every test method + protected void before() throws Throwable { + cleanupZk(); + } + + @Override + // executed after every test method + protected void after() { + cleanupZk(); + } + + private void cleanupZk() { + LOG.info("cleanup zk namespace"); + List children = getZkClient().getChildren("/"); + for (String child : children) { + if (!child.equals("zookeeper")) { + getZkClient().deleteRecursive("/" + child); + } + } + LOG.info("unsubscribing " + getZkClient().numberOfListeners() + " listeners"); + getZkClient().unsubscribeAll(); + } + + public static ZkTestSystem getInstance() { + if (_instance == null) { + _instance = new ZkTestSystem(); + _instance.cleanupZk(); + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + LOG.info("shutting zk down"); + getInstance().getZkServer().shutdown(); + } + }); + } + return _instance; + } + + public ZkServer getZkServer() { + return _zkServer; + } + + public String getZkServerAddress() { + return "localhost:" + getServerPort(); + } + + public ZkClient getZkClient() { + return _zkServer.getZkClient(); + } + + public int getServerPort() { + return PORT; + } + + public ZkClient createZkClient() { + return new ZkClient("localhost:" + PORT); + } + + public void showStructure() { + getZkClient().showFolders(System.out); + } + +} diff --git a/zkclient/src/test/java/org/I0Itec/zkclient/util/ZkPathUtilTest.java b/zkclient/src/test/java/org/I0Itec/zkclient/util/ZkPathUtilTest.java new file mode 100644 index 00000000000..2178b4981da --- /dev/null +++ b/zkclient/src/test/java/org/I0Itec/zkclient/util/ZkPathUtilTest.java @@ -0,0 +1,69 @@ +/** + * Copyright 2010 the original author or authors. + * + * 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 org.I0Itec.zkclient.util; + +import junit.framework.TestCase; + +import org.I0Itec.zkclient.TestUtil; +import org.I0Itec.zkclient.ZkClient; +import org.I0Itec.zkclient.ZkServer; + +public class ZkPathUtilTest extends TestCase { + + protected ZkServer _zkServer; + protected ZkClient _client; + + public void testToString() throws Exception { + _zkServer = TestUtil.startZkServer("ZkPathUtilTest", 4711); + _client = new ZkClient("localhost:4711", 30000); + final String file1 = "/files/file1"; + final String file2 = "/files/file2"; + final String file3 = "/files/file2/file3"; + _client.createPersistent(file1, true); + _client.createPersistent(file2, true); + _client.createPersistent(file3, true); + + String stringRepresentation = ZkPathUtil.toString(_client); + System.out.println(stringRepresentation); + System.out.println("-------------------------"); + assertTrue(stringRepresentation.contains("file1")); + assertTrue(stringRepresentation.contains("file2")); + assertTrue(stringRepresentation.contains("file3")); + + // path filtering + stringRepresentation = ZkPathUtil.toString(_client, "/", new ZkPathUtil.PathFilter() { + @Override + public boolean showChilds(String path) { + return !file2.equals(path); + } + }); + assertTrue(stringRepresentation.contains("file1")); + assertTrue(stringRepresentation.contains("file2")); + assertFalse(stringRepresentation.contains("file3")); + + // start path + stringRepresentation = ZkPathUtil.toString(_client, file2, ZkPathUtil.PathFilter.ALL); + assertFalse(stringRepresentation.contains("file1")); + assertTrue(stringRepresentation.contains("file2")); + assertTrue(stringRepresentation.contains("file3")); + + _zkServer.shutdown(); + } + + public void testLeadingZeros() throws Exception { + assertEquals("0000000001", ZkPathUtil.leadingZeros(1, 10)); + } +} diff --git a/zkclient/src/test/resources/log4j.properties b/zkclient/src/test/resources/log4j.properties new file mode 100644 index 00000000000..4b966c13d9e --- /dev/null +++ b/zkclient/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootLogger=info, console +log4j.logger.org.apache.zookeeper=error + +log4j.appender.console=org.apache.log4j.ConsoleAppender +log4j.appender.console.target=System.out +log4j.appender.console.layout=org.apache.log4j.PatternLayout +log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %5p [%t] (%F:%L) - %m%n