From 8bdecea7ef808d19f0449dd43ec85ba8dbaeeb26 Mon Sep 17 00:00:00 2001 From: "ken.lj" Date: Mon, 17 Aug 2020 13:38:04 +0800 Subject: [PATCH] Move some SPI extensions to apache/dubbo-spi-extensions, add sub package modules (#6157) --- dubbo-compatible/pom.xml | 10 + dubbo-config/dubbo-config-api/pom.xml | 23 +- .../dubbo-configcenter-apollo/pom.xml | 5 +- .../dubbo-configcenter-consul/pom.xml | 47 - .../consul/ConsulDynamicConfiguration.java | 181 - .../ConsulDynamicConfigurationFactory.java | 32 - ...g.configcenter.DynamicConfigurationFactory | 1 - .../ConsulDynamicConfigurationTest.java | 123 - .../dubbo-configcenter-etcd/pom.xml | 74 - .../etcd/EtcdDynamicConfiguration.java | 197 - .../etcd/EtcdDynamicConfigurationFactory.java | 33 - ...g.configcenter.DynamicConfigurationFactory | 1 - .../etcd/EtcdDynamicConfigurationTest.java | 154 - .../dubbo-configcenter-nacos/pom.xml | 3 +- dubbo-configcenter/pom.xml | 2 - dubbo-container/dubbo-container-log4j/pom.xml | 39 - .../dubbo/container/log4j/Log4jContainer.java | 103 - .../org.apache.dubbo.container.Container | 1 - .../container/log4j/Log4jContainerTest.java | 36 - .../dubbo-container-logback/pom.xml | 43 - .../container/logback/LogbackContainer.java | 108 - .../org.apache.dubbo.container.Container | 1 - .../logback/LogbackContainerTest.java | 47 - dubbo-container/pom.xml | 2 - .../dubbo-all}/pom.xml | 337 +- .../dubbo-apache-release/pom.xml | 100 + .../src/assembly/bin-release.xml | 4 +- .../src/assembly/source-release.xml | 2 +- .../dubbo-bom}/pom.xml | 57 +- dubbo-distribution/dubbo-core-spi/pom.xml | 444 ++ dubbo-distribution/pom.xml | 94 +- dubbo-filter/dubbo-filter-cache/pom.xml | 3 +- .../java/org/apache/dubbo/cache/Cache.java | 86 +- .../org/apache/dubbo/cache/CacheFactory.java | 86 +- .../dubbo/cache/filter/CacheFilter.java | 266 +- .../cache/support/AbstractCacheFactory.java | 144 +- .../dubbo/cache/support/jcache/JCache.java | 174 +- .../cache/support/jcache/JCacheFactory.java | 96 +- .../dubbo/cache/support/lru/LruCache.java | 160 +- .../cache/support/lru/LruCacheFactory.java | 86 +- .../support/threadlocal/ThreadLocalCache.java | 154 +- .../threadlocal/ThreadLocalCacheFactory.java | 86 +- .../org.apache.dubbo.cache.CacheFactory | 6 +- dubbo-filter/dubbo-filter-validation/pom.xml | 3 +- .../apache/dubbo/validation/Validation.java | 78 +- .../apache/dubbo/validation/Validator.java | 54 +- .../validation/filter/ValidationFilter.java | 208 +- .../support/AbstractValidation.java | 102 +- .../support/jvalidation/JValidation.java | 78 +- .../support/jvalidation/JValidator.java | 660 +-- .../dubbo-metadata-report-consul/pom.xml | 48 - .../store/consul/ConsulMetadataReport.java | 139 - .../consul/ConsulMetadataReportFactory.java | 31 - ...ubbo.metadata.report.MetadataReportFactory | 1 - .../dubbo-metadata-report-etcd/pom.xml | 70 - .../store/etcd/EtcdMetadataReport.java | 150 - .../store/etcd/EtcdMetadataReportFactory.java | 50 - ...ubbo.metadata.report.MetadataReportFactory | 1 - .../store/etcd/EtcdMetadata4TstService.java | 28 - .../store/etcd/EtcdMetadataReportTest.java | 259 - .../dubbo-metadata-report-nacos/pom.xml | 45 - .../store/nacos/NacosMetadataReport.java | 149 - .../nacos/NacosMetadataReportFactory.java | 31 - ...ubbo.metadata.report.MetadataReportFactory | 1 - .../store/nacos/NacosMetadata4TstService.java | 28 - .../dubbo-metadata-report-redis/pom.xml | 3 +- dubbo-metadata/pom.xml | 9 +- dubbo-registry/dubbo-registry-consul/pom.xml | 63 - .../consul/AbstractConsulRegistry.java | 39 - .../dubbo/registry/consul/ConsulRegistry.java | 380 -- .../consul/ConsulRegistryFactory.java | 32 - .../consul/ConsulServiceDiscovery.java | 474 -- .../org.apache.dubbo.registry.RegistryFactory | 1 - .../registry/consul/ConsulRegistryTest.java | 135 - .../consul/ConsulServiceDiscoveryTest.java | 108 - dubbo-registry/dubbo-registry-default/pom.xml | 69 - .../dubbo/registry/dubbo/DubboRegistry.java | 161 - .../registry/dubbo/DubboRegistryFactory.java | 118 - .../org.apache.dubbo.registry.RegistryFactory | 1 - .../dubbo/AbstractRegistryService.java | 237 - .../dubbo/registry/dubbo/DemoService.java | 27 - .../dubbo/registry/dubbo/DemoServiceImpl.java | 32 - .../registry/dubbo/DubboRegistryTest.java | 155 - .../dubbo/registry/dubbo/MockChannel.java | 141 - .../dubbo/registry/dubbo/MockedClient.java | 298 - .../registry/dubbo/RegistryDirectoryTest.java | 1143 ---- .../registry/dubbo/RegistryProtocolTest.java | 232 - .../dubbo/RegistryStatusCheckerTest.java | 69 - .../dubbo/SimpleRegistryExporter.java | 87 - .../registry/dubbo/SimpleRegistryService.java | 146 - .../src/test/resources/log4j.xml | 38 - dubbo-registry/dubbo-registry-etcd3/pom.xml | 52 - .../dubbo/registry/etcd/EtcdRegistry.java | 359 -- .../registry/etcd/EtcdRegistryFactory.java | 36 - .../registry/etcd/EtcdServiceDiscovery.java | 208 - .../org.apache.dubbo.registry.RegistryFactory | 1 - ...che.dubbo.registry.client.ServiceDiscovery | 1 - .../dubbo/registry/etcd/EtcdRegistryTest.java | 327 -- .../etcd/EtcdServiceDiscoveryTest.java | 124 - dubbo-registry/dubbo-registry-eureka/pom.xml | 86 - .../ConfigurableEurekaInstanceConfig.java | 369 -- .../eureka/EurekaServiceDiscovery.java | 278 - .../dubbo/registry/eureka/package-info.java | 22 - ...che.dubbo.registry.client.ServiceDiscovery | 1 - .../eureka/EurekaServiceDiscoveryTest.java | 67 - dubbo-registry/dubbo-registry-nacos/pom.xml | 3 +- dubbo-registry/dubbo-registry-redis/pom.xml | 53 - .../dubbo/registry/redis/RedisRegistry.java | 661 --- .../registry/redis/RedisRegistryFactory.java | 34 - .../org.apache.dubbo.registry.RegistryFactory | 1 - .../registry/redis/RedisRegistryTest.java | 130 - dubbo-registry/dubbo-registry-sofa/pom.xml | 134 - .../dubbo/registry/sofa/SofaRegistry.java | 300 - .../registry/sofa/SofaRegistryConstants.java | 43 - .../registry/sofa/SofaRegistryFactory.java | 41 - .../org.apache.dubbo.registry.RegistryFactory | 1 - .../dubbo/registry/sofa/HelloService.java | 24 - .../dubbo/registry/sofa/HelloServiceImpl.java | 44 - .../src/test/resources/log4j.properties | 7 - dubbo-registry/pom.xml | 12 +- dubbo-remoting/dubbo-remoting-etcd3/pom.xml | 107 - .../remoting/etcd/AbstractRetryPolicy.java | 45 - .../dubbo/remoting/etcd/ChildListener.java | 25 - .../apache/dubbo/remoting/etcd/Constants.java | 55 - .../dubbo/remoting/etcd/EtcdClient.java | 191 - .../dubbo/remoting/etcd/EtcdTransporter.java | 47 - .../dubbo/remoting/etcd/RetryPolicy.java | 31 - .../dubbo/remoting/etcd/StateListener.java | 27 - .../etcd/jetcd/ConnectionStateListener.java | 31 - .../remoting/etcd/jetcd/JEtcdClient.java | 473 -- .../etcd/jetcd/JEtcdClientWrapper.java | 754 --- .../remoting/etcd/jetcd/JEtcdTransporter.java | 30 - .../dubbo/remoting/etcd/jetcd/RetryLoops.java | 99 - .../remoting/etcd/jetcd/RetryNTimes.java | 36 - .../remoting/etcd/option/OptionUtil.java | 78 - .../etcd/support/AbstractEtcdClient.java | 194 - ...apache.dubbo.remoting.etcd.EtcdTransporter | 1 - .../remoting/etcd/jetcd/JEtcdClientTest.java | 427 -- .../etcd/jetcd/JEtcdClientWrapperTest.java | 187 - .../dubbo/remoting/etcd/jetcd/LeaseTest.java | 154 - dubbo-remoting/dubbo-remoting-grizzly/pom.xml | 43 - .../transport/grizzly/GrizzlyChannel.java | 198 - .../transport/grizzly/GrizzlyClient.java | 112 - .../grizzly/GrizzlyCodecAdapter.java | 145 - .../transport/grizzly/GrizzlyHandler.java | 118 - .../transport/grizzly/GrizzlyServer.java | 127 - .../transport/grizzly/GrizzlyTransporter.java | 43 - .../org.apache.dubbo.remoting.Transporter | 1 - .../grizzly/GrizzlyTransporterTest.java | 41 - dubbo-remoting/dubbo-remoting-http/pom.xml | 62 - .../dubbo/remoting/http/HttpBinder.java | 39 - .../dubbo/remoting/http/HttpHandler.java | 39 - .../dubbo/remoting/http/HttpServer.java | 72 - .../remoting/http/jetty/JettyHttpBinder.java | 34 - .../remoting/http/jetty/JettyHttpServer.java | 112 - .../http/servlet/BootstrapListener.java | 37 - .../http/servlet/DispatcherServlet.java | 65 - .../http/servlet/ServletHttpBinder.java | 34 - .../http/servlet/ServletHttpServer.java | 31 - .../remoting/http/servlet/ServletManager.java | 50 - .../http/support/AbstractHttpServer.java | 134 - .../http/tomcat/TomcatHttpBinder.java | 31 - .../http/tomcat/TomcatHttpServer.java | 95 - .../org.apache.dubbo.remoting.http.HttpBinder | 3 - .../http/jetty/JettyHttpBinderTest.java | 53 - .../http/tomcat/TomcatHttpBinderTest.java | 55 - dubbo-remoting/dubbo-remoting-mina/pom.xml | 53 - .../remoting/transport/mina/MinaChannel.java | 191 - .../remoting/transport/mina/MinaClient.java | 174 - .../transport/mina/MinaCodecAdapter.java | 167 - .../remoting/transport/mina/MinaHandler.java | 95 - .../remoting/transport/mina/MinaServer.java | 112 - .../transport/mina/MinaTransporter.java | 40 - .../org.apache.dubbo.remoting.Transporter | 1 - .../transport/mina/ClientToServerTest.java | 92 - .../remoting/transport/mina/ClientsTest.java | 65 - .../apache/remoting/transport/mina/Hello.java | 45 - .../mina/MinaClientToServerTest.java | 41 - .../apache/remoting/transport/mina/World.java | 45 - .../remoting/transport/mina/WorldHandler.java | 36 - dubbo-remoting/dubbo-remoting-p2p/pom.xml | 45 - .../org/apache/dubbo/remoting/p2p/Group.java | 57 - .../apache/dubbo/remoting/p2p/Networker.java | 39 - .../apache/dubbo/remoting/p2p/Networkers.java | 47 - .../org/apache/dubbo/remoting/p2p/Peer.java | 36 - .../remoting/p2p/exchange/ExchangeGroup.java | 36 - .../p2p/exchange/ExchangeNetworker.java | 35 - .../p2p/exchange/ExchangeNetworkers.java | 45 - .../remoting/p2p/exchange/ExchangePeer.java | 26 - .../support/AbstractExchangeGroup.java | 128 - .../exchange/support/ExchangeServerPeer.java | 137 - .../exchange/support/FileExchangeGroup.java | 135 - .../support/FileExchangeNetworker.java | 34 - .../support/MulticastExchangeGroup.java | 108 - .../support/MulticastExchangeNetworker.java | 34 - .../remoting/p2p/support/AbstractGroup.java | 119 - .../dubbo/remoting/p2p/support/FileGroup.java | 133 - .../remoting/p2p/support/FileNetworker.java | 34 - .../remoting/p2p/support/MulticastGroup.java | 108 - .../p2p/support/MulticastNetworker.java | 34 - .../remoting/p2p/support/ServerPeer.java | 124 - .../org.apache.dubbo.remoting.p2p.Networker | 2 - .../MulticastExchangeNetworkerTest.java | 81 - .../p2p/support/FileNetworkerTest.java | 83 - .../p2p/support/MulticastNetworkerTest.java | 70 - dubbo-remoting/pom.xml | 5 - dubbo-rpc/dubbo-rpc-hessian/pom.xml | 63 - .../dubbo/rpc/protocol/hessian/Constants.java | 35 - .../DubboHessianURLConnectionFactory.java | 41 - .../rpc/protocol/hessian/HessianProtocol.java | 202 - .../hessian/HttpClientConnection.java | 99 - .../hessian/HttpClientConnectionFactory.java | 58 - .../internal/org.apache.dubbo.rpc.Protocol | 1 - .../protocol/hessian/HessianProtocolTest.java | 250 - .../rpc/protocol/hessian/HessianService.java | 37 - .../protocol/hessian/HessianServiceImpl.java | 75 - dubbo-rpc/dubbo-rpc-http/pom.xml | 62 - .../dubbo/rpc/protocol/http/HttpProtocol.java | 191 - .../protocol/http/HttpProtocolErrorCode.java | 29 - .../protocol/http/JsonRemoteInvocation.java | 61 - .../http/JsonRpcProxyFactoryBean.java | 86 - .../internal/org.apache.dubbo.rpc.Protocol | 1 - .../rpc/protocol/http/HttpProtocolTest.java | 92 - .../dubbo/rpc/protocol/http/HttpService.java | 27 - .../rpc/protocol/http/HttpServiceImpl.java | 58 - dubbo-rpc/dubbo-rpc-memcached/pom.xml | 43 - .../protocol/memcached/MemcachedProtocol.java | 122 - .../internal/org.apache.dubbo.rpc.Protocol | 1 - .../memcached/MemcachedProtocolTest.java | 21 - dubbo-rpc/dubbo-rpc-native-thrift/pom.xml | 50 - .../protocol/nativethrift/ThriftProtocol.java | 189 - .../internal/org.apache.dubbo.rpc.Protocol | 1 - .../src/test/idls/DemoService.thrift | 17 - .../src/test/idls/UserService.thrift | 6 - .../protocol/nativethrift/DemoService.java | 5141 ----------------- .../nativethrift/DemoServiceImpl.java | 78 - .../nativethrift/ThriftProtocolTest.java | 84 - .../protocol/nativethrift/UserService.java | 952 --- .../nativethrift/UserServiceImpl.java | 24 - dubbo-rpc/dubbo-rpc-redis/pom.xml | 59 - .../rpc/protocol/redis/RedisProtocol.java | 187 - .../internal/org.apache.dubbo.rpc.Protocol | 1 - .../rpc/protocol/redis/IDemoService.java | 29 - .../rpc/protocol/redis/RedisProtocolTest.java | 230 - ...pache.dubbo.common.serialize.Serialization | 1 - dubbo-rpc/dubbo-rpc-rmi/pom.xml | 43 - .../rpc/protocol/rmi/RmiRemoteInvocation.java | 39 - .../dubbo/rpc/protocol/rmi/RmiProtocol.java | 154 - .../rpc/protocol/rmi/RmiRemoteInvocation.java | 64 - .../internal/org.apache.dubbo.rpc.Protocol | 1 - .../dubbo/rpc/protocol/rmi/DemoService.java | 47 - .../rpc/protocol/rmi/DemoServiceImpl.java | 89 - .../dubbo/rpc/protocol/rmi/RemoteService.java | 26 - .../rpc/protocol/rmi/RemoteServiceImpl.java | 32 - .../rpc/protocol/rmi/RmiProtocolTest.java | 227 - .../apache/dubbo/rpc/protocol/rmi/Type.java | 21 - dubbo-rpc/dubbo-rpc-thrift/pom.xml | 74 - .../protocol/thrift/ClassNameGenerator.java | 31 - .../thrift/DubboClassNameGenerator.java | 36 - .../thrift/ThriftClassNameGenerator.java | 36 - .../rpc/protocol/thrift/ThriftCodec.java | 697 --- .../rpc/protocol/thrift/ThriftConstants.java | 32 - .../rpc/protocol/thrift/ThriftInvoker.java | 171 - .../protocol/thrift/ThriftNativeCodec.java | 96 - .../rpc/protocol/thrift/ThriftProtocol.java | 272 - .../dubbo/rpc/protocol/thrift/ThriftType.java | 51 - .../rpc/protocol/thrift/ThriftUtils.java | 135 - .../thrift/ext/MultiServiceProcessor.java | 121 - .../thrift/io/InputStreamWrapper.java | 88 - .../io/RandomAccessByteArrayOutputStream.java | 117 - .../internal/org.apache.dubbo.remoting.Codec2 | 1 - .../internal/org.apache.dubbo.rpc.Protocol | 1 - ...bbo.rpc.protocol.thrift.ClassNameGenerator | 2 - .../test/java/$__ClassNameTestDubboStub.java | 681 --- .../src/test/java/ClassNameTest.java | 45 - .../src/test/java/ClassNameTestDubbo.java | 29 - .../src/test/java/ClassNameTestThrift.java | 767 --- .../dubbo/rpc/gen/dubbo/$__DemoStub.java | 4347 -------------- .../org/apache/dubbo/rpc/gen/dubbo/Demo.java | 42 - .../org/apache/dubbo/rpc/gen/thrift/Demo.java | 4753 --------------- .../rpc/protocol/thrift/AbstractTest.java | 150 - .../dubbo/rpc/protocol/thrift/DemoImpl.java | 56 - .../rpc/protocol/thrift/DubboDemoImpl.java | 23 - .../thrift/FramedTransportFactory.java | 30 - .../rpc/protocol/thrift/MockedChannel.java | 116 - .../protocol/thrift/ServerExceptionTest.java | 100 - .../thrift/ServiceMethodNotFoundTest.java | 146 - .../rpc/protocol/thrift/ThriftCodecTest.java | 477 -- .../rpc/protocol/thrift/ThriftDemoImpl.java | 22 - .../protocol/thrift/ThriftProtocolTest.java | 87 - .../rpc/protocol/thrift/ThriftUtilsTest.java | 88 - .../thrift/examples/DubboDemoConsumer.java | 36 - .../thrift/examples/DubboDemoProvider.java | 31 - .../test/resources/dubbo-demo-consumer.xml | 32 - .../test/resources/dubbo-demo-provider.xml | 34 - .../src/test/thrift/ClassNameTestDubbo.thrift | 3 - .../test/thrift/ClassNameTestThrift.thrift | 3 - .../src/test/thrift/Demo.thrift | 16 - dubbo-rpc/dubbo-rpc-webservice/pom.xml | 77 - .../webservice/WebServiceProtocol.java | 211 - .../internal/org.apache.dubbo.rpc.Protocol | 1 - .../rpc/protocol/webservice/DemoService.java | 43 - .../protocol/webservice/DemoServiceImpl.java | 80 - .../dubbo/rpc/protocol/webservice/User.java | 38 - .../webservice/WebserviceProtocolTest.java | 167 - dubbo-rpc/dubbo-rpc-xml/README.md | 88 - dubbo-rpc/dubbo-rpc-xml/pom.xml | 67 - .../rpc/protocol/xmlrpc/XmlRpcProtocol.java | 196 - .../xmlrpc/XmlRpcProxyFactoryBean.java | 142 - .../org.apache.dubbo.remoting.http.HttpBinder | 1 - .../internal/org.apache.dubbo.rpc.Protocol | 1 - .../protocol/xmlrpc/XmlRpcProtocolTest.java | 90 - .../rpc/protocol/xmlrpc/XmlRpcService.java | 25 - .../protocol/xmlrpc/XmlRpcServiceImpl.java | 51 - dubbo-rpc/pom.xml | 9 - .../dubbo-serialization-avro/pom.xml | 45 - .../serialize/avro/AvroObjectInput.java | 118 - .../serialize/avro/AvroObjectOutput.java | 106 - .../serialize/avro/AvroSerialization.java | 52 - ...pache.dubbo.common.serialize.Serialization | 1 - .../dubbo-serialization-fastjson/pom.xml | 44 - .../fastjson/FastJsonObjectInput.java | 121 - .../fastjson/FastJsonObjectOutput.java | 113 - .../fastjson/FastJsonSerialization.java | 59 - ...pache.dubbo.common.serialize.Serialization | 1 - .../dubbo-serialization-fst/pom.xml | 43 - .../common/serialize/fst/FstFactory.java | 53 - .../common/serialize/fst/FstObjectInput.java | 117 - .../common/serialize/fst/FstObjectOutput.java | 106 - .../serialize/fst/FstSerialization.java | 58 - ...pache.dubbo.common.serialize.Serialization | 1 - .../dubbo-serialization-gson/pom.xml | 43 - .../serialize/gson/GsonJsonObjectInput.java | 121 - .../serialize/gson/GsonJsonObjectOutput.java | 108 - .../serialize/gson/GsonSerialization.java | 53 - ...pache.dubbo.common.serialize.Serialization | 1 - .../gson/GsonJsonObjectOutputTest.java | 143 - .../gson/GsonJsonSerializationTest.java | 64 - .../dubbo/common/serialize/gson/Image.java | 120 - .../dubbo-serialization-kryo/pom.xml | 48 - .../common/serialize/kryo/CompatibleKryo.java | 54 - .../serialize/kryo/KryoObjectInput.java | 162 - .../serialize/kryo/KryoObjectOutput.java | 118 - .../serialize/kryo/KryoSerialization.java | 58 - .../kryo/optimized/KryoObjectInput2.java | 168 - .../kryo/optimized/KryoObjectOutput2.java | 122 - .../kryo/optimized/KryoSerialization2.java | 57 - .../kryo/utils/AbstractKryoFactory.java | 158 - .../serialize/kryo/utils/KryoUtils.java | 44 - .../kryo/utils/PooledKryoFactory.java | 40 - .../kryo/utils/PrototypeKryoFactory.java | 32 - .../serialize/kryo/utils/ReflectionUtils.java | 33 - .../kryo/utils/ThreadLocalKryoFactory.java | 39 - ...pache.dubbo.common.serialize.Serialization | 2 - .../pom.xml | 43 - .../hessian/Hessian2ObjectInput.java | 98 - .../hessian/Hessian2ObjectOutput.java | 95 - .../hessian/Hessian2Serialization.java | 53 - .../hessian/Hessian2SerializerFactory.java | 42 - .../hessian/Java8SerializerFactory.java | 88 - .../serializer/java8/DurationHandle.java | 53 - .../serializer/java8/InstantHandle.java | 54 - .../serializer/java8/Java8TimeSerializer.java | 57 - .../serializer/java8/LocalDateHandle.java | 55 - .../serializer/java8/LocalDateTimeHandle.java | 55 - .../serializer/java8/LocalTimeHandle.java | 57 - .../serializer/java8/MonthDayHandle.java | 53 - .../java8/OffsetDateTimeHandle.java | 55 - .../serializer/java8/OffsetTimeHandle.java | 55 - .../serializer/java8/PeriodHandle.java | 56 - .../hessian/serializer/java8/YearHandle.java | 52 - .../serializer/java8/YearMonthHandle.java | 53 - .../serializer/java8/ZoneIdHandle.java | 52 - .../serializer/java8/ZoneIdSerializer.java | 43 - .../serializer/java8/ZoneOffsetHandle.java | 51 - .../serializer/java8/ZonedDateTimeHandle.java | 62 - ...pache.dubbo.common.serialize.Serialization | 1 - .../hessian/Java8TimeSerializerTest.java | 150 - .../dubbo-serialization-protobuf/pom.xml | 97 - .../GenericProtobufJsonObjectInput.java | 164 - .../GenericProtobufJsonObjectOutput.java | 161 - .../GenericProtobufJsonSerialization.java | 54 - .../support/GenericProtobufObjectInput.java | 146 - .../support/GenericProtobufObjectOutput.java | 157 - .../support/GenericProtobufSerialization.java | 63 - .../protobuf/support/ProtobufUtils.java | 206 - .../support/ProtobufWrappedException.java | 68 - .../src/main/proto/MapValue.proto | 27 - .../src/main/proto/ThrowablePB.proto | 64 - ...pache.dubbo.common.serialize.Serialization | 2 - .../dubbo-serialization-protostuff/pom.xml | 54 - .../protostuff/ProtostuffObjectInput.java | 136 - .../protostuff/ProtostuffObjectOutput.java | 130 - .../protostuff/ProtostuffSerialization.java | 58 - .../common/serialize/protostuff/Wrapper.java | 33 - .../protostuff/delegate/SqlDateDelegate.java | 55 - .../protostuff/delegate/TimeDelegate.java | 57 - .../delegate/TimestampDelegate.java | 57 - .../protostuff/utils/WrapperUtils.java | 115 - ...pache.dubbo.common.serialize.Serialization | 1 - .../dubbo-serialization-test/pom.xml | 87 - .../avro/AvroObjectInputOutputTest.java | 196 - .../serialize/avro/AvroSerializationTest.java | 64 - .../AbstractSerializationPersonFailTest.java | 141 - .../AbstractSerializationPersonOkTest.java | 92 - .../base/AbstractSerializationTest.java | 1212 ---- .../fastjson/FastJsonObjectInputTest.java | 199 - .../fastjson/FastJsonObjectOutputTest.java | 142 - .../fastjson/FastJsonSerializationTest.java | 62 - .../common/serialize/fst/FstFactoryTest.java | 32 - .../serialize/fst/FstObjectInputTest.java | 51 - .../serialize/fst/FstObjectOutputTest.java | 186 - .../serialize/fst/FstSerializationTest.java | 63 - .../hessian2/Hessian2PersonOkTest.java | 212 - .../hessian2/Hessian2SerializationTest.java | 210 - .../jdk/CompactedJavaSerializationTest.java | 27 - .../serialize/jdk/JavaSerializationTest.java | 27 - .../common/serialize/jdk/JdkPersonOkTest.java | 30 - .../jdk/NativeJavaSerializationTest.java | 26 - .../serialize/kryo/KryoPersonOkTest.java | 29 - .../serialize/kryo/KyroSerializationTest.java | 26 - .../serialize/kryo/ReflectionUtilsTest.java | 46 - .../common/serialize/model/AnimalEnum.java | 21 - .../common/serialize/model/BizException.java | 29 - .../BizExceptionNoDefaultConstructor.java | 26 - .../common/serialize/model/Organization.java | 30 - .../dubbo/common/serialize/model/Person.java | 95 - .../serialize/model/SerializablePerson.java | 97 - .../common/serialize/model/media/Image.java | 120 - .../common/serialize/model/media/Media.java | 205 - .../serialize/model/media/MediaContent.java | 78 - .../serialize/model/person/BigPerson.java | 151 - .../serialize/model/person/FullAddress.java | 202 - .../serialize/model/person/PersonInfo.java | 206 - .../serialize/model/person/PersonStatus.java | 22 - .../common/serialize/model/person/Phone.java | 139 - .../AbstractProtobufSerializationTest.java | 372 -- .../GenericProtobufJsonObjectOutputTest.java | 206 - .../GenericProtobufJsonSerializationTest.java | 23 - .../GenericProtobufSerializationTest.java | 23 - .../protobuf/support/model/GooglePB.java | 3431 ----------- .../support/model/ServiceInterface.java | 21 - .../ProtostuffObjectOutputTest.java | 242 - .../ProtostuffSerializationTest.java | 27 - .../SerializableClassRegistryTest.java | 38 - .../src/test/proto/GooglePB.proto | 51 - .../src/test/resources/log4j.xml | 31 - .../SimpleDO.fc | 2 - dubbo-serialization/pom.xml | 9 - pom.xml | 87 +- 450 files changed, 1916 insertions(+), 59341 deletions(-) delete mode 100644 dubbo-configcenter/dubbo-configcenter-consul/pom.xml delete mode 100644 dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java delete mode 100644 dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationFactory.java delete mode 100644 dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory delete mode 100644 dubbo-configcenter/dubbo-configcenter-consul/src/test/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationTest.java delete mode 100644 dubbo-configcenter/dubbo-configcenter-etcd/pom.xml delete mode 100644 dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java delete mode 100644 dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationFactory.java delete mode 100644 dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory delete mode 100644 dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java delete mode 100644 dubbo-container/dubbo-container-log4j/pom.xml delete mode 100644 dubbo-container/dubbo-container-log4j/src/main/java/org/apache/dubbo/container/log4j/Log4jContainer.java delete mode 100644 dubbo-container/dubbo-container-log4j/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container delete mode 100644 dubbo-container/dubbo-container-log4j/src/test/java/org/apache/dubbo/container/log4j/Log4jContainerTest.java delete mode 100644 dubbo-container/dubbo-container-logback/pom.xml delete mode 100644 dubbo-container/dubbo-container-logback/src/main/java/org/apache/dubbo/container/logback/LogbackContainer.java delete mode 100644 dubbo-container/dubbo-container-logback/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container delete mode 100644 dubbo-container/dubbo-container-logback/src/test/java/org/apache/dubbo/container/logback/LogbackContainerTest.java rename {dubbo-all => dubbo-distribution/dubbo-all}/pom.xml (73%) create mode 100644 dubbo-distribution/dubbo-apache-release/pom.xml rename dubbo-distribution/{ => dubbo-apache-release}/src/assembly/bin-release.xml (95%) rename dubbo-distribution/{ => dubbo-apache-release}/src/assembly/source-release.xml (98%) rename {dubbo-bom => dubbo-distribution/dubbo-bom}/pom.xml (89%) create mode 100644 dubbo-distribution/dubbo-core-spi/pom.xml delete mode 100644 dubbo-metadata/dubbo-metadata-report-consul/pom.xml delete mode 100644 dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java delete mode 100644 dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java delete mode 100644 dubbo-metadata/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory delete mode 100644 dubbo-metadata/dubbo-metadata-report-etcd/pom.xml delete mode 100644 dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java delete mode 100644 dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java delete mode 100644 dubbo-metadata/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory delete mode 100644 dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java delete mode 100644 dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java delete mode 100644 dubbo-metadata/dubbo-metadata-report-nacos/pom.xml delete mode 100644 dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java delete mode 100644 dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java delete mode 100644 dubbo-metadata/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory delete mode 100644 dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java delete mode 100644 dubbo-registry/dubbo-registry-consul/pom.xml delete mode 100644 dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/AbstractConsulRegistry.java delete mode 100644 dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java delete mode 100644 dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistryFactory.java delete mode 100644 dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulServiceDiscovery.java delete mode 100644 dubbo-registry/dubbo-registry-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory delete mode 100644 dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulRegistryTest.java delete mode 100644 dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulServiceDiscoveryTest.java delete mode 100644 dubbo-registry/dubbo-registry-default/pom.xml delete mode 100644 dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/AbstractRegistryService.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoService.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoServiceImpl.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockChannel.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockedClient.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryStatusCheckerTest.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryService.java delete mode 100644 dubbo-registry/dubbo-registry-default/src/test/resources/log4j.xml delete mode 100644 dubbo-registry/dubbo-registry-etcd3/pom.xml delete mode 100644 dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java delete mode 100644 dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistryFactory.java delete mode 100644 dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdServiceDiscovery.java delete mode 100644 dubbo-registry/dubbo-registry-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory delete mode 100644 dubbo-registry/dubbo-registry-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery delete mode 100644 dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java delete mode 100644 dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdServiceDiscoveryTest.java delete mode 100644 dubbo-registry/dubbo-registry-eureka/pom.xml delete mode 100644 dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/ConfigurableEurekaInstanceConfig.java delete mode 100644 dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/EurekaServiceDiscovery.java delete mode 100644 dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/package-info.java delete mode 100644 dubbo-registry/dubbo-registry-eureka/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery delete mode 100644 dubbo-registry/dubbo-registry-eureka/src/test/java/org/apache/dubbo/registry/eureka/EurekaServiceDiscoveryTest.java delete mode 100644 dubbo-registry/dubbo-registry-redis/pom.xml delete mode 100644 dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java delete mode 100644 dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistryFactory.java delete mode 100644 dubbo-registry/dubbo-registry-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory delete mode 100644 dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java delete mode 100644 dubbo-registry/dubbo-registry-sofa/pom.xml delete mode 100644 dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java delete mode 100644 dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryConstants.java delete mode 100644 dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryFactory.java delete mode 100644 dubbo-registry/dubbo-registry-sofa/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory delete mode 100644 dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloService.java delete mode 100644 dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloServiceImpl.java delete mode 100644 dubbo-registry/dubbo-registry-sofa/src/test/resources/log4j.properties delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/pom.xml delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/AbstractRetryPolicy.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/ChildListener.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdClient.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/RetryPolicy.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/StateListener.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/ConnectionStateListener.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdTransporter.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/RetryLoops.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/RetryNTimes.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/OptionUtil.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.etcd.EtcdTransporter delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/LeaseTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-grizzly/pom.xml delete mode 100644 dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyChannel.java delete mode 100644 dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyClient.java delete mode 100644 dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java delete mode 100644 dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyHandler.java delete mode 100644 dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyServer.java delete mode 100644 dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporter.java delete mode 100644 dubbo-remoting/dubbo-remoting-grizzly/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter delete mode 100644 dubbo-remoting/dubbo-remoting-grizzly/src/test/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/pom.xml delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java delete mode 100755 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java delete mode 100755 dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/pom.xml delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaChannel.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaHandler.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaTransporter.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientToServerTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientsTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/Hello.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/MinaClientToServerTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/World.java delete mode 100644 dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/WorldHandler.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/pom.xml delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Group.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Networker.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Networkers.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Peer.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeGroup.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeNetworker.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeNetworkers.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangePeer.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/AbstractExchangeGroup.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/FileExchangeGroup.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/FileExchangeNetworker.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeGroup.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworker.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/AbstractGroup.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/FileGroup.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/FileNetworker.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/MulticastGroup.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/MulticastNetworker.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.p2p.Networker delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworkerTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/FileNetworkerTest.java delete mode 100644 dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/MulticastNetworkerTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-hessian/pom.xml delete mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/Constants.java delete mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java delete mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java delete mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnection.java delete mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java delete mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol delete mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocolTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianService.java delete mode 100644 dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianServiceImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-http/pom.xml delete mode 100644 dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java delete mode 100644 dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolErrorCode.java delete mode 100644 dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/JsonRemoteInvocation.java delete mode 100644 dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/JsonRpcProxyFactoryBean.java delete mode 100644 dubbo-rpc/dubbo-rpc-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol delete mode 100644 dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpService.java delete mode 100644 dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpServiceImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-memcached/pom.xml delete mode 100644 dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java delete mode 100644 dubbo-rpc/dubbo-rpc-memcached/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol delete mode 100644 dubbo-rpc/dubbo-rpc-memcached/src/test/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocolTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/pom.xml delete mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java delete mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol delete mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/DemoService.thrift delete mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/UserService.thrift delete mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoService.java delete mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoServiceImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocolTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserService.java delete mode 100644 dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserServiceImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-redis/pom.xml delete mode 100644 dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java delete mode 100644 dubbo-rpc/dubbo-rpc-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol delete mode 100644 dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/IDemoService.java delete mode 100644 dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-redis/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization delete mode 100644 dubbo-rpc/dubbo-rpc-rmi/pom.xml delete mode 100644 dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java delete mode 100644 dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java delete mode 100644 dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java delete mode 100644 dubbo-rpc/dubbo-rpc-rmi/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol delete mode 100644 dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/DemoService.java delete mode 100644 dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/DemoServiceImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RemoteService.java delete mode 100644 dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RemoteServiceImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocolTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/Type.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/pom.xml delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ClassNameGenerator.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/DubboClassNameGenerator.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftClassNameGenerator.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftConstants.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftType.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtils.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/io/InputStreamWrapper.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Codec2 delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.thrift.ClassNameGenerator delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestDubbo.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/$__DemoStub.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/Demo.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/thrift/Demo.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/AbstractTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/DemoImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/DubboDemoImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/FramedTransportFactory.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/MockedChannel.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServerExceptionTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftDemoImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoProvider.java delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-consumer.xml delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-provider.xml delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestDubbo.thrift delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/ClassNameTestThrift.thrift delete mode 100644 dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/Demo.thrift delete mode 100644 dubbo-rpc/dubbo-rpc-webservice/pom.xml delete mode 100644 dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java delete mode 100644 dubbo-rpc/dubbo-rpc-webservice/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol delete mode 100644 dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/DemoService.java delete mode 100644 dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/DemoServiceImpl.java delete mode 100644 dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/User.java delete mode 100644 dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/WebserviceProtocolTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-xml/README.md delete mode 100644 dubbo-rpc/dubbo-rpc-xml/pom.xml delete mode 100644 dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java delete mode 100644 dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java delete mode 100644 dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder delete mode 100644 dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol delete mode 100644 dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocolTest.java delete mode 100644 dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcService.java delete mode 100644 dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcServiceImpl.java delete mode 100644 dubbo-serialization/dubbo-serialization-avro/pom.xml delete mode 100644 dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroObjectInput.java delete mode 100644 dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroObjectOutput.java delete mode 100644 dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java delete mode 100644 dubbo-serialization/dubbo-serialization-avro/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization delete mode 100644 dubbo-serialization/dubbo-serialization-fastjson/pom.xml delete mode 100644 dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectInput.java delete mode 100644 dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectOutput.java delete mode 100644 dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java delete mode 100644 dubbo-serialization/dubbo-serialization-fastjson/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization delete mode 100644 dubbo-serialization/dubbo-serialization-fst/pom.xml delete mode 100644 dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstFactory.java delete mode 100644 dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstObjectInput.java delete mode 100644 dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstObjectOutput.java delete mode 100644 dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java delete mode 100644 dubbo-serialization/dubbo-serialization-fst/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization delete mode 100644 dubbo-serialization/dubbo-serialization-gson/pom.xml delete mode 100644 dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectInput.java delete mode 100644 dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectOutput.java delete mode 100644 dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java delete mode 100644 dubbo-serialization/dubbo-serialization-gson/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization delete mode 100644 dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectOutputTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/GsonJsonSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/Image.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/pom.xml delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/CompatibleKryo.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoObjectInput.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoObjectOutput.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoObjectInput2.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoObjectOutput2.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoSerialization2.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/AbstractKryoFactory.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/KryoUtils.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/PooledKryoFactory.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/PrototypeKryoFactory.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/ReflectionUtils.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/ThreadLocalKryoFactory.java delete mode 100644 dubbo-serialization/dubbo-serialization-kryo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization delete mode 100644 dubbo-serialization/dubbo-serialization-native-hession/pom.xml delete mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectInput.java delete mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectOutput.java delete mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java delete mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2SerializerFactory.java delete mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Java8SerializerFactory.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/DurationHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/InstantHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/Java8TimeSerializer.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateTimeHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalTimeHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/MonthDayHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetDateTimeHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetTimeHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/PeriodHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearMonthHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdSerializer.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneOffsetHandle.java delete mode 100755 dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZonedDateTimeHandle.java delete mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization delete mode 100644 dubbo-serialization/dubbo-serialization-native-hession/src/test/java/org/apache/dubbo/serialize/hessian/Java8TimeSerializerTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/pom.xml delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonObjectInput.java delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonObjectOutput.java delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonSerialization.java delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectInput.java delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutput.java delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufUtils.java delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufWrappedException.java delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/src/main/proto/MapValue.proto delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/src/main/proto/ThrowablePB.proto delete mode 100644 dubbo-serialization/dubbo-serialization-protobuf/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization delete mode 100644 dubbo-serialization/dubbo-serialization-protostuff/pom.xml delete mode 100644 dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectInput.java delete mode 100644 dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutput.java delete mode 100644 dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java delete mode 100644 dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/Wrapper.java delete mode 100644 dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/SqlDateDelegate.java delete mode 100644 dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimeDelegate.java delete mode 100644 dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimestampDelegate.java delete mode 100644 dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/utils/WrapperUtils.java delete mode 100644 dubbo-serialization/dubbo-serialization-protostuff/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization delete mode 100644 dubbo-serialization/dubbo-serialization-test/pom.xml delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/avro/AvroObjectInputOutputTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/avro/AvroSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/base/AbstractSerializationPersonFailTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/base/AbstractSerializationPersonOkTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/base/AbstractSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectInputTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectOutputTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/fst/FstFactoryTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/fst/FstObjectInputTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/fst/FstObjectOutputTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/fst/FstSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2PersonOkTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/hessian2/Hessian2SerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/jdk/CompactedJavaSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/jdk/JavaSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/jdk/JdkPersonOkTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/jdk/NativeJavaSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/kryo/KryoPersonOkTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/kryo/KyroSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/kryo/ReflectionUtilsTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/AnimalEnum.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/BizException.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/BizExceptionNoDefaultConstructor.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/Organization.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/Person.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/SerializablePerson.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/media/Image.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/media/Media.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/media/MediaContent.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/person/BigPerson.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/person/FullAddress.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/person/PersonInfo.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/person/PersonStatus.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/model/person/Phone.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/AbstractProtobufSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonObjectOutputTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/model/GooglePB.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protobuf/support/model/ServiceInterface.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutputTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerializationTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/support/SerializableClassRegistryTest.java delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/proto/GooglePB.proto delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/resources/log4j.xml delete mode 100644 dubbo-serialization/dubbo-serialization-test/src/test/resources/org.apache.dubbo.common.serialize.dubbo/SimpleDO.fc diff --git a/dubbo-compatible/pom.xml b/dubbo-compatible/pom.xml index b96623a137..c72eddeaca 100644 --- a/dubbo-compatible/pom.xml +++ b/dubbo-compatible/pom.xml @@ -68,6 +68,16 @@ dubbo-rpc-thrift ${project.parent.version} + + org.apache.dubbo + dubbo-filter-cache + ${project.parent.version} + + + org.apache.dubbo + dubbo-filter-validation + ${project.parent.version} + org.apache.dubbo dubbo-serialization-hessian2 diff --git a/dubbo-config/dubbo-config-api/pom.xml b/dubbo-config/dubbo-config-api/pom.xml index 4ccfd67a36..f5cfd34c97 100644 --- a/dubbo-config/dubbo-config-api/pom.xml +++ b/dubbo-config/dubbo-config-api/pom.xml @@ -55,16 +55,6 @@ dubbo-rpc-injvm ${project.parent.version} - - org.apache.dubbo - dubbo-filter-validation - ${project.parent.version} - - - org.apache.dubbo - dubbo-filter-cache - ${project.parent.version} - @@ -231,6 +221,19 @@ test + + org.apache.dubbo + dubbo-filter-cache + ${project.parent.version} + test + + + + org.apache.dubbo + dubbo-filter-validation + ${project.parent.version} + test + diff --git a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml index 26d78efd63..8d3dc0e27c 100644 --- a/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-apollo/pom.xml @@ -16,12 +16,13 @@ --> 4.0.0 + org.apache.dubbo dubbo-configcenter - ${revision} - ../pom.xml + 2.7.7-SNAPSHOT + dubbo-configcenter-apollo jar ${project.artifactId} diff --git a/dubbo-configcenter/dubbo-configcenter-consul/pom.xml b/dubbo-configcenter/dubbo-configcenter-consul/pom.xml deleted file mode 100644 index c6b23937e9..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-consul/pom.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - org.apache.dubbo - dubbo-configcenter - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-configcenter-consul - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - com.orbitz.consul - consul-client - - - com.pszymczyk.consul - embedded-consul - - - - - diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java deleted file mode 100644 index c1e5a44910..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfiguration.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * 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.apache.dubbo.configcenter.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.ConfigChangeType; -import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; -import org.apache.dubbo.common.config.configcenter.ConfigurationListener; -import org.apache.dubbo.common.config.configcenter.TreePathDynamicConfiguration; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.CollectionUtils; - -import com.google.common.base.Charsets; -import com.google.common.net.HostAndPort; -import com.orbitz.consul.Consul; -import com.orbitz.consul.KeyValueClient; -import com.orbitz.consul.cache.KVCache; -import com.orbitz.consul.model.kv.Value; -import org.apache.dubbo.common.utils.StringUtils; - -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; - -/** - * config center implementation for consul - */ -public class ConsulDynamicConfiguration extends TreePathDynamicConfiguration { - private static final Logger logger = LoggerFactory.getLogger(ConsulDynamicConfiguration.class); - - private static final int DEFAULT_PORT = 8500; - private static final int DEFAULT_WATCH_TIMEOUT = 60 * 1000; - private static final String WATCH_TIMEOUT = "consul-watch-timeout"; - - private final Consul client; - - private final KeyValueClient kvClient; - - private final int watchTimeout; - - private final ConcurrentMap watchers = new ConcurrentHashMap<>(); - - public ConsulDynamicConfiguration(URL url) { - super(url); - watchTimeout = url.getParameter(WATCH_TIMEOUT, DEFAULT_WATCH_TIMEOUT); - String host = url.getHost(); - int port = url.getPort() != 0 ? url.getPort() : DEFAULT_PORT; - Consul.Builder builder = Consul.builder() - .withHostAndPort(HostAndPort.fromParts(host, port)); - String token = url.getParameter("token", (String) null); - if (StringUtils.isNotEmpty(token)) { - builder.withAclToken(token); - } - client = builder.build(); - this.kvClient = client.keyValueClient(); - } - - @Override - public String getInternalProperty(String key) { - logger.info("getting config from: " + key); - return kvClient.getValueAsString(key, Charsets.UTF_8).orElse(null); - } - - @Override - protected boolean doPublishConfig(String pathKey, String content) throws Exception { - return kvClient.putValue(pathKey, content); - } - - @Override - protected String doGetConfig(String pathKey) throws Exception { - return getInternalProperty(pathKey); - } - - @Override - protected boolean doRemoveConfig(String pathKey) throws Exception { - kvClient.deleteKey(pathKey); - return true; - } - - @Override - protected Collection doGetConfigKeys(String groupPath) { - List keys = kvClient.getKeys(groupPath); - List configKeys = new LinkedList<>(); - if (CollectionUtils.isNotEmpty(keys)) { - keys.stream() - .filter(k -> !k.equals(groupPath)) - .map(k -> k.substring(k.lastIndexOf(PATH_SEPARATOR) + 1)) - .forEach(configKeys::add); - } - return configKeys; - } - - @Override - protected void doAddListener(String pathKey, ConfigurationListener listener) { - logger.info("register listener " + listener.getClass() + " for config with key: " + pathKey); - ConsulListener watcher = watchers.computeIfAbsent(pathKey, k -> new ConsulListener(pathKey)); - watcher.addListener(listener); - } - - @Override - protected void doRemoveListener(String pathKey, ConfigurationListener listener) { - logger.info("unregister listener " + listener.getClass() + " for config with key: " + pathKey); - ConsulListener watcher = watchers.get(pathKey); - if (watcher != null) { - watcher.removeListener(listener); - } - } - - @Override - protected void doClose() throws Exception { - client.destroy(); - } - - private class ConsulListener implements KVCache.Listener { - - private KVCache kvCache; - private final Set listeners = new LinkedHashSet<>(); - private final String normalizedKey; - - public ConsulListener(String normalizedKey) { - this.normalizedKey = normalizedKey; - initKVCache(); - } - - private void initKVCache() { - this.kvCache = KVCache.newCache(kvClient, normalizedKey, watchTimeout); - kvCache.addListener(this); - kvCache.start(); - } - - @Override - public void notify(Map newValues) { - // Cache notifies all paths with "foo" the root path - // If you want to watch only "foo" value, you must filter other paths - Optional newValue = newValues.values().stream() - .filter(value -> value.getKey().equals(normalizedKey)) - .findAny(); - - newValue.ifPresent(value -> { - // Values are encoded in key/value store, decode it if needed - Optional decodedValue = newValue.get().getValueAsString(); - decodedValue.ifPresent(v -> listeners.forEach(l -> { - ConfigChangedEvent event = new ConfigChangedEvent(normalizedKey, getGroup(), v, ConfigChangeType.MODIFIED); - l.process(event); - })); - }); - } - - private void addListener(ConfigurationListener listener) { - this.listeners.add(listener); - } - - private void removeListener(ConfigurationListener listener) { - this.listeners.remove(listener); - } - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationFactory.java deleted file mode 100644 index 980a156234..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/main/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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.apache.dubbo.configcenter.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; -import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; - -/** - * Config center factory for consul - */ -public class ConsulDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { - @Override - protected DynamicConfiguration createDynamicConfiguration(URL url) { - return new ConsulDynamicConfiguration(url); - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory deleted file mode 100644 index b7a5091efa..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory +++ /dev/null @@ -1 +0,0 @@ -consul=org.apache.dubbo.configcenter.consul.ConsulDynamicConfigurationFactory diff --git a/dubbo-configcenter/dubbo-configcenter-consul/src/test/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-consul/src/test/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationTest.java deleted file mode 100644 index c54d103414..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-consul/src/test/java/org/apache/dubbo/configcenter/consul/ConsulDynamicConfigurationTest.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * 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.apache.dubbo.configcenter.consul; - -import org.apache.dubbo.common.URL; - -import com.google.common.net.HostAndPort; -import com.orbitz.consul.Consul; -import com.orbitz.consul.KeyValueClient; -import com.orbitz.consul.cache.KVCache; -import com.orbitz.consul.model.kv.Value; -import com.pszymczyk.consul.ConsulProcess; -import com.pszymczyk.consul.ConsulStarterBuilder; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.Optional; -import java.util.TreeSet; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * - */ -public class ConsulDynamicConfigurationTest { - - private static ConsulProcess consul; - private static URL configCenterUrl; - private static ConsulDynamicConfiguration configuration; - - private static Consul client; - private static KeyValueClient kvClient; - - @BeforeAll - public static void setUp() throws Exception { - consul = ConsulStarterBuilder.consulStarter() - .build() - .start(); - configCenterUrl = URL.valueOf("consul://127.0.0.1:" + consul.getHttpPort()); - - configuration = new ConsulDynamicConfiguration(configCenterUrl); - client = Consul.builder().withHostAndPort(HostAndPort.fromParts("127.0.0.1", consul.getHttpPort())).build(); - kvClient = client.keyValueClient(); - } - - @AfterAll - public static void tearDown() throws Exception { - consul.close(); - configuration.close(); - } - - @Test - public void testGetConfig() { - kvClient.putValue("/dubbo/config/dubbo/foo", "bar"); - // test equals - assertEquals("bar", configuration.getConfig("foo", "dubbo")); - // test does not block - assertEquals("bar", configuration.getConfig("foo", "dubbo")); - Assertions.assertNull(configuration.getConfig("not-exist", "dubbo")); - } - - @Test - public void testPublishConfig() { - configuration.publishConfig("value", "metadata", "1"); - // test equals - assertEquals("1", configuration.getConfig("value", "/metadata")); - assertEquals("1", kvClient.getValueAsString("/dubbo/config/metadata/value").get()); - } - - @Test - public void testAddListener() { - KVCache cache = KVCache.newCache(kvClient, "/dubbo/config/dubbo/foo"); - cache.addListener(newValues -> { - // Cache notifies all paths with "foo" the root path - // If you want to watch only "foo" value, you must filter other paths - Optional newValue = newValues.values().stream() - .filter(value -> value.getKey().equals("foo")) - .findAny(); - - newValue.ifPresent(value -> { - // Values are encoded in key/value store, decode it if needed - Optional decodedValue = newValue.get().getValueAsString(); - decodedValue.ifPresent(v -> System.out.println(String.format("Value is: %s", v))); //prints "bar" - }); - }); - cache.start(); - - kvClient.putValue("/dubbo/config/dubbo/foo", "new-value"); - kvClient.putValue("/dubbo/config/dubbo/foo/sub", "sub-value"); - kvClient.putValue("/dubbo/config/dubbo/foo/sub2", "sub-value2"); - kvClient.putValue("/dubbo/config/foo", "parent-value"); - - System.out.println(kvClient.getKeys("/dubbo/config/dubbo/foo")); - System.out.println(kvClient.getKeys("/dubbo/config")); - System.out.println(kvClient.getValues("/dubbo/config/dubbo/foo")); - } - - @Test - public void testGetConfigKeys() { - configuration.publishConfig("v1", "metadata", "1"); - configuration.publishConfig("v2", "metadata", "2"); - configuration.publishConfig("v3", "metadata", "3"); - // test equals - assertEquals(new TreeSet(Arrays.asList("v1", "v2", "v3")), configuration.getConfigKeys("metadata")); - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml b/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml deleted file mode 100644 index 3e8d8f355f..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-etcd/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - org.apache.dubbo - dubbo-configcenter - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-configcenter-etcd - jar - ${project.artifactId} - The etcd implementation of the config-center api - - - true - - - - - io.etcd - jetcd-launcher - test - - - org.testcontainers - testcontainers - test - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-etcd3 - ${project.parent.version} - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipIntegrationTests} - - - - - diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java deleted file mode 100644 index f686e86033..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfiguration.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * 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.apache.dubbo.configcenter.support.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.ConfigChangeType; -import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; -import org.apache.dubbo.common.config.configcenter.ConfigurationListener; -import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.remoting.etcd.StateListener; -import org.apache.dubbo.remoting.etcd.jetcd.JEtcdClient; - -import com.google.protobuf.ByteString; -import io.etcd.jetcd.api.Event; -import io.etcd.jetcd.api.WatchCancelRequest; -import io.etcd.jetcd.api.WatchCreateRequest; -import io.etcd.jetcd.api.WatchGrpc; -import io.etcd.jetcd.api.WatchRequest; -import io.etcd.jetcd.api.WatchResponse; -import io.grpc.ManagedChannel; -import io.grpc.stub.StreamObserver; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.dubbo.common.config.configcenter.Constants.CONFIG_NAMESPACE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; - -/** - * The etcd implementation of {@link DynamicConfiguration} - */ -public class EtcdDynamicConfiguration implements DynamicConfiguration { - - /** - * The final root path would be: /$NAME_SPACE/config - */ - private String rootPath; - - /** - * The etcd client - */ - private final JEtcdClient etcdClient; - - /** - * The map store the key to {@link EtcdConfigWatcher} mapping - */ - private final ConcurrentMap watchListenerMap; - - EtcdDynamicConfiguration(URL url) { - rootPath = PATH_SEPARATOR + url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP) + "/config"; - etcdClient = new JEtcdClient(url); - etcdClient.addStateListener(state -> { - if (state == StateListener.CONNECTED) { - try { - recover(); - } catch (Exception e) { - // ignore - } - } - }); - watchListenerMap = new ConcurrentHashMap<>(); - } - - @Override - public void addListener(String key, String group, ConfigurationListener listener) { - if (watchListenerMap.get(listener) == null) { - EtcdConfigWatcher watcher = new EtcdConfigWatcher(key, group, listener); - watchListenerMap.put(listener, watcher); - watcher.watch(); - } - } - - @Override - public void removeListener(String key, String group, ConfigurationListener listener) { - EtcdConfigWatcher watcher = watchListenerMap.get(listener); - watcher.cancelWatch(); - } - - @Override - public String getConfig(String key, String group, long timeout) throws IllegalStateException { - return (String) getInternalProperty(convertKey(group, key)); - } - -// @Override -// public String getConfigs(String key, String group, long timeout) throws IllegalStateException { -// if (StringUtils.isEmpty(group)) { -// group = DEFAULT_GROUP; -// } -// return (String) getInternalProperty(convertKey(group, key)); -// } - - @Override - public Object getInternalProperty(String key) { - return etcdClient.getKVValue(key); - } - - private String buildPath(String group) { - String actualGroup = StringUtils.isEmpty(group) ? DEFAULT_GROUP : group; - return rootPath + PATH_SEPARATOR + actualGroup; - } - - private String convertKey(String group, String key) { - return buildPath(group) + PATH_SEPARATOR + key; - } - - private void recover() { - for (EtcdConfigWatcher watcher : watchListenerMap.values()) { - watcher.watch(); - } - } - - public class EtcdConfigWatcher implements StreamObserver { - - private ConfigurationListener listener; - protected WatchGrpc.WatchStub watchStub; - private StreamObserver observer; - protected long watchId; - private ManagedChannel channel; - - private final String key; - - private final String group; - - private String normalizedKey; - - public EtcdConfigWatcher(String key, String group, ConfigurationListener listener) { - this.key = key; - this.group = group; - this.normalizedKey = convertKey(group, key); - this.listener = listener; - this.channel = etcdClient.getChannel(); - } - - @Override - public void onNext(WatchResponse watchResponse) { - this.watchId = watchResponse.getWatchId(); - for (Event etcdEvent : watchResponse.getEventsList()) { - ConfigChangeType type = ConfigChangeType.MODIFIED; - if (etcdEvent.getType() == Event.EventType.DELETE) { - type = ConfigChangeType.DELETED; - } - ConfigChangedEvent event = new ConfigChangedEvent(key, group, - etcdEvent.getKv().getValue().toString(UTF_8), type); - listener.process(event); - } - } - - @Override - public void onError(Throwable throwable) { - // ignore - } - - @Override - public void onCompleted() { - // ignore - } - - public long getWatchId() { - return watchId; - } - - private void watch() { - watchStub = WatchGrpc.newStub(channel); - observer = watchStub.watch(this); - WatchCreateRequest.Builder builder = WatchCreateRequest.newBuilder() - .setKey(ByteString.copyFromUtf8(normalizedKey)) - .setProgressNotify(true); - WatchRequest req = WatchRequest.newBuilder().setCreateRequest(builder).build(); - observer.onNext(req); - } - - private void cancelWatch() { - WatchCancelRequest watchCancelRequest = - WatchCancelRequest.newBuilder().setWatchId(watchId).build(); - WatchRequest cancelRequest = WatchRequest.newBuilder() - .setCancelRequest(watchCancelRequest).build(); - observer.onNext(cancelRequest); - } - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationFactory.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationFactory.java deleted file mode 100644 index 269cee6046..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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.apache.dubbo.configcenter.support.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory; -import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; - -/** - * The etcd implementation of {@link AbstractDynamicConfigurationFactory} - */ -public class EtcdDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory { - - @Override - protected DynamicConfiguration createDynamicConfiguration(URL url) { - return new EtcdDynamicConfiguration(url); - } -} diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory b/dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory deleted file mode 100644 index d84b1ae0e1..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory +++ /dev/null @@ -1 +0,0 @@ -etcd=org.apache.dubbo.configcenter.support.etcd.EtcdDynamicConfigurationFactory \ No newline at end of file diff --git a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java b/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java deleted file mode 100644 index 86dd306bf8..0000000000 --- a/dubbo-configcenter/dubbo-configcenter-etcd/src/test/java/org/apache/dubbo/configcenter/support/etcd/EtcdDynamicConfigurationTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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.apache.dubbo.configcenter.support.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent; -import org.apache.dubbo.common.config.configcenter.ConfigurationListener; -import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; - -import io.etcd.jetcd.ByteSequence; -import io.etcd.jetcd.Client; -import io.etcd.jetcd.launcher.EtcdCluster; -import io.etcd.jetcd.launcher.EtcdClusterFactory; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import java.net.URI; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.dubbo.remoting.etcd.Constants.SESSION_TIMEOUT_KEY; - -/** - * Unit test for etcd config center support - * Integrate with https://github.com/etcd-io/jetcd#launcher - */ -public class EtcdDynamicConfigurationTest { - - private static EtcdDynamicConfiguration config; - - public EtcdCluster etcdCluster = EtcdClusterFactory.buildCluster(getClass().getSimpleName(), 3, false, false); - - private static Client client; - - @Test - public void testGetConfig() { - - put("/dubbo/config/org.apache.dubbo.etcd.testService/configurators", "hello"); - put("/dubbo/config/test/dubbo.properties", "aaa=bbb"); - Assert.assertEquals("hello", config.getConfig("org.apache.dubbo.etcd.testService.configurators", DynamicConfiguration.DEFAULT_GROUP)); - Assert.assertEquals("aaa=bbb", config.getConfig("dubbo.properties", "test")); - } - - @Test - public void testAddListener() throws Exception { - CountDownLatch latch = new CountDownLatch(4); - TestListener listener1 = new TestListener(latch); - TestListener listener2 = new TestListener(latch); - TestListener listener3 = new TestListener(latch); - TestListener listener4 = new TestListener(latch); - config.addListener("AService.configurators", listener1); - config.addListener("AService.configurators", listener2); - config.addListener("testapp.tagrouters", listener3); - config.addListener("testapp.tagrouters", listener4); - - put("/dubbo/config/AService/configurators", "new value1"); - Thread.sleep(200); - put("/dubbo/config/testapp/tagrouters", "new value2"); - Thread.sleep(200); - put("/dubbo/config/testapp", "new value3"); - - Thread.sleep(1000); - - Assert.assertTrue(latch.await(5, TimeUnit.SECONDS)); - Assert.assertEquals(1, listener1.getCount("/dubbo/config/AService/configurators")); - Assert.assertEquals(1, listener2.getCount("/dubbo/config/AService/configurators")); - Assert.assertEquals(1, listener3.getCount("/dubbo/config/testapp/tagrouters")); - Assert.assertEquals(1, listener4.getCount("/dubbo/config/testapp/tagrouters")); - - Assert.assertEquals("new value1", listener1.getValue()); - Assert.assertEquals("new value1", listener2.getValue()); - Assert.assertEquals("new value2", listener3.getValue()); - Assert.assertEquals("new value2", listener4.getValue()); - } - - private class TestListener implements ConfigurationListener { - private CountDownLatch latch; - private String value; - private Map countMap = new HashMap<>(); - - public TestListener(CountDownLatch latch) { - this.latch = latch; - } - - @Override - public void process(ConfigChangedEvent event) { - Integer count = countMap.computeIfAbsent(event.getKey(), k -> 0); - countMap.put(event.getKey(), ++count); - value = event.getContent(); - latch.countDown(); - } - - public int getCount(String key) { - return countMap.get(key); - } - - public String getValue() { - return value; - } - } - - private void put(String key, String value) { - try { - client.getKVClient().put(ByteSequence.from(key, UTF_8), ByteSequence.from(value, UTF_8)).get(); - } catch (Exception e) { - System.out.println("Error put value to etcd."); - } - } - - @Before - public void setUp() { - - etcdCluster.start(); - - client = Client.builder().endpoints(etcdCluster.getClientEndpoints()).build(); - - List clientEndPoints = etcdCluster.getClientEndpoints(); - - String ipAddress = clientEndPoints.get(0).getHost() + ":" + clientEndPoints.get(0).getPort(); - String urlForDubbo = "etcd3://" + ipAddress + "/org.apache.dubbo.etcd.testService"; - - // timeout in 15 seconds. - URL url = URL.valueOf(urlForDubbo) - .addParameter(SESSION_TIMEOUT_KEY, 15000); - config = new EtcdDynamicConfiguration(url); - } - - @After - public void tearDown() { - etcdCluster.close(); - } - -} diff --git a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml index b54dfc6bce..42dcc69848 100644 --- a/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml +++ b/dubbo-configcenter/dubbo-configcenter-nacos/pom.xml @@ -22,8 +22,7 @@ org.apache.dubbo dubbo-configcenter - ${revision} - ../pom.xml + 2.7.7-SNAPSHOT 4.0.0 diff --git a/dubbo-configcenter/pom.xml b/dubbo-configcenter/pom.xml index 869611cb62..f69f389546 100644 --- a/dubbo-configcenter/pom.xml +++ b/dubbo-configcenter/pom.xml @@ -33,8 +33,6 @@ dubbo-configcenter-zookeeper dubbo-configcenter-apollo - dubbo-configcenter-consul - dubbo-configcenter-etcd dubbo-configcenter-nacos diff --git a/dubbo-container/dubbo-container-log4j/pom.xml b/dubbo-container/dubbo-container-log4j/pom.xml deleted file mode 100644 index 949615f73e..0000000000 --- a/dubbo-container/dubbo-container-log4j/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-container - ${revision} - ../pom.xml - - dubbo-container-log4j - jar - ${project.artifactId} - The log4j container module of dubbo project - - false - - - - org.apache.dubbo - dubbo-container-api - ${project.parent.version} - - - \ No newline at end of file diff --git a/dubbo-container/dubbo-container-log4j/src/main/java/org/apache/dubbo/container/log4j/Log4jContainer.java b/dubbo-container/dubbo-container-log4j/src/main/java/org/apache/dubbo/container/log4j/Log4jContainer.java deleted file mode 100644 index 946e4c59eb..0000000000 --- a/dubbo-container/dubbo-container-log4j/src/main/java/org/apache/dubbo/container/log4j/Log4jContainer.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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.apache.dubbo.container.log4j; - -import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.container.Container; - -import org.apache.log4j.Appender; -import org.apache.log4j.FileAppender; -import org.apache.log4j.LogManager; -import org.apache.log4j.PropertyConfigurator; - -import java.util.Enumeration; -import java.util.Properties; - -/** - * Log4jContainer. (SPI, Singleton, ThreadSafe) - * - * The container class implementation for Log4j - */ -public class Log4jContainer implements Container { - - public static final String LOG4J_FILE = "dubbo.log4j.file"; - - public static final String LOG4J_LEVEL = "dubbo.log4j.level"; - - public static final String LOG4J_SUBDIRECTORY = "dubbo.log4j.subdirectory"; - - public static final String DEFAULT_LOG4J_LEVEL = "ERROR"; - - @Override - @SuppressWarnings("unchecked") - public void start() { - String file = ConfigurationUtils.getProperty(LOG4J_FILE); - if (file != null && file.length() > 0) { - String level = ConfigurationUtils.getProperty(LOG4J_LEVEL); - if (StringUtils.isEmpty(level)) { - level = DEFAULT_LOG4J_LEVEL; - } - Properties properties = new Properties(); - properties.setProperty("log4j.rootLogger", level + ",application"); - properties.setProperty("log4j.appender.application", "org.apache.log4j.DailyRollingFileAppender"); - properties.setProperty("log4j.appender.application.File", file); - properties.setProperty("log4j.appender.application.Append", "true"); - properties.setProperty("log4j.appender.application.DatePattern", "'.'yyyy-MM-dd"); - properties.setProperty("log4j.appender.application.layout", "org.apache.log4j.PatternLayout"); - properties.setProperty("log4j.appender.application.layout.ConversionPattern", "%d [%t] %-5p %C{6} (%F:%L) - %m%n"); - PropertyConfigurator.configure(properties); - } - String subdirectory = ConfigurationUtils.getProperty(LOG4J_SUBDIRECTORY); - if (subdirectory != null && subdirectory.length() > 0) { - Enumeration ls = LogManager.getCurrentLoggers(); - while (ls.hasMoreElements()) { - org.apache.log4j.Logger l = ls.nextElement(); - if (l != null) { - Enumeration as = l.getAllAppenders(); - while (as.hasMoreElements()) { - Appender a = as.nextElement(); - if (a instanceof FileAppender) { - FileAppender fa = (FileAppender) a; - String f = fa.getFile(); - if (f != null && f.length() > 0) { - int i = f.replace('\\', '/').lastIndexOf('/'); - String path; - if (i == -1) { - path = subdirectory; - } else { - path = f.substring(0, i); - if (!path.endsWith(subdirectory)) { - path = path + "/" + subdirectory; - } - f = f.substring(i + 1); - } - fa.setFile(path + "/" + f); - fa.activateOptions(); - } - } - } - } - } - } - } - - @Override - public void stop() { - } - -} diff --git a/dubbo-container/dubbo-container-log4j/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container b/dubbo-container/dubbo-container-log4j/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container deleted file mode 100644 index 0b4c162a6a..0000000000 --- a/dubbo-container/dubbo-container-log4j/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container +++ /dev/null @@ -1 +0,0 @@ -log4j=org.apache.dubbo.container.log4j.Log4jContainer \ No newline at end of file diff --git a/dubbo-container/dubbo-container-log4j/src/test/java/org/apache/dubbo/container/log4j/Log4jContainerTest.java b/dubbo-container/dubbo-container-log4j/src/test/java/org/apache/dubbo/container/log4j/Log4jContainerTest.java deleted file mode 100644 index 535a3d5c5a..0000000000 --- a/dubbo-container/dubbo-container-log4j/src/test/java/org/apache/dubbo/container/log4j/Log4jContainerTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.apache.dubbo.container.log4j; - -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.container.Container; - -import org.junit.jupiter.api.Test; - -/** - * StandaloneContainerTest - */ -public class Log4jContainerTest { - - @Test - public void testContainer() { - Log4jContainer container = (Log4jContainer) ExtensionLoader.getExtensionLoader(Container.class).getExtension("log4j"); - container.start(); - container.stop(); - } - -} \ No newline at end of file diff --git a/dubbo-container/dubbo-container-logback/pom.xml b/dubbo-container/dubbo-container-logback/pom.xml deleted file mode 100644 index 0af3164a8b..0000000000 --- a/dubbo-container/dubbo-container-logback/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-container - ${revision} - ../pom.xml - - dubbo-container-logback - jar - ${project.artifactId} - The logback container module of dubbo project - - false - - - - org.apache.dubbo - dubbo-container-api - ${project.parent.version} - - - ch.qos.logback - logback-classic - - - diff --git a/dubbo-container/dubbo-container-logback/src/main/java/org/apache/dubbo/container/logback/LogbackContainer.java b/dubbo-container/dubbo-container-logback/src/main/java/org/apache/dubbo/container/logback/LogbackContainer.java deleted file mode 100644 index 430e2e2191..0000000000 --- a/dubbo-container/dubbo-container-logback/src/main/java/org/apache/dubbo/container/logback/LogbackContainer.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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.apache.dubbo.container.logback; - -import org.apache.dubbo.common.utils.ConfigUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.container.Container; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.encoder.PatternLayoutEncoder; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.rolling.RollingFileAppender; -import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; -import org.slf4j.LoggerFactory; - -/** - * LogbackContainer. (SPI, Singleton, ThreadSafe) - * - * The container class implementation for Logback - */ -public class LogbackContainer implements Container { - - public static final String LOGBACK_FILE = "dubbo.logback.file"; - - public static final String LOGBACK_LEVEL = "dubbo.logback.level"; - - public static final String LOGBACK_MAX_HISTORY = "dubbo.logback.maxhistory"; - - public static final String DEFAULT_LOGBACK_LEVEL = "ERROR"; - - @Override - public void start() { - String file = ConfigUtils.getProperty(LOGBACK_FILE); - if (file != null && file.length() > 0) { - String level = ConfigUtils.getProperty(LOGBACK_LEVEL); - if (StringUtils.isEmpty(level)) { - level = DEFAULT_LOGBACK_LEVEL; - } - // maxHistory=0 Infinite history - int maxHistory = StringUtils.parseInteger(ConfigUtils.getProperty(LOGBACK_MAX_HISTORY)); - - doInitializer(file, level, maxHistory); - } - } - - @Override - public void stop() { - } - - /** - * Initializer logback - * - * @param file - * @param level - * @param maxHistory - */ - private void doInitializer(String file, String level, int maxHistory) { - LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); - Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME); - rootLogger.detachAndStopAllAppenders(); - - // appender - RollingFileAppender fileAppender = new RollingFileAppender(); - fileAppender.setContext(loggerContext); - fileAppender.setName("application"); - fileAppender.setFile(file); - fileAppender.setAppend(true); - - // policy - TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy(); - policy.setContext(loggerContext); - policy.setMaxHistory(maxHistory); - policy.setFileNamePattern(file + ".%d{yyyy-MM-dd}"); - policy.setParent(fileAppender); - policy.start(); - fileAppender.setRollingPolicy(policy); - - // encoder - PatternLayoutEncoder encoder = new PatternLayoutEncoder(); - encoder.setContext(loggerContext); - encoder.setPattern("%date [%thread] %-5level %logger (%file:%line\\) - %msg%n"); - encoder.start(); - fileAppender.setEncoder(encoder); - - fileAppender.start(); - - rootLogger.addAppender(fileAppender); - rootLogger.setLevel(Level.toLevel(level)); - rootLogger.setAdditive(false); - } - -} diff --git a/dubbo-container/dubbo-container-logback/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container b/dubbo-container/dubbo-container-logback/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container deleted file mode 100644 index 04c4eaa39a..0000000000 --- a/dubbo-container/dubbo-container-logback/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.container.Container +++ /dev/null @@ -1 +0,0 @@ -logback=org.apache.dubbo.container.logback.LogbackContainer \ No newline at end of file diff --git a/dubbo-container/dubbo-container-logback/src/test/java/org/apache/dubbo/container/logback/LogbackContainerTest.java b/dubbo-container/dubbo-container-logback/src/test/java/org/apache/dubbo/container/logback/LogbackContainerTest.java deleted file mode 100644 index d82e8a48a9..0000000000 --- a/dubbo-container/dubbo-container-logback/src/test/java/org/apache/dubbo/container/logback/LogbackContainerTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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.apache.dubbo.container.logback; - -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.container.Container; - -import org.junit.jupiter.api.Test; - -/** - * StandaloneContainerTest - */ -public class LogbackContainerTest { - - private static final Logger logger = LoggerFactory.getLogger(LogbackContainerTest.class); - - @Test - public void testContainer() { - LogbackContainer container = (LogbackContainer) ExtensionLoader.getExtensionLoader(Container.class) - .getExtension("logback"); - container.start(); - - logger.debug("Test debug:" + this.getClass().getName()); - logger.warn("Test warn:" + this.getClass().getName()); - logger.info("Test info:" + this.getClass().getName()); - logger.error("Test error:" + this.getClass().getName()); - - container.stop(); - } - -} \ No newline at end of file diff --git a/dubbo-container/pom.xml b/dubbo-container/pom.xml index d088993ff4..ec2cab09c4 100644 --- a/dubbo-container/pom.xml +++ b/dubbo-container/pom.xml @@ -32,7 +32,5 @@ dubbo-container-api dubbo-container-spring - dubbo-container-log4j - dubbo-container-logback diff --git a/dubbo-all/pom.xml b/dubbo-distribution/dubbo-all/pom.xml similarity index 73% rename from dubbo-all/pom.xml rename to dubbo-distribution/dubbo-all/pom.xml index 050ae24747..5f679306bb 100644 --- a/dubbo-all/pom.xml +++ b/dubbo-distribution/dubbo-all/pom.xml @@ -21,11 +21,11 @@ org.apache.dubbo dubbo-parent ${revision} - ../pom.xml + ../../pom.xml dubbo jar - dubbo-all + dubbo The all in one project of dubbo false @@ -59,20 +59,6 @@ compile true - - org.apache.dubbo - dubbo-filter-cache - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-filter-validation - ${project.version} - compile - true - org.apache.dubbo dubbo-remoting-api @@ -96,35 +82,7 @@ org.apache.dubbo - dubbo-remoting-etcd3 - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-mina - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-grizzly - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-p2p - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-remoting-http + dubbo-remoting-zookeeper ${project.version} compile true @@ -150,62 +108,6 @@ compile true - - org.apache.dubbo - dubbo-rpc-http - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-rmi - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-hessian - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-webservice - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-thrift - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-native-thrift - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-memcached - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-rpc-redis - ${project.version} - compile - true - org.apache.dubbo dubbo-rpc-rest @@ -213,13 +115,6 @@ compile true - - org.apache.dubbo - dubbo-rpc-xml - ${project.version} - compile - true - org.apache.dubbo dubbo-rpc-grpc @@ -234,13 +129,6 @@ compile true - - org.apache.dubbo - dubbo-registry-default - ${project.version} - compile - true - org.apache.dubbo dubbo-registry-multicast @@ -255,44 +143,6 @@ compile true - - org.apache.dubbo - dubbo-registry-redis - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-registry-consul - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-registry-etcd3 - ${project.version} - compile - true - - - io.grpc - grpc-core - - - io.grpc - grpc-netty - - - - - org.apache.dubbo - dubbo-registry-eureka - ${project.version} - compile - true - org.apache.dubbo dubbo-registry-nacos @@ -300,13 +150,6 @@ compile true - - org.apache.dubbo - dubbo-registry-sofa - ${project.version} - compile - true - org.apache.dubbo dubbo-registry-multiple @@ -335,20 +178,6 @@ compile true - - org.apache.dubbo - dubbo-container-log4j - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-container-logback - ${project.version} - compile - true - org.apache.dubbo dubbo-qos @@ -363,20 +192,6 @@ compile true - - org.apache.dubbo - dubbo-serialization-fastjson - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-fst - ${project.version} - compile - true - org.apache.dubbo dubbo-serialization-hessian2 @@ -384,13 +199,6 @@ compile true - - org.apache.dubbo - dubbo-serialization-native-hession - ${project.version} - compile - true - org.apache.dubbo dubbo-serialization-jdk @@ -398,41 +206,6 @@ compile true - - org.apache.dubbo - dubbo-serialization-kryo - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-avro - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-protostuff - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-gson - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-serialization-protobuf - ${project.version} - compile - true - org.apache.dubbo dubbo-configcenter-zookeeper @@ -454,30 +227,6 @@ compile true - - org.apache.dubbo - dubbo-configcenter-consul - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-configcenter-etcd - ${project.version} - compile - true - - - io.grpc - grpc-core - - - io.grpc - grpc-netty - - - org.apache.dubbo dubbo-compatible @@ -515,31 +264,7 @@ org.apache.dubbo - dubbo-metadata-report-consul - ${project.version} - compile - true - - - org.apache.dubbo - dubbo-metadata-report-etcd - ${project.version} - compile - true - - - io.grpc - grpc-core - - - io.grpc - grpc-netty - - - - - org.apache.dubbo - dubbo-metadata-report-nacos + dubbo-auth ${project.version} compile true @@ -620,71 +345,35 @@ org.apache.dubbo:dubbo-remoting-api org.apache.dubbo:dubbo-remoting-netty org.apache.dubbo:dubbo-remoting-netty4 - org.apache.dubbo:dubbo-remoting-etcd3 - org.apache.dubbo:dubbo-remoting-mina - org.apache.dubbo:dubbo-remoting-grizzly - org.apache.dubbo:dubbo-remoting-p2p - org.apache.dubbo:dubbo-remoting-http org.apache.dubbo:dubbo-remoting-zookeeper org.apache.dubbo:dubbo-rpc-api org.apache.dubbo:dubbo-rpc-dubbo org.apache.dubbo:dubbo-rpc-injvm - org.apache.dubbo:dubbo-rpc-http - org.apache.dubbo:dubbo-rpc-rmi - org.apache.dubbo:dubbo-rpc-hessian - org.apache.dubbo:dubbo-rpc-webservice - org.apache.dubbo:dubbo-rpc-thrift - org.apache.dubbo:dubbo-rpc-native-thrift - org.apache.dubbo:dubbo-rpc-memcached - org.apache.dubbo:dubbo-rpc-redis org.apache.dubbo:dubbo-rpc-rest - org.apache.dubbo:dubbo-rpc-xml org.apache.dubbo:dubbo-rpc-grpc - org.apache.dubbo:dubbo-filter-validation - org.apache.dubbo:dubbo-filter-cache org.apache.dubbo:dubbo-cluster org.apache.dubbo:dubbo-registry-api org.apache.dubbo:dubbo-registry-default org.apache.dubbo:dubbo-registry-multicast org.apache.dubbo:dubbo-registry-zookeeper - org.apache.dubbo:dubbo-registry-redis - org.apache.dubbo:dubbo-registry-consul - org.apache.dubbo:dubbo-registry-etcd3 - org.apache.dubbo:dubbo-registry-eureka org.apache.dubbo:dubbo-registry-nacos - org.apache.dubbo:dubbo-registry-sofa org.apache.dubbo:dubbo-registry-multiple org.apache.dubbo:dubbo-monitor-api org.apache.dubbo:dubbo-monitor-default org.apache.dubbo:dubbo-container-api org.apache.dubbo:dubbo-container-spring - org.apache.dubbo:dubbo-container-log4j - org.apache.dubbo:dubbo-container-logback - org.apache.dubbo:dubbo-qos org.apache.dubbo:dubbo-serialization-api - org.apache.dubbo:dubbo-serialization-fastjson org.apache.dubbo:dubbo-serialization-hessian2 - org.apache.dubbo:dubbo-serialization-fst - org.apache.dubbo:dubbo-serialization-kryo - org.apache.dubbo:dubbo-serialization-avro org.apache.dubbo:dubbo-serialization-jdk - org.apache.dubbo:dubbo-serialization-protostuff - org.apache.dubbo:dubbo-serialization-gson - org.apache.dubbo:dubbo-serialization-protobuf org.apache.dubbo:dubbo-configcenter-api - org.apache.dubbo:dubbo-configcenter-definition org.apache.dubbo:dubbo-configcenter-apollo org.apache.dubbo:dubbo-configcenter-zookeeper - org.apache.dubbo:dubbo-configcenter-consul - org.apache.dubbo:dubbo-configcenter-etcd org.apache.dubbo:dubbo-configcenter-nacos org.apache.dubbo:dubbo-metadata-api org.apache.dubbo:dubbo-metadata-report-redis org.apache.dubbo:dubbo-metadata-report-zookeeper - org.apache.dubbo:dubbo-metadata-report-consul - org.apache.dubbo:dubbo-metadata-report-etcd - org.apache.dubbo:dubbo-metadata-report-nacos - org.apache.dubbo:dubbo-serialization-native-hession + org.apache.dubbo:dubbo-qos + org.apache.dubbo:dubbo-auth @@ -980,6 +669,18 @@ META-INF/services/org.apache.dubbo.common.extension.LoadingStrategy + + + META-INF/dubbo/internal/org.apache.dubbo.auth.spi.AccessKeyStorage + + + + + META-INF/dubbo/internal/org.apache.dubbo.auth.spi.Authenticator + + org.apache.dubbo:dubbo - + com/** org/** diff --git a/dubbo-distribution/dubbo-apache-release/pom.xml b/dubbo-distribution/dubbo-apache-release/pom.xml new file mode 100644 index 0000000000..fd0e67786a --- /dev/null +++ b/dubbo-distribution/dubbo-apache-release/pom.xml @@ -0,0 +1,100 @@ + + + 4.0.0 + + org.apache.dubbo + dubbo-distribution + ${revision} + ../pom.xml + + dubbo-apache-release + pom + dubbo-apache-release + The apache source release + + true + + + + + org.apache.dubbo + dubbo-demo-api-provider + ${project.version} + + + org.apache.dubbo + dubbo-demo-api-consumer + ${project.version} + + + + + + release + + apache-dubbo-${project.version} + + + maven-assembly-plugin + 3.1.0 + + + bin + package + + single + + + + src/assembly/bin-release.xml + + + + + src + package + + single + + + + src/assembly/source-release.xml + + + + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.6 + + + verify + + sign + + + + + + + + + diff --git a/dubbo-distribution/src/assembly/bin-release.xml b/dubbo-distribution/dubbo-apache-release/src/assembly/bin-release.xml similarity index 95% rename from dubbo-distribution/src/assembly/bin-release.xml rename to dubbo-distribution/dubbo-apache-release/src/assembly/bin-release.xml index 76409930e6..570d190173 100644 --- a/dubbo-distribution/src/assembly/bin-release.xml +++ b/dubbo-distribution/dubbo-apache-release/src/assembly/bin-release.xml @@ -24,7 +24,7 @@ ${project.build.finalName}-bin - ../ + ../../ DISCLAIMER NOTICE @@ -32,7 +32,7 @@ - ../dubbo-demo + ../../dubbo-demo README.md diff --git a/dubbo-distribution/src/assembly/source-release.xml b/dubbo-distribution/dubbo-apache-release/src/assembly/source-release.xml similarity index 98% rename from dubbo-distribution/src/assembly/source-release.xml rename to dubbo-distribution/dubbo-apache-release/src/assembly/source-release.xml index 2f265166b7..68bab41867 100644 --- a/dubbo-distribution/src/assembly/source-release.xml +++ b/dubbo-distribution/dubbo-apache-release/src/assembly/source-release.xml @@ -25,7 +25,7 @@ - ../ + ../../ true **/* diff --git a/dubbo-bom/pom.xml b/dubbo-distribution/dubbo-bom/pom.xml similarity index 89% rename from dubbo-bom/pom.xml rename to dubbo-distribution/dubbo-bom/pom.xml index a5b8b87c98..afd52bddab 100644 --- a/dubbo-bom/pom.xml +++ b/dubbo-distribution/dubbo-bom/pom.xml @@ -23,68 +23,13 @@ org.apache.dubbo dubbo-parent ${revision} - ../pom.xml + ../../pom.xml dubbo-bom pom dubbo-bom - Dubbo dependencies BOM - https://github.com/apache/dubbo - 2011 - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0 - repo - - - - - https://github.com/apache/dubbo - scm:git:https://github.com/apache/dubbo.git - scm:git:https://github.com/apache/dubbo.git - HEAD - - - - Development List - dev-subscribe@dubbo.apache.org - dev-unsubscribe@dubbo.apache.org - dev@dubbo.apache.org - - - Commits List - commits-subscribe@dubbo.apache.org - commits-unsubscribe@dubbo.apache.org - commits@dubbo.apache.org - - - Issues List - issues-subscribe@dubbo.apache.org - issues-unsubscribe@dubbo.apache.org - issues@dubbo.apache.org - - - - - dubbo.io - The Dubbo Project Contributors - dev-subscribe@dubbo.apache.org - http://dubbo.apache.org/ - - - - - The Apache Software Foundation - http://www.apache.org/ - - - - Github Issues - https://github.com/apache/dubbo/issues - diff --git a/dubbo-distribution/dubbo-core-spi/pom.xml b/dubbo-distribution/dubbo-core-spi/pom.xml new file mode 100644 index 0000000000..ad06e629cb --- /dev/null +++ b/dubbo-distribution/dubbo-core-spi/pom.xml @@ -0,0 +1,444 @@ + + + 4.0.0 + + org.apache.dubbo + dubbo-parent + ${revision} + ../../pom.xml + + dubbo-core-spi + jar + dubbo-core-spi + All the SPI definitions of Dubbo + + true + + + + + org.apache.dubbo + dubbo-cluster + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-common + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-remoting-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-rpc-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-registry-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-monitor-api + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-qos + ${project.version} + compile + true + + + org.apache.dubbo + dubbo-serialization-api + ${project.version} + compile + true + + + + org.apache.dubbo + dubbo-metadata-api + ${project.version} + compile + true + + + + + + + org.apache.maven.plugins + maven-shade-plugin + + + package + + shade + + + true + false + + + org.apache.dubbo:dubbo-common + org.apache.dubbo:dubbo-cluster + org.apache.dubbo:dubbo-qos + org.apache.dubbo:dubbo-remoting-api + org.apache.dubbo:dubbo-rpc-api + org.apache.dubbo:dubbo-cluster + org.apache.dubbo:dubbo-registry-api + org.apache.dubbo:dubbo-monitor-api + org.apache.dubbo:dubbo-container-api + org.apache.dubbo:dubbo-serialization-api + org.apache.dubbo:dubbo-metadata-api + + + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.compiler.Compiler + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionFactory + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.infra.InfraAdapter + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.logger.LoggerAdapter + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.status.StatusChecker + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.store.DataStore + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.threadpool.ThreadPool + + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization + + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.Dispatcher + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.Codec2 + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.exchange.Exchanger + + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder + + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.p2p.Networker + + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.telnet.TelnetHandler + + + + + META-INF/dubbo/internal/org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter + + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.Filter + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.InvokerListener + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.ExporterListener + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.ProxyFactory + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Cluster + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.LoadBalance + + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.Merger + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.RouterFactory + + + + + META-INF/dubbo/internal/org.apache.dubbo.rpc.cluster.ConfiguratorFactory + + + + META-INF/dubbo/internal/org.apache.dubbo.container.Container + + + META-INF/dubbo/internal/org.apache.dubbo.monitor.MonitorFactory + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory + + + + META-INF/dubbo/internal/org.apache.dubbo.validation.Validation + + + META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory + + + META-INF/dubbo/internal/org.apache.dubbo.qos.command.BaseCommand + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory + + + + + META-INF/dubbo/internal/org.apache.dubbo.event.EventDispatcher + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.MetadataServiceExporter + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.WritableMetadataService + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.ServiceNameMapping + + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.proxy.MetadataServiceProxyFactory + + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscoveryFactory + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.definition.builder.TypeBuilder + + + + META-INF/dubbo/internal/org.apache.dubbo.event.EventListener + + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceInstanceCustomizer + + + + + META-INF/dubbo/internal/org.apache.dubbo.registry.client.metadata.MetadataServiceURLBuilder + + + + + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.convert.Converter + + + + + META-INF/dubbo/internal/org.apache.dubbo.common.convert.multiple.MultiValueConverter + + + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.AnnotatedMethodParameterProcessor + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.rest.ServiceRestMetadataResolver + + + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.builder.TypeDefinitionBuilder + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.AnnotatedMethodParameterProcessor + + + + + META-INF/dubbo/internal/org.apache.dubbo.metadata.annotation.processing.rest.ServiceRestMetadataResolver + + + + + + + + + META-INF/services/org.apache.dubbo.common.extension.LoadingStrategy + + + + + + + org.apache.dubbo:dubbo + + + com/** + org/** + + META-INF/dubbo/** + + + + + + + + + + + diff --git a/dubbo-distribution/pom.xml b/dubbo-distribution/pom.xml index 5b18042087..c8995303a8 100644 --- a/dubbo-distribution/pom.xml +++ b/dubbo-distribution/pom.xml @@ -14,86 +14,44 @@ See the License for the specific language governing permissions and limitations under the License. --> - - 4.0.0 + + org.apache.dubbo dubbo-parent ${revision} ../pom.xml + 4.0.0 + dubbo-distribution pom - dubbo-distribution - The binary distribution module for dubbo temporarily - - true - - - - - org.apache.dubbo - dubbo-demo-api-provider - ${project.version} - - - org.apache.dubbo - dubbo-demo-api-consumer - ${project.version} - - release - - apache-dubbo-${project.version} - - - maven-assembly-plugin - 3.1.0 - - - bin - package - - single - - - - src/assembly/bin-release.xml - - - - - src - package - - single - - - - src/assembly/source-release.xml - - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.6 - - - verify - - sign - - - - - - + + dubbo-all + dubbo-apache-release + dubbo-bom + dubbo-core-spi + + + + dubbo-all + + true + + + dubbo-all + + + + dubbo-core-spi + + dubbo-all + diff --git a/dubbo-filter/dubbo-filter-cache/pom.xml b/dubbo-filter/dubbo-filter-cache/pom.xml index 22c905c579..49f99cff87 100644 --- a/dubbo-filter/dubbo-filter-cache/pom.xml +++ b/dubbo-filter/dubbo-filter-cache/pom.xml @@ -19,8 +19,7 @@ org.apache.dubbo dubbo-filter - ${revision} - ../pom.xml + 2.7.7-SNAPSHOT dubbo-filter-cache jar diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java index bba7aca0ee..69ae6710ee 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java @@ -1,43 +1,43 @@ -/* - * 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.apache.dubbo.cache; - -/** - * Cache interface to support storing and retrieval of value against a lookup key. It has two operation get and put. - *
  • put-Storing value against a key.
  • - *
  • get-Retrieval of object.
  • - * @see org.apache.dubbo.cache.support.lru.LruCache - * @see org.apache.dubbo.cache.support.jcache.JCache - * @see org.apache.dubbo.cache.support.expiring.ExpiringCache - * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache - */ -public interface Cache { - /** - * API to store value against a key - * @param key Unique identifier for the object being store. - * @param value Value getting store - */ - void put(Object key, Object value); - - /** - * API to return stored value using a key. - * @param key Unique identifier for cache lookup - * @return Return stored object against key - */ - Object get(Object key); - -} +/* + * 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.apache.dubbo.cache; + +/** + * Cache interface to support storing and retrieval of value against a lookup key. It has two operation get and put. + *
  • put-Storing value against a key.
  • + *
  • get-Retrieval of object.
  • + * @see org.apache.dubbo.cache.support.lru.LruCache + * @see org.apache.dubbo.cache.support.jcache.JCache + * @see org.apache.dubbo.cache.support.expiring.ExpiringCache + * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache + */ +public interface Cache { + /** + * API to store value against a key + * @param key Unique identifier for the object being store. + * @param value Value getting store + */ + void put(Object key, Object value); + + /** + * API to return stored value using a key. + * @param key Unique identifier for cache lookup + * @return Return stored object against key + */ + Object get(Object key); + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java index 77256bb5ee..66b5b59e2c 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java @@ -1,43 +1,43 @@ -/* - * 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.apache.dubbo.cache; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Adaptive; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.rpc.Invocation; - -/** - * Interface needs to be implemented by all the cache store provider.Along with implementing CacheFactory interface - * entry needs to be added in org.apache.dubbo.cache.CacheFactory file in a classpath META-INF sub directories. - * - * @see Cache - */ -@SPI("lru") -public interface CacheFactory { - - /** - * CacheFactory implementation class needs to implement this return underlying cache instance for method against - * url and invocation. - * @param url - * @param invocation - * @return Instance of Cache containing cached value against method url and invocation. - */ - @Adaptive("cache") - Cache getCache(URL url, Invocation invocation); - -} +/* + * 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.apache.dubbo.cache; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.Adaptive; +import org.apache.dubbo.common.extension.SPI; +import org.apache.dubbo.rpc.Invocation; + +/** + * Interface needs to be implemented by all the cache store provider.Along with implementing CacheFactory interface + * entry needs to be added in org.apache.dubbo.cache.CacheFactory file in a classpath META-INF sub directories. + * + * @see Cache + */ +@SPI("lru") +public interface CacheFactory { + + /** + * CacheFactory implementation class needs to implement this return underlying cache instance for method against + * url and invocation. + * @param url + * @param invocation + * @return Instance of Cache containing cached value against method url and invocation. + */ + @Adaptive("cache") + Cache getCache(URL url, Invocation invocation); + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java index 902bf6dcea..02d0e299a0 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java @@ -1,133 +1,133 @@ -/* - * 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.apache.dubbo.cache.filter; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.cache.CacheFactory; -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.utils.ConfigUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.rpc.AsyncRpcResult; -import org.apache.dubbo.rpc.Filter; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcException; - -import java.io.Serializable; - -import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; -import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; -import static org.apache.dubbo.common.constants.FilterConstants.CACHE_KEY; - -/** - * CacheFilter is a core component of dubbo.Enabling cache key of service,method,consumer or provider dubbo will cache method return value. - * Along with cache key we need to configure cache type. Dubbo default implemented cache types are - *
  • lur
  • - *
  • threadlocal
  • - *
  • jcache
  • - *
  • expiring
  • - * - *
    - *   e.g. 1)<dubbo:service cache="lru" />
    - *        2)<dubbo:service /> <dubbo:method name="method2" cache="threadlocal" /> <dubbo:service/>
    - *        3)<dubbo:provider cache="expiring" />
    - *        4)<dubbo:consumer cache="jcache" />
    - *
    - *If cache type is defined in method level then method level type will get precedence. According to above provided
    - *example, if service has two method, method1 and method2, method2 will have cache type as threadlocal where others will
    - *be backed by lru
    - *
    - * - * @see org.apache.dubbo.rpc.Filter - * @see org.apache.dubbo.cache.support.lru.LruCacheFactory - * @see org.apache.dubbo.cache.support.lru.LruCache - * @see org.apache.dubbo.cache.support.jcache.JCacheFactory - * @see org.apache.dubbo.cache.support.jcache.JCache - * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory - * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache - * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory - * @see org.apache.dubbo.cache.support.expiring.ExpiringCache - * - */ -@Activate(group = {CONSUMER, PROVIDER}, value = CACHE_KEY) -public class CacheFilter implements Filter { - - private CacheFactory cacheFactory; - - /** - * Dubbo will populate and set the cache factory instance based on service/method/consumer/provider configured - * cache attribute value. Dubbo will search for the class name implementing configured cache in file org.apache.dubbo.cache.CacheFactory - * under META-INF sub folders. - * - * @param cacheFactory instance of CacheFactory based on cache type - */ - public void setCacheFactory(CacheFactory cacheFactory) { - this.cacheFactory = cacheFactory; - } - - /** - * If cache is configured, dubbo will invoke method on each method call. If cache value is returned by cache store - * then it will return otherwise call the remote method and return value. If remote method's return value has error - * then it will not cache the value. - * @param invoker service - * @param invocation invocation. - * @return Cache returned value if found by the underlying cache store. If cache miss it will call target method. - * @throws RpcException - */ - @Override - public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - if (cacheFactory != null && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) { - Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation); - if (cache != null) { - String key = StringUtils.toArgumentString(invocation.getArguments()); - Object value = cache.get(key); - if (value != null) { - if (value instanceof ValueWrapper) { - return AsyncRpcResult.newDefaultAsyncResult(((ValueWrapper) value).get(), invocation); - } else { - return AsyncRpcResult.newDefaultAsyncResult(value, invocation); - } - } - Result result = invoker.invoke(invocation); - if (!result.hasException()) { - cache.put(key, new ValueWrapper(result.getValue())); - } - return result; - } - } - return invoker.invoke(invocation); - } - - /** - * Cache value wrapper. - */ - static class ValueWrapper implements Serializable { - - private static final long serialVersionUID = -1777337318019193256L; - - private final Object value; - - public ValueWrapper (Object value) { - this.value = value; - } - - public Object get() { - return this.value; - } - } -} +/* + * 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.apache.dubbo.cache.filter; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.cache.CacheFactory; +import org.apache.dubbo.common.extension.Activate; +import org.apache.dubbo.common.utils.ConfigUtils; +import org.apache.dubbo.common.utils.StringUtils; +import org.apache.dubbo.rpc.AsyncRpcResult; +import org.apache.dubbo.rpc.Filter; +import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Result; +import org.apache.dubbo.rpc.RpcException; + +import java.io.Serializable; + +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.FilterConstants.CACHE_KEY; + +/** + * CacheFilter is a core component of dubbo.Enabling cache key of service,method,consumer or provider dubbo will cache method return value. + * Along with cache key we need to configure cache type. Dubbo default implemented cache types are + *
  • lur
  • + *
  • threadlocal
  • + *
  • jcache
  • + *
  • expiring
  • + * + *
    + *   e.g. 1)<dubbo:service cache="lru" />
    + *        2)<dubbo:service /> <dubbo:method name="method2" cache="threadlocal" /> <dubbo:service/>
    + *        3)<dubbo:provider cache="expiring" />
    + *        4)<dubbo:consumer cache="jcache" />
    + *
    + *If cache type is defined in method level then method level type will get precedence. According to above provided
    + *example, if service has two method, method1 and method2, method2 will have cache type as threadlocal where others will
    + *be backed by lru
    + *
    + * + * @see org.apache.dubbo.rpc.Filter + * @see org.apache.dubbo.cache.support.lru.LruCacheFactory + * @see org.apache.dubbo.cache.support.lru.LruCache + * @see org.apache.dubbo.cache.support.jcache.JCacheFactory + * @see org.apache.dubbo.cache.support.jcache.JCache + * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory + * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache + * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory + * @see org.apache.dubbo.cache.support.expiring.ExpiringCache + * + */ +@Activate(group = {CONSUMER, PROVIDER}, value = CACHE_KEY) +public class CacheFilter implements Filter { + + private CacheFactory cacheFactory; + + /** + * Dubbo will populate and set the cache factory instance based on service/method/consumer/provider configured + * cache attribute value. Dubbo will search for the class name implementing configured cache in file org.apache.dubbo.cache.CacheFactory + * under META-INF sub folders. + * + * @param cacheFactory instance of CacheFactory based on cache type + */ + public void setCacheFactory(CacheFactory cacheFactory) { + this.cacheFactory = cacheFactory; + } + + /** + * If cache is configured, dubbo will invoke method on each method call. If cache value is returned by cache store + * then it will return otherwise call the remote method and return value. If remote method's return value has error + * then it will not cache the value. + * @param invoker service + * @param invocation invocation. + * @return Cache returned value if found by the underlying cache store. If cache miss it will call target method. + * @throws RpcException + */ + @Override + public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { + if (cacheFactory != null && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) { + Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation); + if (cache != null) { + String key = StringUtils.toArgumentString(invocation.getArguments()); + Object value = cache.get(key); + if (value != null) { + if (value instanceof ValueWrapper) { + return AsyncRpcResult.newDefaultAsyncResult(((ValueWrapper) value).get(), invocation); + } else { + return AsyncRpcResult.newDefaultAsyncResult(value, invocation); + } + } + Result result = invoker.invoke(invocation); + if (!result.hasException()) { + cache.put(key, new ValueWrapper(result.getValue())); + } + return result; + } + } + return invoker.invoke(invocation); + } + + /** + * Cache value wrapper. + */ + static class ValueWrapper implements Serializable { + + private static final long serialVersionUID = -1777337318019193256L; + + private final Object value; + + public ValueWrapper (Object value) { + this.value = value; + } + + public Object get() { + return this.value; + } + } +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java index 98ca797b24..966d923a78 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java @@ -1,72 +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.apache.dubbo.cache.support; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.cache.CacheFactory; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.Invocation; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; - -/** - * AbstractCacheFactory is a default implementation of {@link CacheFactory}. It abstract out the key formation from URL along with - * invocation method. It initially check if the value for key already present in own local in-memory store then it won't check underlying storage cache {@link Cache}. - * Internally it used {@link ConcurrentHashMap} to store do level-1 caching. - * - * @see CacheFactory - * @see org.apache.dubbo.cache.support.jcache.JCacheFactory - * @see org.apache.dubbo.cache.support.lru.LruCacheFactory - * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory - * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory - */ -public abstract class AbstractCacheFactory implements CacheFactory { - - /** - * This is used to store factory level-1 cached data. - */ - private final ConcurrentMap caches = new ConcurrentHashMap(); - - /** - * Takes URL and invocation instance and return cache instance for a given url. - * @param url url of the method - * @param invocation invocation context. - * @return Instance of cache store used as storage for caching return values. - */ - @Override - public Cache getCache(URL url, Invocation invocation) { - url = url.addParameter(METHOD_KEY, invocation.getMethodName()); - String key = url.toFullString(); - Cache cache = caches.get(key); - if (cache == null) { - caches.put(key, createCache(url)); - cache = caches.get(key); - } - return cache; - } - - /** - * Takes url as an method argument and return new instance of cache store implemented by AbstractCacheFactory subclass. - * @param url url of the method - * @return Create and return new instance of cache store used as storage for caching return values. - */ - protected abstract Cache createCache(URL url); - -} +/* + * 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.apache.dubbo.cache.support; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.cache.CacheFactory; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.rpc.Invocation; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; + +/** + * AbstractCacheFactory is a default implementation of {@link CacheFactory}. It abstract out the key formation from URL along with + * invocation method. It initially check if the value for key already present in own local in-memory store then it won't check underlying storage cache {@link Cache}. + * Internally it used {@link ConcurrentHashMap} to store do level-1 caching. + * + * @see CacheFactory + * @see org.apache.dubbo.cache.support.jcache.JCacheFactory + * @see org.apache.dubbo.cache.support.lru.LruCacheFactory + * @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory + * @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory + */ +public abstract class AbstractCacheFactory implements CacheFactory { + + /** + * This is used to store factory level-1 cached data. + */ + private final ConcurrentMap caches = new ConcurrentHashMap(); + + /** + * Takes URL and invocation instance and return cache instance for a given url. + * @param url url of the method + * @param invocation invocation context. + * @return Instance of cache store used as storage for caching return values. + */ + @Override + public Cache getCache(URL url, Invocation invocation) { + url = url.addParameter(METHOD_KEY, invocation.getMethodName()); + String key = url.toFullString(); + Cache cache = caches.get(key); + if (cache == null) { + caches.put(key, createCache(url)); + cache = caches.get(key); + } + return cache; + } + + /** + * Takes url as an method argument and return new instance of cache store implemented by AbstractCacheFactory subclass. + * @param url url of the method + * @return Create and return new instance of cache store used as storage for caching return values. + */ + protected abstract Cache createCache(URL url); + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java index bf4b3d1646..7972a9dd9a 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java @@ -1,87 +1,87 @@ -/* - * 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.apache.dubbo.cache.support.jcache; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.StringUtils; - -import javax.cache.Cache; -import javax.cache.CacheException; -import javax.cache.CacheManager; -import javax.cache.Caching; -import javax.cache.configuration.MutableConfiguration; -import javax.cache.expiry.CreatedExpiryPolicy; -import javax.cache.expiry.Duration; -import javax.cache.spi.CachingProvider; -import java.util.concurrent.TimeUnit; - -import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; - -/** - * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache - * with value jcache, dubbo initialize the instance of this class using {@link JCacheFactory} to store method's returns value - * to server from store without making method call. - * - * @see Cache - * @see JCacheFactory - * @see org.apache.dubbo.cache.support.AbstractCacheFactory - * @see org.apache.dubbo.cache.filter.CacheFilter - */ -public class JCache implements org.apache.dubbo.cache.Cache { - - private final Cache store; - - public JCache(URL url) { - String method = url.getParameter(METHOD_KEY, ""); - String key = url.getAddress() + "." + url.getServiceKey() + "." + method; - // jcache parameter is the full-qualified class name of SPI implementation - String type = url.getParameter("jcache"); - - CachingProvider provider = StringUtils.isEmpty(type) ? Caching.getCachingProvider() : Caching.getCachingProvider(type); - CacheManager cacheManager = provider.getCacheManager(); - Cache cache = cacheManager.getCache(key); - if (cache == null) { - try { - //configure the cache - MutableConfiguration config = - new MutableConfiguration<>() - .setTypes(Object.class, Object.class) - .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, url.getMethodParameter(method, "cache.write.expire", 60 * 1000)))) - .setStoreByValue(false) - .setManagementEnabled(true) - .setStatisticsEnabled(true); - cache = cacheManager.createCache(key, config); - } catch (CacheException e) { - // concurrent cache initialization - cache = cacheManager.getCache(key); - } - } - - this.store = cache; - } - - @Override - public void put(Object key, Object value) { - store.put(key, value); - } - - @Override - public Object get(Object key) { - return store.get(key); - } - -} +/* + * 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.apache.dubbo.cache.support.jcache; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.StringUtils; + +import javax.cache.Cache; +import javax.cache.CacheException; +import javax.cache.CacheManager; +import javax.cache.Caching; +import javax.cache.configuration.MutableConfiguration; +import javax.cache.expiry.CreatedExpiryPolicy; +import javax.cache.expiry.Duration; +import javax.cache.spi.CachingProvider; +import java.util.concurrent.TimeUnit; + +import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY; + +/** + * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache + * with value jcache, dubbo initialize the instance of this class using {@link JCacheFactory} to store method's returns value + * to server from store without making method call. + * + * @see Cache + * @see JCacheFactory + * @see org.apache.dubbo.cache.support.AbstractCacheFactory + * @see org.apache.dubbo.cache.filter.CacheFilter + */ +public class JCache implements org.apache.dubbo.cache.Cache { + + private final Cache store; + + public JCache(URL url) { + String method = url.getParameter(METHOD_KEY, ""); + String key = url.getAddress() + "." + url.getServiceKey() + "." + method; + // jcache parameter is the full-qualified class name of SPI implementation + String type = url.getParameter("jcache"); + + CachingProvider provider = StringUtils.isEmpty(type) ? Caching.getCachingProvider() : Caching.getCachingProvider(type); + CacheManager cacheManager = provider.getCacheManager(); + Cache cache = cacheManager.getCache(key); + if (cache == null) { + try { + //configure the cache + MutableConfiguration config = + new MutableConfiguration<>() + .setTypes(Object.class, Object.class) + .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, url.getMethodParameter(method, "cache.write.expire", 60 * 1000)))) + .setStoreByValue(false) + .setManagementEnabled(true) + .setStatisticsEnabled(true); + cache = cacheManager.createCache(key, config); + } catch (CacheException e) { + // concurrent cache initialization + cache = cacheManager.getCache(key); + } + } + + this.store = cache; + } + + @Override + public void put(Object key, Object value) { + store.put(key, value); + } + + @Override + public Object get(Object key) { + return store.get(key); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java index c4d713f0b1..aba9a2f9c4 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java @@ -1,48 +1,48 @@ -/* - * 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.apache.dubbo.cache.support.jcache; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.cache.support.AbstractCacheFactory; -import org.apache.dubbo.common.URL; - -import javax.cache.spi.CachingProvider; - -/** - * JCacheFactory is factory class to provide instance of javax spi cache.Implement {@link org.apache.dubbo.cache.CacheFactory} by - * extending {@link AbstractCacheFactory} and provide - * @see AbstractCacheFactory - * @see JCache - * @see org.apache.dubbo.cache.filter.CacheFilter - * @see Cache - * @see CachingProvider - * @see javax.cache.Cache - * @see javax.cache.CacheManager - */ -public class JCacheFactory extends AbstractCacheFactory { - - /** - * Takes url as an method argument and return new instance of cache store implemented by JCache. - * @param url url of the method - * @return JCache instance of cache - */ - @Override - protected Cache createCache(URL url) { - return new JCache(url); - } - -} +/* + * 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.apache.dubbo.cache.support.jcache; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.cache.support.AbstractCacheFactory; +import org.apache.dubbo.common.URL; + +import javax.cache.spi.CachingProvider; + +/** + * JCacheFactory is factory class to provide instance of javax spi cache.Implement {@link org.apache.dubbo.cache.CacheFactory} by + * extending {@link AbstractCacheFactory} and provide + * @see AbstractCacheFactory + * @see JCache + * @see org.apache.dubbo.cache.filter.CacheFilter + * @see Cache + * @see CachingProvider + * @see javax.cache.Cache + * @see javax.cache.CacheManager + */ +public class JCacheFactory extends AbstractCacheFactory { + + /** + * Takes url as an method argument and return new instance of cache store implemented by JCache. + * @param url url of the method + * @return JCache instance of cache + */ + @Override + protected Cache createCache(URL url) { + return new JCache(url); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java index bb24fed9b2..1b8022fb78 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java @@ -1,80 +1,80 @@ -/* - * 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.apache.dubbo.cache.support.lru; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.LRUCache; - -import java.util.Map; - -/** - * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache - * with value lru, dubbo initialize the instance of this class using {@link LruCacheFactory} to store method's returns value - * to server from store without making method call. - *
    - *     e.g. 1) <dubbo:service cache="lru" cache.size="5000"/>
    - *          2) <dubbo:consumer cache="lru" />
    - * 
    - *
    - * LruCache uses url's cache.size value for its max store size, if nothing is provided then
    - * default value will be 1000
    - * 
    - * - * @see Cache - * @see LruCacheFactory - * @see org.apache.dubbo.cache.support.AbstractCacheFactory - * @see org.apache.dubbo.cache.filter.CacheFilter - */ -public class LruCache implements Cache { - - /** - * This is used to store cache records - */ - private final Map store; - - /** - * Initialize LruCache, it uses constructor argument cache.size value as its storage max size. - * If nothing is provided then it will use 1000 as default value. - * @param url A valid URL instance - */ - public LruCache(URL url) { - final int max = url.getParameter("cache.size", 1000); - this.store = new LRUCache<>(max); - } - - /** - * API to store value against a key in the calling thread scope. - * @param key Unique identifier for the object being store. - * @param value Value getting store - */ - @Override - public void put(Object key, Object value) { - store.put(key, value); - } - - /** - * API to return stored value using a key against the calling thread specific store. - * @param key Unique identifier for cache lookup - * @return Return stored object against key - */ - @Override - public Object get(Object key) { - return store.get(key); - } - -} +/* + * 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.apache.dubbo.cache.support.lru; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.utils.LRUCache; + +import java.util.Map; + +/** + * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache + * with value lru, dubbo initialize the instance of this class using {@link LruCacheFactory} to store method's returns value + * to server from store without making method call. + *
    + *     e.g. 1) <dubbo:service cache="lru" cache.size="5000"/>
    + *          2) <dubbo:consumer cache="lru" />
    + * 
    + *
    + * LruCache uses url's cache.size value for its max store size, if nothing is provided then
    + * default value will be 1000
    + * 
    + * + * @see Cache + * @see LruCacheFactory + * @see org.apache.dubbo.cache.support.AbstractCacheFactory + * @see org.apache.dubbo.cache.filter.CacheFilter + */ +public class LruCache implements Cache { + + /** + * This is used to store cache records + */ + private final Map store; + + /** + * Initialize LruCache, it uses constructor argument cache.size value as its storage max size. + * If nothing is provided then it will use 1000 as default value. + * @param url A valid URL instance + */ + public LruCache(URL url) { + final int max = url.getParameter("cache.size", 1000); + this.store = new LRUCache<>(max); + } + + /** + * API to store value against a key in the calling thread scope. + * @param key Unique identifier for the object being store. + * @param value Value getting store + */ + @Override + public void put(Object key, Object value) { + store.put(key, value); + } + + /** + * API to return stored value using a key against the calling thread specific store. + * @param key Unique identifier for cache lookup + * @return Return stored object against key + */ + @Override + public Object get(Object key) { + return store.get(key); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java index cda21292e8..9ec94862a5 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java @@ -1,43 +1,43 @@ -/* - * 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.apache.dubbo.cache.support.lru; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.cache.support.AbstractCacheFactory; -import org.apache.dubbo.common.URL; - -/** - * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide - * instance of new {@link LruCache}. - * - * @see AbstractCacheFactory - * @see LruCache - * @see Cache - */ -public class LruCacheFactory extends AbstractCacheFactory { - - /** - * Takes url as an method argument and return new instance of cache store implemented by LruCache. - * @param url url of the method - * @return ThreadLocalCache instance of cache - */ - @Override - protected Cache createCache(URL url) { - return new LruCache(url); - } - -} +/* + * 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.apache.dubbo.cache.support.lru; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.cache.support.AbstractCacheFactory; +import org.apache.dubbo.common.URL; + +/** + * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide + * instance of new {@link LruCache}. + * + * @see AbstractCacheFactory + * @see LruCache + * @see Cache + */ +public class LruCacheFactory extends AbstractCacheFactory { + + /** + * Takes url as an method argument and return new instance of cache store implemented by LruCache. + * @param url url of the method + * @return ThreadLocalCache instance of cache + */ + @Override + protected Cache createCache(URL url) { + return new LruCache(url); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java index 412e1beae2..12b3b5ca03 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java @@ -1,77 +1,77 @@ -/* - * 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.apache.dubbo.cache.support.threadlocal; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.common.URL; - -import java.util.HashMap; -import java.util.Map; - -/** - * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache - * with value threadlocal, dubbo initialize the instance of this class using {@link ThreadLocalCacheFactory} to store method's returns value - * to server from store without making method call. - *
    - *      e.g. <dubbo:service cache="threadlocal" />
    - *  
    - *
    - * As this ThreadLocalCache stores key-value in memory without any expiry or delete support per thread wise, if number threads and number of key-value are high then jvm should be
    - * configured with appropriate memory.
    - * 
    - * - * @see org.apache.dubbo.cache.support.AbstractCacheFactory - * @see org.apache.dubbo.cache.filter.CacheFilter - * @see Cache - */ -public class ThreadLocalCache implements Cache { - - /** - * Thread local variable to store cached data. - */ - private final ThreadLocal> store; - - /** - * Taken URL as an argument to create an instance of ThreadLocalCache. In this version of implementation constructor - * argument is not getting used in the scope of this class. - * @param url - */ - public ThreadLocalCache(URL url) { - this.store = ThreadLocal.withInitial(HashMap::new); - } - - /** - * API to store value against a key in the calling thread scope. - * @param key Unique identifier for the object being store. - * @param value Value getting store - */ - @Override - public void put(Object key, Object value) { - store.get().put(key, value); - } - - /** - * API to return stored value using a key against the calling thread specific store. - * @param key Unique identifier for cache lookup - * @return Return stored object against key - */ - @Override - public Object get(Object key) { - return store.get().get(key); - } - -} +/* + * 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.apache.dubbo.cache.support.threadlocal; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.common.URL; + +import java.util.HashMap; +import java.util.Map; + +/** + * This class store the cache value per thread. If a service,method,consumer or provided is configured with key cache + * with value threadlocal, dubbo initialize the instance of this class using {@link ThreadLocalCacheFactory} to store method's returns value + * to server from store without making method call. + *
    + *      e.g. <dubbo:service cache="threadlocal" />
    + *  
    + *
    + * As this ThreadLocalCache stores key-value in memory without any expiry or delete support per thread wise, if number threads and number of key-value are high then jvm should be
    + * configured with appropriate memory.
    + * 
    + * + * @see org.apache.dubbo.cache.support.AbstractCacheFactory + * @see org.apache.dubbo.cache.filter.CacheFilter + * @see Cache + */ +public class ThreadLocalCache implements Cache { + + /** + * Thread local variable to store cached data. + */ + private final ThreadLocal> store; + + /** + * Taken URL as an argument to create an instance of ThreadLocalCache. In this version of implementation constructor + * argument is not getting used in the scope of this class. + * @param url + */ + public ThreadLocalCache(URL url) { + this.store = ThreadLocal.withInitial(HashMap::new); + } + + /** + * API to store value against a key in the calling thread scope. + * @param key Unique identifier for the object being store. + * @param value Value getting store + */ + @Override + public void put(Object key, Object value) { + store.get().put(key, value); + } + + /** + * API to return stored value using a key against the calling thread specific store. + * @param key Unique identifier for cache lookup + * @return Return stored object against key + */ + @Override + public Object get(Object key) { + return store.get().get(key); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java index bde16f63bd..cdda6cf3e4 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java +++ b/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java @@ -1,43 +1,43 @@ -/* - * 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.apache.dubbo.cache.support.threadlocal; - -import org.apache.dubbo.cache.Cache; -import org.apache.dubbo.cache.support.AbstractCacheFactory; -import org.apache.dubbo.common.URL; - -/** - * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide - * instance of new {@link ThreadLocalCache}. Note about this class is, each thread does not have a local copy of factory. - * - * @see AbstractCacheFactory - * @see ThreadLocalCache - * @see Cache - */ -public class ThreadLocalCacheFactory extends AbstractCacheFactory { - - /** - * Takes url as an method argument and return new instance of cache store implemented by ThreadLocalCache. - * @param url url of the method - * @return ThreadLocalCache instance of cache - */ - @Override - protected Cache createCache(URL url) { - return new ThreadLocalCache(url); - } - -} +/* + * 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.apache.dubbo.cache.support.threadlocal; + +import org.apache.dubbo.cache.Cache; +import org.apache.dubbo.cache.support.AbstractCacheFactory; +import org.apache.dubbo.common.URL; + +/** + * Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide + * instance of new {@link ThreadLocalCache}. Note about this class is, each thread does not have a local copy of factory. + * + * @see AbstractCacheFactory + * @see ThreadLocalCache + * @see Cache + */ +public class ThreadLocalCacheFactory extends AbstractCacheFactory { + + /** + * Takes url as an method argument and return new instance of cache store implemented by ThreadLocalCache. + * @param url url of the method + * @return ThreadLocalCache instance of cache + */ + @Override + protected Cache createCache(URL url) { + return new ThreadLocalCache(url); + } + +} diff --git a/dubbo-filter/dubbo-filter-cache/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory b/dubbo-filter/dubbo-filter-cache/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory index c849461da1..1ea180adf5 100644 --- a/dubbo-filter/dubbo-filter-cache/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory +++ b/dubbo-filter/dubbo-filter-cache/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.cache.CacheFactory @@ -1,4 +1,4 @@ -threadlocal=org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory -lru=org.apache.dubbo.cache.support.lru.LruCacheFactory -jcache=org.apache.dubbo.cache.support.jcache.JCacheFactory +threadlocal=org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory +lru=org.apache.dubbo.cache.support.lru.LruCacheFactory +jcache=org.apache.dubbo.cache.support.jcache.JCacheFactory expiring=org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory \ No newline at end of file diff --git a/dubbo-filter/dubbo-filter-validation/pom.xml b/dubbo-filter/dubbo-filter-validation/pom.xml index 164653e52c..933f1c97be 100644 --- a/dubbo-filter/dubbo-filter-validation/pom.xml +++ b/dubbo-filter/dubbo-filter-validation/pom.xml @@ -19,8 +19,7 @@ org.apache.dubbo dubbo-filter - ${revision} - ../pom.xml + 2.7.7-SNAPSHOT dubbo-filter-validation jar diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java index 281346c2ec..73c4cd8cdc 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java @@ -1,39 +1,39 @@ -/* - * 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.apache.dubbo.validation; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Adaptive; -import org.apache.dubbo.common.extension.SPI; - -import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; - -/** - * Instance of Validation interface provide instance of {@link Validator} based on the value of validation attribute. - */ -@SPI("jvalidation") -public interface Validation { - - /** - * Return the instance of {@link Validator} for a given url. - * @param url Invocation url - * @return Instance of {@link Validator} - */ - @Adaptive(VALIDATION_KEY) - Validator getValidator(URL url); - -} +/* + * 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.apache.dubbo.validation; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.extension.Adaptive; +import org.apache.dubbo.common.extension.SPI; + +import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; + +/** + * Instance of Validation interface provide instance of {@link Validator} based on the value of validation attribute. + */ +@SPI("jvalidation") +public interface Validation { + + /** + * Return the instance of {@link Validator} for a given url. + * @param url Invocation url + * @return Instance of {@link Validator} + */ + @Adaptive(VALIDATION_KEY) + Validator getValidator(URL url); + +} diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java index b1565ba4b6..c78c62a116 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java @@ -1,27 +1,27 @@ -/* - * 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.apache.dubbo.validation; - -/** - * Instance of validator class is an extension to perform validation on method input parameter before the actual method invocation. - * - */ -public interface Validator { - - void validate(String methodName, Class[] parameterTypes, Object[] arguments) throws Exception; - -} +/* + * 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.apache.dubbo.validation; + +/** + * Instance of validator class is an extension to perform validation on method input parameter before the actual method invocation. + * + */ +public interface Validator { + + void validate(String methodName, Class[] parameterTypes, Object[] arguments) throws Exception; + +} diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java index 774b1debb5..0df27526e1 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java @@ -1,104 +1,104 @@ -/* - * 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.apache.dubbo.validation.filter; - -import org.apache.dubbo.common.extension.Activate; -import org.apache.dubbo.common.utils.ConfigUtils; -import org.apache.dubbo.rpc.AsyncRpcResult; -import org.apache.dubbo.rpc.Filter; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.validation.Validation; -import org.apache.dubbo.validation.Validator; - -import javax.validation.ValidationException; - -import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; -import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; -import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; - -/** - * ValidationFilter invoke the validation by finding the right {@link Validator} instance based on the - * configured validation attribute value of invoker url before the actual method invocation. - * - *
    - *     e.g. <dubbo:method name="save" validation="jvalidation" />
    - *     In the above configuration a validation has been configured of type jvalidation. On invocation of method save
    - *     dubbo will invoke {@link org.apache.dubbo.validation.support.jvalidation.JValidator}
    - * 
    - * - * To add a new type of validation - *
    - *     e.g. <dubbo:method name="save" validation="special" />
    - *     where "special" is representing a validator for special character.
    - * 
    - * - * developer needs to do - *
    - * 1)Implement a SpecialValidation.java class (package name xxx.yyy.zzz) either by implementing {@link Validation} or extending {@link org.apache.dubbo.validation.support.AbstractValidation}
    - * 2)Implement a SpecialValidator.java class (package name xxx.yyy.zzz)
    - * 3)Add an entry special=xxx.yyy.zzz.SpecialValidation under META-INF folders org.apache.dubbo.validation.Validation file. - * - * @see Validation - * @see Validator - * @see Filter - * @see org.apache.dubbo.validation.support.AbstractValidation - */ -@Activate(group = {CONSUMER, PROVIDER}, value = VALIDATION_KEY, order = 10000) -public class ValidationFilter implements Filter { - - private Validation validation; - - /** - * Sets the validation instance for ValidationFilter - * @param validation Validation instance injected by dubbo framework based on "validation" attribute value. - */ - public void setValidation(Validation validation) { - this.validation = validation; - } - - /** - * Perform the validation of before invoking the actual method based on validation attribute value. - * @param invoker service - * @param invocation invocation. - * @return Method invocation result - * @throws RpcException Throws RpcException if validation failed or any other runtime exception occurred. - */ - @Override - public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { - if (validation != null && !invocation.getMethodName().startsWith("$") - && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), VALIDATION_KEY))) { - try { - Validator validator = validation.getValidator(invoker.getUrl()); - if (validator != null) { - validator.validate(invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); - } - } catch (RpcException e) { - throw e; - } catch (ValidationException e) { - // only use exception's message to avoid potential serialization issue - return AsyncRpcResult.newDefaultAsyncResult(new ValidationException(e.getMessage()), invocation); - } catch (Throwable t) { - return AsyncRpcResult.newDefaultAsyncResult(t, invocation); - } - } - return invoker.invoke(invocation); - } - -} +/* + * 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.apache.dubbo.validation.filter; + +import org.apache.dubbo.common.extension.Activate; +import org.apache.dubbo.common.utils.ConfigUtils; +import org.apache.dubbo.rpc.AsyncRpcResult; +import org.apache.dubbo.rpc.Filter; +import org.apache.dubbo.rpc.Invocation; +import org.apache.dubbo.rpc.Invoker; +import org.apache.dubbo.rpc.Result; +import org.apache.dubbo.rpc.RpcException; +import org.apache.dubbo.validation.Validation; +import org.apache.dubbo.validation.Validator; + +import javax.validation.ValidationException; + +import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER; +import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; +import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY; + +/** + * ValidationFilter invoke the validation by finding the right {@link Validator} instance based on the + * configured validation attribute value of invoker url before the actual method invocation. + * + *
    + *     e.g. <dubbo:method name="save" validation="jvalidation" />
    + *     In the above configuration a validation has been configured of type jvalidation. On invocation of method save
    + *     dubbo will invoke {@link org.apache.dubbo.validation.support.jvalidation.JValidator}
    + * 
    + * + * To add a new type of validation + *
    + *     e.g. <dubbo:method name="save" validation="special" />
    + *     where "special" is representing a validator for special character.
    + * 
    + * + * developer needs to do + *
    + * 1)Implement a SpecialValidation.java class (package name xxx.yyy.zzz) either by implementing {@link Validation} or extending {@link org.apache.dubbo.validation.support.AbstractValidation}
    + * 2)Implement a SpecialValidator.java class (package name xxx.yyy.zzz)
    + * 3)Add an entry special=xxx.yyy.zzz.SpecialValidation under META-INF folders org.apache.dubbo.validation.Validation file. + * + * @see Validation + * @see Validator + * @see Filter + * @see org.apache.dubbo.validation.support.AbstractValidation + */ +@Activate(group = {CONSUMER, PROVIDER}, value = VALIDATION_KEY, order = 10000) +public class ValidationFilter implements Filter { + + private Validation validation; + + /** + * Sets the validation instance for ValidationFilter + * @param validation Validation instance injected by dubbo framework based on "validation" attribute value. + */ + public void setValidation(Validation validation) { + this.validation = validation; + } + + /** + * Perform the validation of before invoking the actual method based on validation attribute value. + * @param invoker service + * @param invocation invocation. + * @return Method invocation result + * @throws RpcException Throws RpcException if validation failed or any other runtime exception occurred. + */ + @Override + public Result invoke(Invoker invoker, Invocation invocation) throws RpcException { + if (validation != null && !invocation.getMethodName().startsWith("$") + && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), VALIDATION_KEY))) { + try { + Validator validator = validation.getValidator(invoker.getUrl()); + if (validator != null) { + validator.validate(invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); + } + } catch (RpcException e) { + throw e; + } catch (ValidationException e) { + // only use exception's message to avoid potential serialization issue + return AsyncRpcResult.newDefaultAsyncResult(new ValidationException(e.getMessage()), invocation); + } catch (Throwable t) { + return AsyncRpcResult.newDefaultAsyncResult(t, invocation); + } + } + return invoker.invoke(invocation); + } + +} diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java index be161a94d7..a6f9c8eda3 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java @@ -1,51 +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.apache.dubbo.validation.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.validation.Validation; -import org.apache.dubbo.validation.Validator; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * AbstractValidation is abstract class for Validation interface. It helps low level Validation implementation classes - * by performing common task e.g. key formation, storing instance of validation class to avoid creation of unnecessary - * copy of validation instance and faster execution. - * - * @see Validation - * @see Validator - */ -public abstract class AbstractValidation implements Validation { - - private final ConcurrentMap validators = new ConcurrentHashMap<>(); - - @Override - public Validator getValidator(URL url) { - String key = url.toFullString(); - Validator validator = validators.get(key); - if (validator == null) { - validators.put(key, createValidator(url)); - validator = validators.get(key); - } - return validator; - } - - protected abstract Validator createValidator(URL url); - -} +/* + * 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.apache.dubbo.validation.support; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.validation.Validation; +import org.apache.dubbo.validation.Validator; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * AbstractValidation is abstract class for Validation interface. It helps low level Validation implementation classes + * by performing common task e.g. key formation, storing instance of validation class to avoid creation of unnecessary + * copy of validation instance and faster execution. + * + * @see Validation + * @see Validator + */ +public abstract class AbstractValidation implements Validation { + + private final ConcurrentMap validators = new ConcurrentHashMap<>(); + + @Override + public Validator getValidator(URL url) { + String key = url.toFullString(); + Validator validator = validators.get(key); + if (validator == null) { + validators.put(key, createValidator(url)); + validator = validators.get(key); + } + return validator; + } + + protected abstract Validator createValidator(URL url); + +} diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java index e0859897f1..e8b48cf1d0 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java @@ -1,40 +1,40 @@ -/* - * 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.apache.dubbo.validation.support.jvalidation; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.validation.Validator; -import org.apache.dubbo.validation.support.AbstractValidation; - -/** - * Creates a new instance of {@link Validator} using input argument url. - * @see AbstractValidation - * @see Validator - */ -public class JValidation extends AbstractValidation { - - /** - * Return new instance of {@link JValidator} - * @param url Valid URL instance - * @return Instance of JValidator - */ - @Override - protected Validator createValidator(URL url) { - return new JValidator(url); - } - +/* + * 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.apache.dubbo.validation.support.jvalidation; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.validation.Validator; +import org.apache.dubbo.validation.support.AbstractValidation; + +/** + * Creates a new instance of {@link Validator} using input argument url. + * @see AbstractValidation + * @see Validator + */ +public class JValidation extends AbstractValidation { + + /** + * Return new instance of {@link JValidator} + * @param url Valid URL instance + * @return Instance of JValidator + */ + @Override + protected Validator createValidator(URL url) { + return new JValidator(url); + } + } \ No newline at end of file diff --git a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java index e3978c6c13..ea8c6dbd4a 100644 --- a/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java +++ b/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java @@ -1,330 +1,330 @@ -/* - * 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.apache.dubbo.validation.support.jvalidation; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.bytecode.ClassGenerator; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ReflectUtils; -import org.apache.dubbo.validation.MethodValidated; -import org.apache.dubbo.validation.Validator; - -import javassist.ClassPool; -import javassist.CtClass; -import javassist.CtField; -import javassist.CtNewConstructor; -import javassist.Modifier; -import javassist.NotFoundException; -import javassist.bytecode.AnnotationsAttribute; -import javassist.bytecode.ClassFile; -import javassist.bytecode.ConstPool; -import javassist.bytecode.annotation.ArrayMemberValue; -import javassist.bytecode.annotation.BooleanMemberValue; -import javassist.bytecode.annotation.ByteMemberValue; -import javassist.bytecode.annotation.CharMemberValue; -import javassist.bytecode.annotation.ClassMemberValue; -import javassist.bytecode.annotation.DoubleMemberValue; -import javassist.bytecode.annotation.EnumMemberValue; -import javassist.bytecode.annotation.FloatMemberValue; -import javassist.bytecode.annotation.IntegerMemberValue; -import javassist.bytecode.annotation.LongMemberValue; -import javassist.bytecode.annotation.MemberValue; -import javassist.bytecode.annotation.ShortMemberValue; -import javassist.bytecode.annotation.StringMemberValue; - -import javax.validation.Constraint; -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; -import javax.validation.Validation; -import javax.validation.ValidatorFactory; -import javax.validation.groups.Default; -import java.lang.annotation.Annotation; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Implementation of JValidation. JValidation is invoked if configuration validation attribute value is 'jvalidation'. - *
    - *     e.g. <dubbo:method name="save" validation="jvalidation" />
    - * 
    - */ -public class JValidator implements Validator { - - private static final Logger logger = LoggerFactory.getLogger(JValidator.class); - - private final Class clazz; - - private final Map methodClassMap; - - private final javax.validation.Validator validator; - - @SuppressWarnings({"unchecked", "rawtypes"}) - public JValidator(URL url) { - this.clazz = ReflectUtils.forName(url.getServiceInterface()); - String jvalidation = url.getParameter("jvalidation"); - ValidatorFactory factory; - if (jvalidation != null && jvalidation.length() > 0) { - factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory(); - } else { - factory = Validation.buildDefaultValidatorFactory(); - } - this.validator = factory.getValidator(); - this.methodClassMap = new ConcurrentHashMap<>(); - } - - private static Object getMethodParameterBean(Class clazz, Method method, Object[] args) { - if (!hasConstraintParameter(method)) { - return null; - } - try { - String parameterClassName = generateMethodParameterClassName(clazz, method); - Class parameterClass; - try { - parameterClass = Class.forName(parameterClassName, true, clazz.getClassLoader()); - } catch (ClassNotFoundException e) { - parameterClass = generateMethodParameterClass(clazz, method, parameterClassName); - } - Object parameterBean = parameterClass.newInstance(); - for (int i = 0; i < args.length; i++) { - Field field = parameterClass.getField(method.getName() + "Argument" + i); - field.set(parameterBean, args[i]); - } - return parameterBean; - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - return null; - } - } - - /** - * try to generate methodParameterClass. - * - * @param clazz interface class - * @param method invoke method - * @param parameterClassName generated parameterClassName - * @return Class generated methodParameterClass - * @throws Exception - */ - private static Class generateMethodParameterClass(Class clazz, Method method, String parameterClassName) - throws Exception { - ClassPool pool = ClassGenerator.getClassPool(clazz.getClassLoader()); - synchronized (parameterClassName.intern()) { - CtClass ctClass = null; - try { - ctClass = pool.getCtClass(parameterClassName); - } catch (NotFoundException ignore) { - } - - if (null == ctClass) { - ctClass = pool.makeClass(parameterClassName); - ClassFile classFile = ctClass.getClassFile(); - classFile.setVersionToJava5(); - ctClass.addConstructor(CtNewConstructor.defaultConstructor(pool.getCtClass(parameterClassName))); - // parameter fields - Class[] parameterTypes = method.getParameterTypes(); - Annotation[][] parameterAnnotations = method.getParameterAnnotations(); - for (int i = 0; i < parameterTypes.length; i++) { - Class type = parameterTypes[i]; - Annotation[] annotations = parameterAnnotations[i]; - AnnotationsAttribute attribute = new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag); - for (Annotation annotation : annotations) { - if (annotation.annotationType().isAnnotationPresent(Constraint.class)) { - javassist.bytecode.annotation.Annotation ja = new javassist.bytecode.annotation.Annotation( - classFile.getConstPool(), pool.getCtClass(annotation.annotationType().getName())); - Method[] members = annotation.annotationType().getMethods(); - for (Method member : members) { - if (Modifier.isPublic(member.getModifiers()) - && member.getParameterTypes().length == 0 - && member.getDeclaringClass() == annotation.annotationType()) { - Object value = member.invoke(annotation); - if (null != value) { - MemberValue memberValue = createMemberValue( - classFile.getConstPool(), pool.get(member.getReturnType().getName()), value); - ja.addMemberValue(member.getName(), memberValue); - } - } - } - attribute.addAnnotation(ja); - } - } - String fieldName = method.getName() + "Argument" + i; - CtField ctField = CtField.make("public " + type.getCanonicalName() + " " + fieldName + ";", pool.getCtClass(parameterClassName)); - ctField.getFieldInfo().addAttribute(attribute); - ctClass.addField(ctField); - } - return ctClass.toClass(clazz.getClassLoader(), null); - } else { - return Class.forName(parameterClassName, true, clazz.getClassLoader()); - } - } - } - - private static String generateMethodParameterClassName(Class clazz, Method method) { - StringBuilder builder = new StringBuilder().append(clazz.getName()) - .append("_") - .append(toUpperMethodName(method.getName())) - .append("Parameter"); - - Class[] parameterTypes = method.getParameterTypes(); - for (Class parameterType : parameterTypes) { - builder.append("_").append(parameterType.getName()); - } - - return builder.toString(); - } - - private static boolean hasConstraintParameter(Method method) { - Annotation[][] parameterAnnotations = method.getParameterAnnotations(); - if (parameterAnnotations != null && parameterAnnotations.length > 0) { - for (Annotation[] annotations : parameterAnnotations) { - for (Annotation annotation : annotations) { - if (annotation.annotationType().isAnnotationPresent(Constraint.class)) { - return true; - } - } - } - } - return false; - } - - private static String toUpperMethodName(String methodName) { - return methodName.substring(0, 1).toUpperCase() + methodName.substring(1); - } - - // Copy from javassist.bytecode.annotation.Annotation.createMemberValue(ConstPool, CtClass); - private static MemberValue createMemberValue(ConstPool cp, CtClass type, Object value) throws NotFoundException { - MemberValue memberValue = javassist.bytecode.annotation.Annotation.createMemberValue(cp, type); - if (memberValue instanceof BooleanMemberValue) { - ((BooleanMemberValue) memberValue).setValue((Boolean) value); - } else if (memberValue instanceof ByteMemberValue) { - ((ByteMemberValue) memberValue).setValue((Byte) value); - } else if (memberValue instanceof CharMemberValue) { - ((CharMemberValue) memberValue).setValue((Character) value); - } else if (memberValue instanceof ShortMemberValue) { - ((ShortMemberValue) memberValue).setValue((Short) value); - } else if (memberValue instanceof IntegerMemberValue) { - ((IntegerMemberValue) memberValue).setValue((Integer) value); - } else if (memberValue instanceof LongMemberValue) { - ((LongMemberValue) memberValue).setValue((Long) value); - } else if (memberValue instanceof FloatMemberValue) { - ((FloatMemberValue) memberValue).setValue((Float) value); - } else if (memberValue instanceof DoubleMemberValue) { - ((DoubleMemberValue) memberValue).setValue((Double) value); - } else if (memberValue instanceof ClassMemberValue) { - ((ClassMemberValue) memberValue).setValue(((Class) value).getName()); - } else if (memberValue instanceof StringMemberValue) { - ((StringMemberValue) memberValue).setValue((String) value); - } else if (memberValue instanceof EnumMemberValue) { - ((EnumMemberValue) memberValue).setValue(((Enum) value).name()); - } - /* else if (memberValue instanceof AnnotationMemberValue) */ - else if (memberValue instanceof ArrayMemberValue) { - CtClass arrayType = type.getComponentType(); - int len = Array.getLength(value); - MemberValue[] members = new MemberValue[len]; - for (int i = 0; i < len; i++) { - members[i] = createMemberValue(cp, arrayType, Array.get(value, i)); - } - ((ArrayMemberValue) memberValue).setValue(members); - } - return memberValue; - } - - @Override - public void validate(String methodName, Class[] parameterTypes, Object[] arguments) throws Exception { - List> groups = new ArrayList<>(); - Class methodClass = methodClass(methodName); - if (methodClass != null) { - groups.add(methodClass); - } - Set> violations = new HashSet<>(); - Method method = clazz.getMethod(methodName, parameterTypes); - Class[] methodClasses; - if (method.isAnnotationPresent(MethodValidated.class)){ - methodClasses = method.getAnnotation(MethodValidated.class).value(); - groups.addAll(Arrays.asList(methodClasses)); - } - // add into default group - groups.add(0, Default.class); - groups.add(1, clazz); - - // convert list to array - Class[] classgroups = groups.toArray(new Class[groups.size()]); - - Object parameterBean = getMethodParameterBean(clazz, method, arguments); - if (parameterBean != null) { - violations.addAll(validator.validate(parameterBean, classgroups )); - } - - for (Object arg : arguments) { - validate(violations, arg, classgroups); - } - - if (!violations.isEmpty()) { - logger.error("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations); - throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations); - } - } - - private Class methodClass(String methodName) { - Class methodClass = null; - String methodClassName = clazz.getName() + "$" + toUpperMethodName(methodName); - Class cached = methodClassMap.get(methodClassName); - if (cached != null) { - return cached == clazz ? null : cached; - } - try { - methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); - methodClassMap.put(methodClassName, methodClass); - } catch (ClassNotFoundException e) { - methodClassMap.put(methodClassName, clazz); - } - return methodClass; - } - - private void validate(Set> violations, Object arg, Class... groups) { - if (arg != null && !ReflectUtils.isPrimitives(arg.getClass())) { - if (arg instanceof Object[]) { - for (Object item : (Object[]) arg) { - validate(violations, item, groups); - } - } else if (arg instanceof Collection) { - for (Object item : (Collection) arg) { - validate(violations, item, groups); - } - } else if (arg instanceof Map) { - for (Map.Entry entry : ((Map) arg).entrySet()) { - validate(violations, entry.getKey(), groups); - validate(violations, entry.getValue(), groups); - } - } else { - violations.addAll(validator.validate(arg, groups)); - } - } - } - -} +/* + * 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.apache.dubbo.validation.support.jvalidation; + +import org.apache.dubbo.common.URL; +import org.apache.dubbo.common.bytecode.ClassGenerator; +import org.apache.dubbo.common.logger.Logger; +import org.apache.dubbo.common.logger.LoggerFactory; +import org.apache.dubbo.common.utils.ReflectUtils; +import org.apache.dubbo.validation.MethodValidated; +import org.apache.dubbo.validation.Validator; + +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtField; +import javassist.CtNewConstructor; +import javassist.Modifier; +import javassist.NotFoundException; +import javassist.bytecode.AnnotationsAttribute; +import javassist.bytecode.ClassFile; +import javassist.bytecode.ConstPool; +import javassist.bytecode.annotation.ArrayMemberValue; +import javassist.bytecode.annotation.BooleanMemberValue; +import javassist.bytecode.annotation.ByteMemberValue; +import javassist.bytecode.annotation.CharMemberValue; +import javassist.bytecode.annotation.ClassMemberValue; +import javassist.bytecode.annotation.DoubleMemberValue; +import javassist.bytecode.annotation.EnumMemberValue; +import javassist.bytecode.annotation.FloatMemberValue; +import javassist.bytecode.annotation.IntegerMemberValue; +import javassist.bytecode.annotation.LongMemberValue; +import javassist.bytecode.annotation.MemberValue; +import javassist.bytecode.annotation.ShortMemberValue; +import javassist.bytecode.annotation.StringMemberValue; + +import javax.validation.Constraint; +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import javax.validation.Validation; +import javax.validation.ValidatorFactory; +import javax.validation.groups.Default; +import java.lang.annotation.Annotation; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Implementation of JValidation. JValidation is invoked if configuration validation attribute value is 'jvalidation'. + *
    + *     e.g. <dubbo:method name="save" validation="jvalidation" />
    + * 
    + */ +public class JValidator implements Validator { + + private static final Logger logger = LoggerFactory.getLogger(JValidator.class); + + private final Class clazz; + + private final Map methodClassMap; + + private final javax.validation.Validator validator; + + @SuppressWarnings({"unchecked", "rawtypes"}) + public JValidator(URL url) { + this.clazz = ReflectUtils.forName(url.getServiceInterface()); + String jvalidation = url.getParameter("jvalidation"); + ValidatorFactory factory; + if (jvalidation != null && jvalidation.length() > 0) { + factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory(); + } else { + factory = Validation.buildDefaultValidatorFactory(); + } + this.validator = factory.getValidator(); + this.methodClassMap = new ConcurrentHashMap<>(); + } + + private static Object getMethodParameterBean(Class clazz, Method method, Object[] args) { + if (!hasConstraintParameter(method)) { + return null; + } + try { + String parameterClassName = generateMethodParameterClassName(clazz, method); + Class parameterClass; + try { + parameterClass = Class.forName(parameterClassName, true, clazz.getClassLoader()); + } catch (ClassNotFoundException e) { + parameterClass = generateMethodParameterClass(clazz, method, parameterClassName); + } + Object parameterBean = parameterClass.newInstance(); + for (int i = 0; i < args.length; i++) { + Field field = parameterClass.getField(method.getName() + "Argument" + i); + field.set(parameterBean, args[i]); + } + return parameterBean; + } catch (Throwable e) { + logger.warn(e.getMessage(), e); + return null; + } + } + + /** + * try to generate methodParameterClass. + * + * @param clazz interface class + * @param method invoke method + * @param parameterClassName generated parameterClassName + * @return Class generated methodParameterClass + * @throws Exception + */ + private static Class generateMethodParameterClass(Class clazz, Method method, String parameterClassName) + throws Exception { + ClassPool pool = ClassGenerator.getClassPool(clazz.getClassLoader()); + synchronized (parameterClassName.intern()) { + CtClass ctClass = null; + try { + ctClass = pool.getCtClass(parameterClassName); + } catch (NotFoundException ignore) { + } + + if (null == ctClass) { + ctClass = pool.makeClass(parameterClassName); + ClassFile classFile = ctClass.getClassFile(); + classFile.setVersionToJava5(); + ctClass.addConstructor(CtNewConstructor.defaultConstructor(pool.getCtClass(parameterClassName))); + // parameter fields + Class[] parameterTypes = method.getParameterTypes(); + Annotation[][] parameterAnnotations = method.getParameterAnnotations(); + for (int i = 0; i < parameterTypes.length; i++) { + Class type = parameterTypes[i]; + Annotation[] annotations = parameterAnnotations[i]; + AnnotationsAttribute attribute = new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag); + for (Annotation annotation : annotations) { + if (annotation.annotationType().isAnnotationPresent(Constraint.class)) { + javassist.bytecode.annotation.Annotation ja = new javassist.bytecode.annotation.Annotation( + classFile.getConstPool(), pool.getCtClass(annotation.annotationType().getName())); + Method[] members = annotation.annotationType().getMethods(); + for (Method member : members) { + if (Modifier.isPublic(member.getModifiers()) + && member.getParameterTypes().length == 0 + && member.getDeclaringClass() == annotation.annotationType()) { + Object value = member.invoke(annotation); + if (null != value) { + MemberValue memberValue = createMemberValue( + classFile.getConstPool(), pool.get(member.getReturnType().getName()), value); + ja.addMemberValue(member.getName(), memberValue); + } + } + } + attribute.addAnnotation(ja); + } + } + String fieldName = method.getName() + "Argument" + i; + CtField ctField = CtField.make("public " + type.getCanonicalName() + " " + fieldName + ";", pool.getCtClass(parameterClassName)); + ctField.getFieldInfo().addAttribute(attribute); + ctClass.addField(ctField); + } + return ctClass.toClass(clazz.getClassLoader(), null); + } else { + return Class.forName(parameterClassName, true, clazz.getClassLoader()); + } + } + } + + private static String generateMethodParameterClassName(Class clazz, Method method) { + StringBuilder builder = new StringBuilder().append(clazz.getName()) + .append("_") + .append(toUpperMethoName(method.getName())) + .append("Parameter"); + + Class[] parameterTypes = method.getParameterTypes(); + for (Class parameterType : parameterTypes) { + builder.append("_").append(parameterType.getName()); + } + + return builder.toString(); + } + + private static boolean hasConstraintParameter(Method method) { + Annotation[][] parameterAnnotations = method.getParameterAnnotations(); + if (parameterAnnotations != null && parameterAnnotations.length > 0) { + for (Annotation[] annotations : parameterAnnotations) { + for (Annotation annotation : annotations) { + if (annotation.annotationType().isAnnotationPresent(Constraint.class)) { + return true; + } + } + } + } + return false; + } + + private static String toUpperMethoName(String methodName) { + return methodName.substring(0, 1).toUpperCase() + methodName.substring(1); + } + + // Copy from javassist.bytecode.annotation.Annotation.createMemberValue(ConstPool, CtClass); + private static MemberValue createMemberValue(ConstPool cp, CtClass type, Object value) throws NotFoundException { + MemberValue memberValue = javassist.bytecode.annotation.Annotation.createMemberValue(cp, type); + if (memberValue instanceof BooleanMemberValue) { + ((BooleanMemberValue) memberValue).setValue((Boolean) value); + } else if (memberValue instanceof ByteMemberValue) { + ((ByteMemberValue) memberValue).setValue((Byte) value); + } else if (memberValue instanceof CharMemberValue) { + ((CharMemberValue) memberValue).setValue((Character) value); + } else if (memberValue instanceof ShortMemberValue) { + ((ShortMemberValue) memberValue).setValue((Short) value); + } else if (memberValue instanceof IntegerMemberValue) { + ((IntegerMemberValue) memberValue).setValue((Integer) value); + } else if (memberValue instanceof LongMemberValue) { + ((LongMemberValue) memberValue).setValue((Long) value); + } else if (memberValue instanceof FloatMemberValue) { + ((FloatMemberValue) memberValue).setValue((Float) value); + } else if (memberValue instanceof DoubleMemberValue) { + ((DoubleMemberValue) memberValue).setValue((Double) value); + } else if (memberValue instanceof ClassMemberValue) { + ((ClassMemberValue) memberValue).setValue(((Class) value).getName()); + } else if (memberValue instanceof StringMemberValue) { + ((StringMemberValue) memberValue).setValue((String) value); + } else if (memberValue instanceof EnumMemberValue) { + ((EnumMemberValue) memberValue).setValue(((Enum) value).name()); + } + /* else if (memberValue instanceof AnnotationMemberValue) */ + else if (memberValue instanceof ArrayMemberValue) { + CtClass arrayType = type.getComponentType(); + int len = Array.getLength(value); + MemberValue[] members = new MemberValue[len]; + for (int i = 0; i < len; i++) { + members[i] = createMemberValue(cp, arrayType, Array.get(value, i)); + } + ((ArrayMemberValue) memberValue).setValue(members); + } + return memberValue; + } + + @Override + public void validate(String methodName, Class[] parameterTypes, Object[] arguments) throws Exception { + List> groups = new ArrayList<>(); + Class methodClass = methodClass(methodName); + if (methodClass != null) { + groups.add(methodClass); + } + Set> violations = new HashSet<>(); + Method method = clazz.getMethod(methodName, parameterTypes); + Class[] methodClasses; + if (method.isAnnotationPresent(MethodValidated.class)){ + methodClasses = method.getAnnotation(MethodValidated.class).value(); + groups.addAll(Arrays.asList(methodClasses)); + } + // add into default group + groups.add(0, Default.class); + groups.add(1, clazz); + + // convert list to array + Class[] classgroups = groups.toArray(new Class[groups.size()]); + + Object parameterBean = getMethodParameterBean(clazz, method, arguments); + if (parameterBean != null) { + violations.addAll(validator.validate(parameterBean, classgroups )); + } + + for (Object arg : arguments) { + validate(violations, arg, classgroups); + } + + if (!violations.isEmpty()) { + logger.error("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations); + throw new ConstraintViolationException("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: " + violations, violations); + } + } + + private Class methodClass(String methodName) { + Class methodClass = null; + String methodClassName = clazz.getName() + "$" + toUpperMethoName(methodName); + Class cached = methodClassMap.get(methodClassName); + if (cached != null) { + return cached == clazz ? null : cached; + } + try { + methodClass = Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader()); + methodClassMap.put(methodClassName, methodClass); + } catch (ClassNotFoundException e) { + methodClassMap.put(methodClassName, clazz); + } + return methodClass; + } + + private void validate(Set> violations, Object arg, Class... groups) { + if (arg != null && !ReflectUtils.isPrimitives(arg.getClass())) { + if (arg instanceof Object[]) { + for (Object item : (Object[]) arg) { + validate(violations, item, groups); + } + } else if (arg instanceof Collection) { + for (Object item : (Collection) arg) { + validate(violations, item, groups); + } + } else if (arg instanceof Map) { + for (Map.Entry entry : ((Map) arg).entrySet()) { + validate(violations, entry.getKey(), groups); + validate(violations, entry.getValue(), groups); + } + } else { + violations.addAll(validator.validate(arg, groups)); + } + } + } + +} diff --git a/dubbo-metadata/dubbo-metadata-report-consul/pom.xml b/dubbo-metadata/dubbo-metadata-report-consul/pom.xml deleted file mode 100644 index 8a01b72d49..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-consul/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-metadata-report-consul - - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-configcenter-consul - ${project.parent.version} - - - com.ecwid.consul - consul-api - - - - diff --git a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java deleted file mode 100644 index e6b7054261..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReport.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * 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.apache.dubbo.metadata.store.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; -import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; -import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; -import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReport; -import org.apache.dubbo.rpc.RpcException; - -import com.ecwid.consul.v1.ConsulClient; -import com.ecwid.consul.v1.Response; -import com.ecwid.consul.v1.kv.model.GetValue; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * metadata report impl for consul - * - * @deprecated 2.7.8 This class will be removed in the future, {@link ConfigCenterBasedMetadataReport} as a substitute. - */ -@Deprecated -public class ConsulMetadataReport extends AbstractMetadataReport { - private static final Logger logger = LoggerFactory.getLogger(ConsulMetadataReport.class); - private static final int DEFAULT_PORT = 8500; - - private ConsulClient client; - - public ConsulMetadataReport(URL url) { - super(url); - - String host = url.getHost(); - int port = url.getPort() != 0 ? url.getPort() : DEFAULT_PORT; - client = new ConsulClient(host, port); - } - - @Override - protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { - this.storeMetadata(providerMetadataIdentifier, serviceDefinitions); - } - - @Override - protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) { - this.storeMetadata(consumerMetadataIdentifier, value); - } - - @Override - protected void doSaveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier, URL url) { - this.storeMetadata(serviceMetadataIdentifier, URL.encode(url.toFullString())); - } - - @Override - protected void doRemoveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier) { - this.deleteMetadata(serviceMetadataIdentifier); - } - - @Override - protected List doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { - //todo encode and decode - String content = getMetadata(metadataIdentifier); - if (StringUtils.isEmpty(content)) { - return Collections.emptyList(); - } - return new ArrayList(Arrays.asList(URL.decode(content))); - } - - @Override - protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr) { - this.storeMetadata(subscriberMetadataIdentifier, urlListStr); - } - - @Override - protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { - return getMetadata(subscriberMetadataIdentifier); - } - - private void storeMetadata(BaseMetadataIdentifier identifier, String v) { - try { - client.setKVValue(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), v); - } catch (Throwable t) { - logger.error("Failed to put " + identifier + " to consul " + v + ", cause: " + t.getMessage(), t); - throw new RpcException("Failed to put " + identifier + " to consul " + v + ", cause: " + t.getMessage(), t); - } - } - - private void deleteMetadata(BaseMetadataIdentifier identifier) { - try { - client.deleteKVValue(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); - } catch (Throwable t) { - logger.error("Failed to delete " + identifier + " from consul , cause: " + t.getMessage(), t); - throw new RpcException("Failed to delete " + identifier + " from consul , cause: " + t.getMessage(), t); - } - } - - private String getMetadata(BaseMetadataIdentifier identifier) { - try { - Response value = client.getKVValue(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY)); - //FIXME CHECK - if (value != null && value.getValue() != null) { - //todo check decode value and value diff - return value.getValue().getValue(); - } - return null; - } catch (Throwable t) { - logger.error("Failed to get " + identifier + " from consul , cause: " + t.getMessage(), t); - throw new RpcException("Failed to get " + identifier + " from consul , cause: " + t.getMessage(), t); - } - } - - @Override - public String getServiceDefinition(MetadataIdentifier metadataIdentifier) { - return getMetadata(metadataIdentifier); - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java deleted file mode 100644 index 7f5f1901e7..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-consul/src/main/java/org/apache/dubbo/metadata/store/consul/ConsulMetadataReportFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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.apache.dubbo.metadata.store.consul; - -import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; -import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReportFactory; - -/** - * metadata report factory impl for consul - */ -public class ConsulMetadataReportFactory extends ConfigCenterBasedMetadataReportFactory { - - public ConsulMetadataReportFactory() { - super(KeyTypeEnum.UNIQUE_KEY); - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory deleted file mode 100644 index 1f27535d44..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory +++ /dev/null @@ -1 +0,0 @@ -consul=org.apache.dubbo.metadata.store.consul.ConsulMetadataReportFactory diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/pom.xml b/dubbo-metadata/dubbo-metadata-report-etcd/pom.xml deleted file mode 100644 index 747dc2a2e0..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-metadata-report-etcd - - - true - - - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-etcd3 - ${project.parent.version} - - - io.etcd - jetcd-launcher - test - - - org.testcontainers - testcontainers - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipIntegrationTests} - - - - - diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java deleted file mode 100644 index a80c6e83dd..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReport.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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. - */ - -/* - * 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.apache.dubbo.metadata.store.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; -import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; -import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; -import org.apache.dubbo.remoting.etcd.jetcd.JEtcdClient; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; - -/** - * Report Metadata to Etcd - */ -public class EtcdMetadataReport extends AbstractMetadataReport { - - private final static Logger logger = LoggerFactory.getLogger(EtcdMetadataReport.class); - - private final String root; - - /** - * The etcd client - */ - private final JEtcdClient etcdClient; - - public EtcdMetadataReport(URL url) { - super(url); - if (url.isAnyHost()) { - throw new IllegalStateException("registry address == null"); - } - String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); - if (!group.startsWith(PATH_SEPARATOR)) { - group = PATH_SEPARATOR + group; - } - this.root = group; - etcdClient = new JEtcdClient(url); - } - - @Override - protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { - storeMetadata(providerMetadataIdentifier, serviceDefinitions); - } - - @Override - protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) { - storeMetadata(consumerMetadataIdentifier, value); - } - - @Override - protected void doSaveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier, URL url) { - String key = getNodeKey(serviceMetadataIdentifier); - if (!etcdClient.put(key, URL.encode(url.toFullString()))) { - logger.error("Failed to put " + serviceMetadataIdentifier + " to etcd, value: " + url); - } - } - - @Override - protected void doRemoveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier) { - etcdClient.delete(getNodeKey(serviceMetadataIdentifier)); - } - - @Override - protected List doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { - String content = etcdClient.getKVValue(getNodeKey(metadataIdentifier)); - if (StringUtils.isEmpty(content)) { - return Collections.emptyList(); - } - return new ArrayList(Arrays.asList(URL.decode(content))); - } - - @Override - protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr) { - String key = getNodeKey(subscriberMetadataIdentifier); - if (!etcdClient.put(key, urlListStr)) { - logger.error("Failed to put " + subscriberMetadataIdentifier + " to etcd, value: " + urlListStr); - } - } - - @Override - protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { - return etcdClient.getKVValue(getNodeKey(subscriberMetadataIdentifier)); - } - - @Override - public String getServiceDefinition(MetadataIdentifier metadataIdentifier) { - return etcdClient.getKVValue(getNodeKey(metadataIdentifier)); - } - - private void storeMetadata(MetadataIdentifier identifier, String v) { - String key = getNodeKey(identifier); - if (!etcdClient.put(key, v)) { - logger.error("Failed to put " + identifier + " to etcd, value: " + v); - } - } - - String getNodeKey(BaseMetadataIdentifier identifier) { - return toRootDir() + identifier.getUniqueKey(KeyTypeEnum.PATH); - } - - String toRootDir() { - if (root.equals(PATH_SEPARATOR)) { - return root; - } - return root + PATH_SEPARATOR; - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java deleted file mode 100644 index 3bb9e92d3e..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportFactory.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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. - */ - -/* - * 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.apache.dubbo.metadata.store.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.metadata.report.MetadataReport; -import org.apache.dubbo.metadata.report.support.AbstractMetadataReportFactory; - -/** - * MetadataReportFactory to create an Etcd based {@link MetadataReport}. - */ -public class EtcdMetadataReportFactory extends AbstractMetadataReportFactory { - - @Override - public MetadataReport createMetadataReport(URL url) { - return new EtcdMetadataReport(url); - } - -} diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory deleted file mode 100644 index 9a3c98c82a..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory +++ /dev/null @@ -1 +0,0 @@ -etcd=org.apache.dubbo.metadata.store.etcd.EtcdMetadataReportFactory diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java b/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java deleted file mode 100644 index 1de21ce565..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadata4TstService.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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.apache.dubbo.metadata.store.etcd; - -/** - * Test interface for Etcd metadata report - */ -public interface EtcdMetadata4TstService { - - int getCounter(); - - void printResult(String var); -} diff --git a/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java b/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java deleted file mode 100644 index 2d2efd5a0e..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-etcd/src/test/java/org/apache/dubbo/metadata/store/etcd/EtcdMetadataReportTest.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * 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.apache.dubbo.metadata.store.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.metadata.definition.ServiceDefinitionBuilder; -import org.apache.dubbo.metadata.definition.model.FullServiceDefinition; -import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; - -import com.google.gson.Gson; -import io.etcd.jetcd.ByteSequence; -import io.etcd.jetcd.Client; -import io.etcd.jetcd.kv.GetResponse; -import io.etcd.jetcd.launcher.EtcdCluster; -import io.etcd.jetcd.launcher.EtcdClusterFactory; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; - -import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; -import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE; - -/** - * Unit test for etcd metadata report - */ -public class EtcdMetadataReportTest { - - private static final String TEST_SERVICE = "org.apache.dubbo.metadata.store.etcd.EtcdMetadata4TstService"; - - private EtcdCluster etcdCluster = EtcdClusterFactory.buildCluster(getClass().getSimpleName(), 1, false, false); - private Client etcdClientForTest; - private EtcdMetadataReport etcdMetadataReport; - private URL registryUrl; - private EtcdMetadataReportFactory etcdMetadataReportFactory; - - @BeforeEach - public void setUp() { - etcdCluster.start(); - etcdClientForTest = Client.builder().endpoints(etcdCluster.getClientEndpoints()).build(); - List clientEndPoints = etcdCluster.getClientEndpoints(); - this.registryUrl = URL.valueOf("etcd://" + clientEndPoints.get(0).getHost() + ":" + clientEndPoints.get(0).getPort()); - etcdMetadataReportFactory = new EtcdMetadataReportFactory(); - this.etcdMetadataReport = (EtcdMetadataReport) etcdMetadataReportFactory.createMetadataReport(registryUrl); - } - - @AfterEach - public void tearDown() throws Exception { - etcdCluster.close(); - } - - @Test - public void testStoreProvider() throws Exception { - String version = "1.0.0"; - String group = null; - String application = "etcd-metdata-report-test"; - - String r = etcdMetadataReport.getServiceDefinition(new MetadataIdentifier(TEST_SERVICE, version, group, "provider", application)); - Assertions.assertNull(r); - MetadataIdentifier providerIdentifier = - storeProvider(etcdMetadataReport, TEST_SERVICE, version, group, application); - - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(providerIdentifier), StandardCharsets.UTF_8)); - String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); - Assertions.assertNotNull(fileContent); - - Gson gson = new Gson(); - FullServiceDefinition fullServiceDefinition = gson.fromJson(fileContent, FullServiceDefinition.class); - Assertions.assertEquals(fullServiceDefinition.getParameters().get("paramTest"), "etcdTest"); - - r = etcdMetadataReport.getServiceDefinition(new MetadataIdentifier(TEST_SERVICE, version, group, "provider", application)); - Assertions.assertNotNull(r); - } - - @Test - public void testStoreConsumer() throws Exception { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - MetadataIdentifier consumerIdentifier = storeConsumer(etcdMetadataReport, TEST_SERVICE, version, group, application); - - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(consumerIdentifier), StandardCharsets.UTF_8)); - String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); - Assertions.assertNotNull(fileContent); - Assertions.assertEquals(fileContent, "{\"paramConsumerTest\":\"etcdConsumer\"}"); - } - - @Test - public void testDoSaveMetadata() throws ExecutionException, InterruptedException { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - String revision = "90980"; - String protocol = "xxx"; - URL url = generateURL(TEST_SERVICE, version, group, application); - ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(TEST_SERVICE, version, - group, "provider", revision, protocol); - etcdMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); - - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(serviceMetadataIdentifier), StandardCharsets.UTF_8)); - String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); - Assertions.assertNotNull(fileContent); - - Assertions.assertEquals(fileContent, URL.encode(url.toFullString())); - } - - @Test - public void testDoRemoveMetadata() throws ExecutionException, InterruptedException { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - String revision = "90980"; - String protocol = "xxx"; - URL url = generateURL(TEST_SERVICE, version, group, application); - ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(TEST_SERVICE, version, - group, "provider", revision, protocol); - etcdMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(serviceMetadataIdentifier), StandardCharsets.UTF_8)); - String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); - Assertions.assertNotNull(fileContent); - - - etcdMetadataReport.doRemoveMetadata(serviceMetadataIdentifier); - - response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(serviceMetadataIdentifier), StandardCharsets.UTF_8)); - Assertions.assertTrue(response.get().getKvs().isEmpty()); - } - - @Test - public void testDoGetExportedURLs() throws ExecutionException, InterruptedException { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - String revision = "90980"; - String protocol = "xxx"; - URL url = generateURL(TEST_SERVICE, version, group, application); - ServiceMetadataIdentifier serviceMetadataIdentifier = new ServiceMetadataIdentifier(TEST_SERVICE, version, - group, "provider", revision, protocol); - etcdMetadataReport.doSaveMetadata(serviceMetadataIdentifier, url); - - List r = etcdMetadataReport.doGetExportedURLs(serviceMetadataIdentifier); - Assertions.assertTrue(r.size() == 1); - - String fileContent = r.get(0); - Assertions.assertNotNull(fileContent); - - Assertions.assertEquals(fileContent, url.toFullString()); - } - - @Test - public void testDoSaveSubscriberData() throws ExecutionException, InterruptedException { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - String revision = "90980"; - String protocol = "xxx"; - URL url = generateURL(TEST_SERVICE, version, group, application); - SubscriberMetadataIdentifier subscriberMetadataIdentifier = new SubscriberMetadataIdentifier(application, revision); - Gson gson = new Gson(); - String r = gson.toJson(Arrays.asList(url)); - etcdMetadataReport.doSaveSubscriberData(subscriberMetadataIdentifier, r); - - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(subscriberMetadataIdentifier), StandardCharsets.UTF_8)); - String fileContent = response.get().getKvs().get(0).getValue().toString(StandardCharsets.UTF_8); - Assertions.assertNotNull(fileContent); - - Assertions.assertEquals(fileContent, r); - } - - @Test - public void testDoGetSubscribedURLs() throws ExecutionException, InterruptedException { - String version = "1.0.0"; - String group = null; - String application = "etc-metadata-report-consumer-test"; - String revision = "90980"; - String protocol = "xxx"; - URL url = generateURL(TEST_SERVICE, version, group, application); - SubscriberMetadataIdentifier subscriberMetadataIdentifier = new SubscriberMetadataIdentifier(application, revision); - Gson gson = new Gson(); - String r = gson.toJson(Arrays.asList(url)); - etcdMetadataReport.doSaveSubscriberData(subscriberMetadataIdentifier, r); - - CompletableFuture response = etcdClientForTest.getKVClient().get(ByteSequence.from( - etcdMetadataReport.getNodeKey(subscriberMetadataIdentifier), StandardCharsets.UTF_8)); - String fileContent = etcdMetadataReport.doGetSubscribedURLs(subscriberMetadataIdentifier); - Assertions.assertNotNull(fileContent); - - Assertions.assertEquals(fileContent, r); - } - - private MetadataIdentifier storeProvider(EtcdMetadataReport etcdMetadataReport, String interfaceName, String version, - String group, String application) - throws ClassNotFoundException, InterruptedException { - URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":4444/" + interfaceName + - "?paramTest=etcdTest&version=" + version + "&application=" - + application + (group == null ? "" : "&group=" + group)); - - MetadataIdentifier providerMetadataIdentifier = - new MetadataIdentifier(interfaceName, version, group, PROVIDER_SIDE, application); - Class interfaceClass = Class.forName(interfaceName); - FullServiceDefinition fullServiceDefinition = - ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, url.getParameters()); - - etcdMetadataReport.storeProviderMetadata(providerMetadataIdentifier, fullServiceDefinition); - Thread.sleep(1000); - return providerMetadataIdentifier; - } - - private URL generateURL(String interfaceName, String version, String group, String application) { - URL url = URL.valueOf("xxx://" + NetUtils.getLocalAddress().getHostName() + ":8989/" + interfaceName + - "?paramTest=etcdTest&version=" + version + "&application=" - + application + (group == null ? "" : "&group=" + group)); - return url; - } - - private MetadataIdentifier storeConsumer(EtcdMetadataReport etcdMetadataReport, String interfaceName, - String version, String group, String application) throws InterruptedException { - - MetadataIdentifier consumerIdentifier = new MetadataIdentifier(interfaceName, version, group, CONSUMER_SIDE, application); - Map tmp = new HashMap<>(); - tmp.put("paramConsumerTest", "etcdConsumer"); - etcdMetadataReport.storeConsumerMetadata(consumerIdentifier, tmp); - Thread.sleep(1000); - return consumerIdentifier; - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml b/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml deleted file mode 100644 index 03211e02ec..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-nacos/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - org.apache.dubbo - dubbo-metadata - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-metadata-report-nacos - - - - org.apache.dubbo - dubbo-metadata-api - ${project.parent.version} - - - - org.apache.dubbo - dubbo-configcenter-nacos - ${project.parent.version} - - - - diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java deleted file mode 100644 index 5c413d8fb0..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReport.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * 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.apache.dubbo.metadata.store.nacos; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.configcenter.DynamicConfiguration; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.metadata.report.identifier.BaseMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; -import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.ServiceMetadataIdentifier; -import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier; -import org.apache.dubbo.metadata.report.support.AbstractMetadataReport; -import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReport; -import org.apache.dubbo.rpc.RpcException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static java.util.concurrent.TimeUnit.SECONDS; - -/** - * metadata report impl for nacos - * - * @deprecated 2.7.8 This class will be removed in the future, {@link ConfigCenterBasedMetadataReport} as a substitute. - */ -@Deprecated -public class NacosMetadataReport extends AbstractMetadataReport { - - private static final Logger logger = LoggerFactory.getLogger(NacosMetadataReport.class); - - private final DynamicConfiguration dynamicConfiguration; - - /** - * The group used to store metadata in Nacos - */ - private String group; - - public NacosMetadataReport(URL url, DynamicConfiguration dynamicConfiguration) { - super(url); - this.dynamicConfiguration = dynamicConfiguration; - } - - @Override - protected void doStoreProviderMetadata(MetadataIdentifier providerMetadataIdentifier, String serviceDefinitions) { - this.storeMetadata(providerMetadataIdentifier, serviceDefinitions); - } - - @Override - protected void doStoreConsumerMetadata(MetadataIdentifier consumerMetadataIdentifier, String value) { - this.storeMetadata(consumerMetadataIdentifier, value); - } - - @Override - protected void doSaveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier, URL url) { - storeMetadata(serviceMetadataIdentifier, URL.encode(url.toFullString())); - } - - @Override - protected void doRemoveMetadata(ServiceMetadataIdentifier serviceMetadataIdentifier) { - deleteMetadata(serviceMetadataIdentifier); - } - - @Override - protected List doGetExportedURLs(ServiceMetadataIdentifier metadataIdentifier) { - String content = getConfig(metadataIdentifier); - if (StringUtils.isEmpty(content)) { - return Collections.emptyList(); - } - return new ArrayList(Arrays.asList(URL.decode(content))); - } - - @Override - protected void doSaveSubscriberData(SubscriberMetadataIdentifier subscriberMetadataIdentifier, String urlListStr) { - storeMetadata(subscriberMetadataIdentifier, urlListStr); - } - - @Override - protected String doGetSubscribedURLs(SubscriberMetadataIdentifier subscriberMetadataIdentifier) { - return getConfig(subscriberMetadataIdentifier); - } - - @Override - public String getServiceDefinition(MetadataIdentifier metadataIdentifier) { - return getConfig(metadataIdentifier); - } - - @Override - public boolean saveExportedURLs(String serviceName, String exportedServicesRevision, String exportedURLsContent) { - return dynamicConfiguration.publishConfig(serviceName, exportedServicesRevision, exportedURLsContent); - } - - @Override - public String getExportedURLsContent(String serviceName, String exportedServicesRevision) { - return dynamicConfiguration.getConfig(serviceName, exportedServicesRevision, SECONDS.toMillis(3)); - } - - private void storeMetadata(BaseMetadataIdentifier identifier, String value) { - try { - boolean publishResult = dynamicConfiguration.publishConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, value); - if (!publishResult) { - throw new RuntimeException("publish nacos metadata failed"); - } - } catch (Throwable t) { - logger.error("Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t); - throw new RpcException("Failed to put " + identifier + " to nacos " + value + ", cause: " + t.getMessage(), t); - } - } - - private void deleteMetadata(BaseMetadataIdentifier identifier) { - try { - boolean publishResult = dynamicConfiguration.removeConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group); - if (!publishResult) { - throw new RuntimeException("remove nacos metadata failed"); - } - } catch (Throwable t) { - logger.error("Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), t); - throw new RpcException("Failed to remove " + identifier + " from nacos , cause: " + t.getMessage(), t); - } - } - - private String getConfig(BaseMetadataIdentifier identifier) { - try { - return dynamicConfiguration.getConfig(identifier.getUniqueKey(KeyTypeEnum.UNIQUE_KEY), group, 300); - } catch (Throwable t) { - logger.error("Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t); - throw new RpcException("Failed to get " + identifier + " from nacos , cause: " + t.getMessage(), t); - } - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java deleted file mode 100644 index 8c8d5a2efa..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/java/org/apache/dubbo/metadata/store/nacos/NacosMetadataReportFactory.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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.apache.dubbo.metadata.store.nacos; - -import org.apache.dubbo.metadata.report.identifier.KeyTypeEnum; -import org.apache.dubbo.metadata.report.support.ConfigCenterBasedMetadataReportFactory; - -/** - * metadata report factory impl for nacos - */ -public class NacosMetadataReportFactory extends ConfigCenterBasedMetadataReportFactory { - - public NacosMetadataReportFactory() { - super(KeyTypeEnum.UNIQUE_KEY); - } -} diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory b/dubbo-metadata/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory deleted file mode 100644 index de3b50a4b4..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.metadata.report.MetadataReportFactory +++ /dev/null @@ -1 +0,0 @@ -nacos=org.apache.dubbo.metadata.store.nacos.NacosMetadataReportFactory diff --git a/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java b/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java deleted file mode 100644 index e84efc529c..0000000000 --- a/dubbo-metadata/dubbo-metadata-report-nacos/src/test/java/org/apache/dubbo/metadata/store/nacos/NacosMetadata4TstService.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * 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.apache.dubbo.metadata.store.nacos; - -/** - * Test interface for Nacos metadata report - */ -public interface NacosMetadata4TstService { - - int getCounter(); - - void printResult(String var); -} diff --git a/dubbo-metadata/dubbo-metadata-report-redis/pom.xml b/dubbo-metadata/dubbo-metadata-report-redis/pom.xml index f42424bea5..70bd32d363 100644 --- a/dubbo-metadata/dubbo-metadata-report-redis/pom.xml +++ b/dubbo-metadata/dubbo-metadata-report-redis/pom.xml @@ -18,8 +18,7 @@ org.apache.dubbo dubbo-metadata - ${revision} - ../pom.xml + 2.7.7-SNAPSHOT 4.0.0 diff --git a/dubbo-metadata/pom.xml b/dubbo-metadata/pom.xml index a11277960b..9119e09488 100644 --- a/dubbo-metadata/pom.xml +++ b/dubbo-metadata/pom.xml @@ -29,13 +29,10 @@ pom dubbo-metadata-api - + dubbo-metadata-definition-protobuf + dubbo-metadata-processor dubbo-metadata-report-zookeeper - - - - - + dubbo-metadata-report-redis
    diff --git a/dubbo-registry/dubbo-registry-consul/pom.xml b/dubbo-registry/dubbo-registry-consul/pom.xml deleted file mode 100644 index e8f863e0e3..0000000000 --- a/dubbo-registry/dubbo-registry-consul/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - - dubbo-registry - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-registry-consul - - - true - - - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - - - com.ecwid.consul - consul-api - - - com.pszymczyk.consul - embedded-consul - test - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipIntegrationTests} - - - - - - diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/AbstractConsulRegistry.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/AbstractConsulRegistry.java deleted file mode 100644 index 8a5e6d7871..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/AbstractConsulRegistry.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.apache.dubbo.registry.consul; - -/** - * @author cvictory ON 2019-08-02 - */ -public class AbstractConsulRegistry { - - static final String SERVICE_TAG = "dubbo"; - static final String URL_META_KEY = "url"; - static final String WATCH_TIMEOUT = "consul-watch-timeout"; - static final String CHECK_PASS_INTERVAL = "consul-check-pass-interval"; - static final String DEREGISTER_AFTER = "consul-deregister-critical-service-after"; - - static final int DEFAULT_PORT = 8500; - // default watch timeout in millisecond - static final int DEFAULT_WATCH_TIMEOUT = 60 * 1000; - // default time-to-live in millisecond - static final long DEFAULT_CHECK_PASS_INTERVAL = 16000L; - // default deregister critical server after - static final String DEFAULT_DEREGISTER_TIME = "20s"; - - -} diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java deleted file mode 100644 index 990646ae6c..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistry.java +++ /dev/null @@ -1,380 +0,0 @@ -/* - * 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.apache.dubbo.registry.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.URLBuilder; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.UrlUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.support.FailbackRegistry; -import org.apache.dubbo.rpc.RpcException; - -import com.ecwid.consul.v1.ConsulClient; -import com.ecwid.consul.v1.QueryParams; -import com.ecwid.consul.v1.Response; -import com.ecwid.consul.v1.agent.model.NewService; -import com.ecwid.consul.v1.catalog.CatalogServicesRequest; -import com.ecwid.consul.v1.health.HealthServicesRequest; -import com.ecwid.consul.v1.health.model.HealthService; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import static java.util.concurrent.Executors.newCachedThreadPool; -import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; -import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; -import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.registry.Constants.PROVIDER_PROTOCOL; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.CHECK_PASS_INTERVAL; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_CHECK_PASS_INTERVAL; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_DEREGISTER_TIME; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_PORT; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_WATCH_TIMEOUT; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEREGISTER_AFTER; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.SERVICE_TAG; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.URL_META_KEY; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.WATCH_TIMEOUT; -import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; - -/** - * registry center implementation for consul - */ -public class ConsulRegistry extends FailbackRegistry { - private static final Logger logger = LoggerFactory.getLogger(ConsulRegistry.class); - - private ConsulClient client; - private long checkPassInterval; - private ExecutorService notifierExecutor = newCachedThreadPool( - new NamedThreadFactory("dubbo-consul-notifier", true)); - private ConcurrentMap notifiers = new ConcurrentHashMap<>(); - private ScheduledExecutorService ttlConsulCheckExecutor; - /** - * The ACL token - */ - private String token; - - - public ConsulRegistry(URL url) { - super(url); - token = url.getParameter(TOKEN_KEY, (String) null); - String host = url.getHost(); - int port = url.getPort() != 0 ? url.getPort() : DEFAULT_PORT; - client = new ConsulClient(host, port); - checkPassInterval = url.getParameter(CHECK_PASS_INTERVAL, DEFAULT_CHECK_PASS_INTERVAL); - ttlConsulCheckExecutor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("Ttl-Consul-Check-Executor", true)); - ttlConsulCheckExecutor.scheduleAtFixedRate(this::checkPass, checkPassInterval / 8, - checkPassInterval / 8, TimeUnit.MILLISECONDS); - } - - @Override - public void register(URL url) { - if (isConsumerSide(url)) { - return; - } - - super.register(url); - } - - @Override - public void doRegister(URL url) { - if (token == null) { - client.agentServiceRegister(buildService(url)); - } else { - client.agentServiceRegister(buildService(url), token); - } - } - - @Override - public void unregister(URL url) { - if (isConsumerSide(url)) { - return; - } - - super.unregister(url); - } - - @Override - public void doUnregister(URL url) { - if (token == null) { - client.agentServiceDeregister(buildId(url)); - } else { - client.agentServiceDeregister(buildId(url), token); - } - } - - @Override - public void subscribe(URL url, NotifyListener listener) { - if (isProviderSide(url)) { - return; - } - - super.subscribe(url, listener); - } - - @Override - public void doSubscribe(URL url, NotifyListener listener) { - Long index; - List urls; - if (ANY_VALUE.equals(url.getServiceInterface())) { - Response>> response = getAllServices(-1, buildWatchTimeout(url)); - index = response.getConsulIndex(); - List services = getHealthServices(response.getValue()); - urls = convert(services, url); - } else { - String service = url.getServiceInterface(); - Response> response = getHealthServices(service, -1, buildWatchTimeout(url)); - index = response.getConsulIndex(); - urls = convert(response.getValue(), url); - } - - notify(url, listener, urls); - ConsulNotifier notifier = notifiers.computeIfAbsent(url, k -> new ConsulNotifier(url, index)); - notifierExecutor.submit(notifier); - } - - @Override - public void unsubscribe(URL url, NotifyListener listener) { - if (isProviderSide(url)) { - return; - } - - super.unsubscribe(url, listener); - } - - @Override - public void doUnsubscribe(URL url, NotifyListener listener) { - ConsulNotifier notifier = notifiers.remove(url); - notifier.stop(); - } - - @Override - public List lookup(URL url) { - if (url == null) { - throw new IllegalArgumentException("lookup url == null"); - } - try { - String service = url.getServiceKey(); - Response> result = getHealthServices(service, -1, buildWatchTimeout(url)); - if (result == null || result.getValue() == null || result.getValue().isEmpty()) { - return new ArrayList<>(); - } else { - return convert(result.getValue(), url); - } - } catch (Throwable e) { - throw new RpcException("Failed to lookup " + url + " from consul " + getUrl() + ", cause: " + e.getMessage(), e); - } - } - - @Override - public boolean isAvailable() { - return client.getAgentSelf() != null; - } - - @Override - public void destroy() { - super.destroy(); - notifierExecutor.shutdown(); - ttlConsulCheckExecutor.shutdown(); - } - - private void checkPass() { - for (URL url : getRegistered()) { - String checkId = buildId(url); - try { - if (token == null) { - client.agentCheckPass("service:" + checkId); - } else { - client.agentCheckPass("service:" + checkId, null, token); - } - if (logger.isDebugEnabled()) { - logger.debug("check pass for url: " + url + " with check id: " + checkId); - } - } catch (Throwable t) { - logger.warn("fail to check pass for url: " + url + ", check id is: " + checkId, t); - } - } - } - - private Response> getHealthServices(String service, long index, int watchTimeout) { - HealthServicesRequest request = HealthServicesRequest.newBuilder() - .setTag(SERVICE_TAG) - .setQueryParams(new QueryParams(watchTimeout, index)) - .setPassing(true) - .setToken(token) - .build(); - return client.getHealthServices(service, request); - } - - private Response>> getAllServices(long index, int watchTimeout) { - CatalogServicesRequest request = CatalogServicesRequest.newBuilder() - .setQueryParams(new QueryParams(watchTimeout, index)) - .setToken(token) - .build(); - return client.getCatalogServices(request); - } - - private List getHealthServices(Map> services) { - return services.entrySet().stream() - .filter(s -> s.getValue().contains(SERVICE_TAG)) - .map(s -> getHealthServices(s.getKey(), -1, -1).getValue()) - .flatMap(Collection::stream) - .collect(Collectors.toList()); - } - - - private boolean isConsumerSide(URL url) { - return url.getProtocol().equals(CONSUMER_PROTOCOL); - } - - private boolean isProviderSide(URL url) { - return url.getProtocol().equals(PROVIDER_PROTOCOL); - } - - private List convert(List services, URL consumerURL) { - if (CollectionUtils.isEmpty(services)) { - return emptyURL(consumerURL); - } - return services.stream() - .map(HealthService::getService) - .filter(Objects::nonNull) - .map(HealthService.Service::getMeta) - .filter(m -> m != null && m.containsKey(URL_META_KEY)) - .map(m -> m.get(URL_META_KEY)) - .map(URL::valueOf) - .filter(url -> UrlUtils.isMatch(consumerURL, url)) - .collect(Collectors.toList()); - } - - private List emptyURL(URL consumerURL) { - // No Category Parameter - URL empty = URLBuilder.from(consumerURL) - .setProtocol(EMPTY_PROTOCOL) - .removeParameter(CATEGORY_KEY) - .build(); - List result = new ArrayList(); - result.add(empty); - return result; - } - - private NewService buildService(URL url) { - NewService service = new NewService(); - service.setAddress(url.getHost()); - service.setPort(url.getPort()); - service.setId(buildId(url)); - service.setName(url.getServiceInterface()); - service.setCheck(buildCheck(url)); - service.setTags(buildTags(url)); - service.setMeta(Collections.singletonMap(URL_META_KEY, url.toFullString())); - return service; - } - - private List buildTags(URL url) { - Map params = url.getParameters(); - List tags = params.entrySet().stream() - .map(k -> k.getKey() + "=" + k.getValue()) - .collect(Collectors.toList()); - tags.add(SERVICE_TAG); - return tags; - } - - private String buildId(URL url) { - // let's simply use url's hashcode to generate unique service id for now - return Integer.toHexString(url.hashCode()); - } - - private NewService.Check buildCheck(URL url) { - NewService.Check check = new NewService.Check(); - check.setTtl((checkPassInterval / 1000) + "s"); - check.setDeregisterCriticalServiceAfter(url.getParameter(DEREGISTER_AFTER, DEFAULT_DEREGISTER_TIME)); - return check; - } - - private int buildWatchTimeout(URL url) { - return url.getParameter(WATCH_TIMEOUT, DEFAULT_WATCH_TIMEOUT) / 1000; - } - - private class ConsulNotifier implements Runnable { - private URL url; - private long consulIndex; - private boolean running; - - ConsulNotifier(URL url, long consulIndex) { - this.url = url; - this.consulIndex = consulIndex; - this.running = true; - } - - @Override - public void run() { - while (this.running) { - if (ANY_VALUE.equals(url.getServiceInterface())) { - processServices(); - } else { - processService(); - } - } - } - - private void processService() { - String service = url.getServiceKey(); - Response> response = getHealthServices(service, consulIndex, buildWatchTimeout(url)); - Long currentIndex = response.getConsulIndex(); - if (currentIndex != null && currentIndex > consulIndex) { - consulIndex = currentIndex; - List services = response.getValue(); - List urls = convert(services, url); - for (NotifyListener listener : getSubscribed().get(url)) { - doNotify(url, listener, urls); - } - } - } - - private void processServices() { - Response>> response = getAllServices(consulIndex, buildWatchTimeout(url)); - Long currentIndex = response.getConsulIndex(); - if (currentIndex != null && currentIndex > consulIndex) { - consulIndex = currentIndex; - List services = getHealthServices(response.getValue()); - List urls = convert(services, url); - for (NotifyListener listener : getSubscribed().get(url)) { - doNotify(url, listener, urls); - } - } - } - - void stop() { - this.running = false; - } - } -} diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistryFactory.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistryFactory.java deleted file mode 100644 index c36f009c0d..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulRegistryFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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.apache.dubbo.registry.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.support.AbstractRegistryFactory; - -/** - * registry center factory implementation for consul - */ -public class ConsulRegistryFactory extends AbstractRegistryFactory { - @Override - protected Registry createRegistry(URL url) { - return new ConsulRegistry(url); - } -} diff --git a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulServiceDiscovery.java b/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulServiceDiscovery.java deleted file mode 100644 index 0c330aab9a..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/main/java/org/apache/dubbo/registry/consul/ConsulServiceDiscovery.java +++ /dev/null @@ -1,474 +0,0 @@ -/* - * 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.apache.dubbo.registry.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.event.EventListener; -import org.apache.dubbo.registry.client.DefaultServiceInstance; -import org.apache.dubbo.registry.client.ServiceDiscovery; -import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; -import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; - -import com.ecwid.consul.v1.ConsistencyMode; -import com.ecwid.consul.v1.ConsulClient; -import com.ecwid.consul.v1.QueryParams; -import com.ecwid.consul.v1.Response; -import com.ecwid.consul.v1.agent.model.NewService; -import com.ecwid.consul.v1.catalog.CatalogServicesRequest; -import com.ecwid.consul.v1.health.HealthServicesRequest; -import com.ecwid.consul.v1.health.model.HealthService; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import static java.util.concurrent.Executors.newCachedThreadPool; -import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR_CHAR; -import static org.apache.dubbo.common.constants.CommonConstants.SEMICOLON_SPLIT_PATTERN; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.CHECK_PASS_INTERVAL; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_CHECK_PASS_INTERVAL; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_DEREGISTER_TIME; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_PORT; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEFAULT_WATCH_TIMEOUT; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.DEREGISTER_AFTER; -import static org.apache.dubbo.registry.consul.AbstractConsulRegistry.WATCH_TIMEOUT; -import static org.apache.dubbo.registry.consul.ConsulParameter.ACL_TOKEN; -import static org.apache.dubbo.registry.consul.ConsulParameter.CONSISTENCY_MODE; -import static org.apache.dubbo.registry.consul.ConsulParameter.DEFAULT_ZONE_METADATA_NAME; -import static org.apache.dubbo.registry.consul.ConsulParameter.INSTANCE_GROUP; -import static org.apache.dubbo.registry.consul.ConsulParameter.INSTANCE_ZONE; -import static org.apache.dubbo.registry.consul.ConsulParameter.TAGS; - -/** - * 2019-07-31 - */ -public class ConsulServiceDiscovery implements ServiceDiscovery, EventListener { - - private static final Logger logger = LoggerFactory.getLogger(ConsulServiceDiscovery.class); - - private static final String QUERY_TAG = "consul_query_tag"; - private static final String REGISTER_TAG = "consul_register_tag"; - - private List registeringTags = new ArrayList<>(); - private String tag; - private ConsulClient client; - private ExecutorService notifierExecutor = newCachedThreadPool( - new NamedThreadFactory("dubbo-service-discovery-consul-notifier", true)); - private ConsulNotifier notifier; - private TtlScheduler ttlScheduler; - private long checkPassInterval; - private URL url; - - private String aclToken; - - private List tags; - - private ConsistencyMode consistencyMode; - - private String defaultZoneMetadataName; - - /** - * Service instance zone. - */ - private String instanceZone; - - /** - * Service instance group. - */ - private String instanceGroup; - - - @Override - public void onEvent(ServiceInstancesChangedEvent event) { - - } - - @Override - public void initialize(URL registryURL) throws Exception { - this.url = registryURL; - String host = url.getHost(); - int port = url.getPort() != 0 ? url.getPort() : DEFAULT_PORT; - checkPassInterval = url.getParameter(CHECK_PASS_INTERVAL, DEFAULT_CHECK_PASS_INTERVAL); - client = new ConsulClient(host, port); - ttlScheduler = new TtlScheduler(checkPassInterval, client); - this.tag = registryURL.getParameter(QUERY_TAG); - this.registeringTags.addAll(getRegisteringTags(url)); - this.aclToken = ACL_TOKEN.getValue(registryURL); - this.tags = getTags(registryURL); - this.consistencyMode = getConsistencyMode(registryURL); - this.defaultZoneMetadataName = DEFAULT_ZONE_METADATA_NAME.getValue(registryURL); - this.instanceZone = INSTANCE_ZONE.getValue(registryURL); - this.instanceGroup = INSTANCE_GROUP.getValue(registryURL); - } - - /** - * Get the {@link ConsistencyMode} - * - * @param registryURL the {@link URL} of registry - * @return non-null, {@link ConsistencyMode#DEFAULT} as default - * @sine 2.7.8 - */ - private ConsistencyMode getConsistencyMode(URL registryURL) { - String value = CONSISTENCY_MODE.getValue(registryURL); - if (StringUtils.isNotEmpty(value)) { - return ConsistencyMode.valueOf(value); - } - return ConsistencyMode.DEFAULT; - } - - /** - * Get the "tags" from the {@link URL} of registry - * - * @param registryURL the {@link URL} of registry - * @return non-null - * @sine 2.7.8 - */ - private List getTags(URL registryURL) { - String value = TAGS.getValue(registryURL); - return StringUtils.splitToList(value, COMMA_SEPARATOR_CHAR); - } - - @Override - public URL getUrl() { - return url; - } - - private List getRegisteringTags(URL url) { - List tags = new ArrayList<>(); - String rawTag = url.getParameter(REGISTER_TAG); - if (StringUtils.isNotEmpty(rawTag)) { - tags.addAll(Arrays.asList(SEMICOLON_SPLIT_PATTERN.split(rawTag))); - } - return tags; - } - - @Override - public void destroy() { - if (notifier != null) { - notifier.stop(); - } - notifier = null; - notifierExecutor.shutdownNow(); - ttlScheduler.stop(); - } - - @Override - public void register(ServiceInstance serviceInstance) throws RuntimeException { - NewService consulService = buildService(serviceInstance); - ttlScheduler.add(consulService.getId()); - client.agentServiceRegister(consulService, aclToken); - } - - @Override - public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { - if (notifier == null) { - String serviceName = listener.getServiceNames(); - Response> response = getHealthServices(serviceName, -1, buildWatchTimeout()); - Long consulIndex = response.getConsulIndex(); - notifier = new ConsulNotifier(serviceName, consulIndex); - } - notifierExecutor.execute(notifier); - } - - @Override - public void update(ServiceInstance serviceInstance) throws RuntimeException { - // TODO - // client.catalogRegister(buildCatalogService(serviceInstance)); - } - - @Override - public void unregister(ServiceInstance serviceInstance) throws RuntimeException { - String id = buildId(serviceInstance); - ttlScheduler.remove(id); - client.agentServiceDeregister(id, aclToken); - } - - @Override - public Set getServices() { - CatalogServicesRequest request = CatalogServicesRequest.newBuilder() - .setQueryParams(QueryParams.DEFAULT) - .setToken(aclToken) - .build(); - return this.client.getCatalogServices(request).getValue().keySet(); - } - - @Override - public List getInstances(String serviceName) throws NullPointerException { - Response> response = getHealthServices(serviceName, -1, buildWatchTimeout()); - Long consulIndex = response.getConsulIndex(); - if (notifier == null) { - notifier = new ConsulNotifier(serviceName, consulIndex); - } - return convert(response.getValue()); - } - - private List convert(List services) { - return services.stream() - .map(HealthService::getService) - .map(service -> { - ServiceInstance instance = new DefaultServiceInstance( - service.getId(), - service.getService(), - service.getAddress(), - service.getPort()); - instance.getMetadata().putAll(getMetadata(service)); - return instance; - }) - .collect(Collectors.toList()); - } - - private Response> getHealthServices(String service, long index, int watchTimeout) { - HealthServicesRequest request = HealthServicesRequest.newBuilder() - .setTag(tag) - .setQueryParams(new QueryParams(watchTimeout, index)) - .setPassing(true) - .build(); - return client.getHealthServices(service, request); - } - - private Map getMetadata(HealthService.Service service) { - Map metadata = service.getMeta(); - metadata = decodeMetadata(metadata); - if (CollectionUtils.isEmptyMap(metadata)) { - metadata = getScCompatibleMetadata(service.getTags()); - } - return metadata; - } - - private Map getScCompatibleMetadata(List tags) { - LinkedHashMap metadata = new LinkedHashMap<>(); - if (tags != null) { - for (String tag : tags) { - String[] parts = StringUtils.delimitedListToStringArray(tag, "="); - switch (parts.length) { - case 0: - break; - case 1: - metadata.put(parts[0], parts[0]); - break; - case 2: - metadata.put(parts[0], parts[1]); - break; - default: - String[] end = Arrays.copyOfRange(parts, 1, parts.length); - metadata.put(parts[0], StringUtils.arrayToDelimitedString(end, "=")); - break; - } - - } - } - - return metadata; - } - - private NewService buildService(ServiceInstance serviceInstance) { - NewService service = new NewService(); - service.setAddress(serviceInstance.getHost()); - service.setPort(serviceInstance.getPort()); - service.setId(buildId(serviceInstance)); - service.setName(serviceInstance.getServiceName()); - service.setCheck(buildCheck(serviceInstance)); - service.setTags(buildTags(serviceInstance)); - return service; - } - - private String buildId(ServiceInstance serviceInstance) { - return Integer.toHexString(serviceInstance.hashCode()); - } - - private List buildTags(ServiceInstance serviceInstance) { - List tags = new LinkedList<>(this.tags); - - if (StringUtils.isNotEmpty(instanceZone)) { - tags.add(defaultZoneMetadataName + "=" + instanceZone); - } - - if (StringUtils.isNotEmpty(instanceGroup)) { - tags.add("group=" + instanceGroup); - } - - Map params = serviceInstance.getMetadata(); - params.keySet().stream() - .map(k -> k + "=" + params.get(k)) - .forEach(tags::add); - - tags.addAll(registeringTags); - return tags; - } - - private Map buildMetadata(ServiceInstance serviceInstance) { - Map metadata = new LinkedHashMap<>(); - metadata.putAll(getScCompatibleMetadata(registeringTags)); - if (CollectionUtils.isNotEmptyMap(serviceInstance.getMetadata())) { - metadata.putAll(serviceInstance.getMetadata()); - } - metadata = encodeMetadata(metadata); - return metadata; - } - - private Map encodeMetadata(Map metadata) { - if (metadata == null) { - return metadata; - } - Map encoded = new HashMap<>(metadata.size()); - metadata.forEach((k, v) -> encoded.put(Base64.getEncoder().encodeToString(k.getBytes()), v)); - return encoded; - } - - private Map decodeMetadata(Map metadata) { - if (metadata == null) { - return metadata; - } - Map decoded = new HashMap<>(metadata.size()); - metadata.forEach((k, v) -> decoded.put(new String(Base64.getDecoder().decode(k)), v)); - return decoded; - } - - private NewService.Check buildCheck(ServiceInstance serviceInstance) { - NewService.Check check = new NewService.Check(); - check.setTtl((checkPassInterval / 1000) + "s"); - String deregister = serviceInstance.getMetadata().get(DEREGISTER_AFTER); - check.setDeregisterCriticalServiceAfter(deregister == null ? DEFAULT_DEREGISTER_TIME : deregister); - return check; - } - - private int buildWatchTimeout() { - return url.getParameter(WATCH_TIMEOUT, DEFAULT_WATCH_TIMEOUT) / 1000; - } - - private class ConsulNotifier implements Runnable { - private String serviceName; - private long consulIndex; - private boolean running; - - ConsulNotifier(String serviceName, long consulIndex) { - this.serviceName = serviceName; - this.consulIndex = consulIndex; - this.running = true; - } - - @Override - public void run() { - while (this.running) { - processService(); - } - } - - private void processService() { - Response> response = getHealthServices(serviceName, consulIndex, Integer.MAX_VALUE); - Long currentIndex = response.getConsulIndex(); - if (currentIndex != null && currentIndex > consulIndex) { - consulIndex = currentIndex; - List services = response.getValue(); - List serviceInstances = convert(services); - dispatchServiceInstancesChangedEvent(serviceName, serviceInstances); - } - } - - void stop() { - this.running = false; - } - } - - private static class TtlScheduler { - - private static final Logger logger = LoggerFactory.getLogger(TtlScheduler.class); - - private final Map serviceHeartbeats = new ConcurrentHashMap<>(); - - private ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); - - private long checkInterval; - - private ConsulClient client; - - public TtlScheduler(long checkInterval, ConsulClient client) { - this.checkInterval = checkInterval; - this.client = client; - } - - /** - * Add a service to the checks loop. - * - * @param instanceId instance id - */ - public void add(String instanceId) { - ScheduledFuture task = this.scheduler.scheduleAtFixedRate( - new ConsulHeartbeatTask(instanceId), - checkInterval / 8, - checkInterval / 8, - TimeUnit.MILLISECONDS); - ScheduledFuture previousTask = this.serviceHeartbeats.put(instanceId, task); - if (previousTask != null) { - previousTask.cancel(true); - } - } - - public void remove(String instanceId) { - ScheduledFuture task = this.serviceHeartbeats.get(instanceId); - if (task != null) { - task.cancel(true); - } - this.serviceHeartbeats.remove(instanceId); - } - - private class ConsulHeartbeatTask implements Runnable { - - private String checkId; - - ConsulHeartbeatTask(String serviceId) { - this.checkId = serviceId; - if (!this.checkId.startsWith("service:")) { - this.checkId = "service:" + this.checkId; - } - } - - @Override - public void run() { - TtlScheduler.this.client.agentCheckPass(this.checkId); - if (logger.isDebugEnabled()) { - logger.debug("Sending consul heartbeat for: " + this.checkId); - } - } - - } - - public void stop() { - scheduler.shutdownNow(); - } - - } -} diff --git a/dubbo-registry/dubbo-registry-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory b/dubbo-registry/dubbo-registry-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory deleted file mode 100644 index 7aea18f4d8..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory +++ /dev/null @@ -1 +0,0 @@ -consul=org.apache.dubbo.registry.consul.ConsulRegistryFactory diff --git a/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulRegistryTest.java b/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulRegistryTest.java deleted file mode 100644 index f0a3db923c..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulRegistryTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * 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.apache.dubbo.registry.consul; - -import com.pszymczyk.consul.ConsulProcess; -import com.pszymczyk.consul.ConsulStarterBuilder; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.status.Status; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.status.RegistryStatusChecker; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.mock; - -public class ConsulRegistryTest { - - private static ConsulProcess consul; - private ConsulRegistry consulRegistry; - private String service = "org.apache.dubbo.test.injvmServie"; - private URL serviceUrl = URL.valueOf("consul://127.0.0.1:" + NetUtils.getAvailablePort() + "/" + service + "?notify=false&methods=test1,test2"); - private URL registryUrl; - private ConsulRegistryFactory consulRegistryFactory; - - @BeforeEach - public void setUp() throws Exception { - this.consul = ConsulStarterBuilder.consulStarter() - .build() - .start(); - this.registryUrl = URL.valueOf("consul://localhost:" + consul.getHttpPort()); - - consulRegistryFactory = new ConsulRegistryFactory(); - this.consulRegistry = (ConsulRegistry) consulRegistryFactory.createRegistry(registryUrl); - } - - @AfterEach - public void tearDown() throws Exception { - consul.close(); - this.consulRegistry.destroy(); - } - - @Test - public void testRegister() { - Set registered; - - for (int i = 0; i < 2; i++) { - consulRegistry.register(serviceUrl); - registered = consulRegistry.getRegistered(); - assertThat(registered.contains(serviceUrl), is(true)); - } - - registered = consulRegistry.getRegistered(); - - assertThat(registered.size(), is(1)); - } - - @Test - public void testSubscribe() { - NotifyListener listener = mock(NotifyListener.class); - consulRegistry.subscribe(serviceUrl, listener); - - Map> subscribed = consulRegistry.getSubscribed(); - assertThat(subscribed.size(), is(1)); - assertThat(subscribed.get(serviceUrl).size(), is(1)); - - consulRegistry.unsubscribe(serviceUrl, listener); - subscribed = consulRegistry.getSubscribed(); - assertThat(subscribed.size(), is(1)); - assertThat(subscribed.get(serviceUrl).size(), is(0)); - } - - @Test - public void testAvailable() { - consulRegistry.register(serviceUrl); - assertThat(consulRegistry.isAvailable(), is(true)); - -// consulRegistry.destroy(); -// assertThat(consulRegistry.isAvailable(), is(false)); - } - - @Test - public void testLookup() throws InterruptedException { - List lookup = consulRegistry.lookup(serviceUrl); - assertThat(lookup.size(), is(0)); - - consulRegistry.register(serviceUrl); - Thread.sleep(5000); - lookup = consulRegistry.lookup(serviceUrl); - assertThat(lookup.size(), is(1)); - } - - @Test - public void testStatusChecker() { - RegistryStatusChecker registryStatusChecker = new RegistryStatusChecker(); - Status status = registryStatusChecker.check(); - assertThat(status.getLevel(), is(Status.Level.UNKNOWN)); - - Registry registry = consulRegistryFactory.getRegistry(registryUrl); - assertThat(registry, not(nullValue())); - - status = registryStatusChecker.check(); - assertThat(status.getLevel(), is(Status.Level.OK)); - - registry.register(serviceUrl); - status = registryStatusChecker.check(); - assertThat(status.getLevel(), is(Status.Level.OK)); - } - -} diff --git a/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulServiceDiscoveryTest.java deleted file mode 100644 index 9f10d0ab16..0000000000 --- a/dubbo-registry/dubbo-registry-consul/src/test/java/org/apache/dubbo/registry/consul/ConsulServiceDiscoveryTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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.apache.dubbo.registry.consul; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.client.DefaultServiceInstance; -import org.apache.dubbo.registry.client.ServiceInstance; - -import com.pszymczyk.consul.ConsulProcess; -import com.pszymczyk.consul.ConsulStarterBuilder; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - -import static java.lang.String.valueOf; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class ConsulServiceDiscoveryTest { - - private URL url; - private ConsulServiceDiscovery consulServiceDiscovery; - private ConsulProcess consul; - private static final String SERVICE_NAME = "A"; - private static final String LOCALHOST = "127.0.0.1"; - - @BeforeEach - public void init() throws Exception { - this.consul = ConsulStarterBuilder.consulStarter() - .build() - .start(); - url = URL.valueOf("consul://localhost:" + consul.getHttpPort()); - consulServiceDiscovery = new ConsulServiceDiscovery(); - consulServiceDiscovery.initialize(url); - } - - @AfterEach - public void close() { - consulServiceDiscovery.destroy(); - consul.close(); - } - - @Test - public void testRegistration() throws InterruptedException { - DefaultServiceInstance serviceInstance = createServiceInstance(SERVICE_NAME, LOCALHOST, NetUtils.getAvailablePort()); - consulServiceDiscovery.register(serviceInstance); - Thread.sleep(5000); - - List serviceInstances = consulServiceDiscovery.getInstances(SERVICE_NAME); - assertEquals(serviceInstances.size(), 1); - assertEquals(serviceInstances.get(0).getId(), Integer.toHexString(serviceInstance.hashCode())); - assertEquals(serviceInstances.get(0).getHost(), serviceInstance.getHost()); - assertEquals(serviceInstances.get(0).getServiceName(), serviceInstance.getServiceName()); - assertEquals(serviceInstances.get(0).getPort(), serviceInstance.getPort()); - - consulServiceDiscovery.unregister(serviceInstance); - Thread.sleep(5000); - serviceInstances = consulServiceDiscovery.getInstances(SERVICE_NAME); - System.out.println(serviceInstances.size()); - assertTrue(serviceInstances.isEmpty()); - } - - private DefaultServiceInstance createServiceInstance(String serviceName, String host, int port) { - return new DefaultServiceInstance(host + ":" + port, serviceName, host, port); - } - - @Test - public void testGetInstances() throws Exception { - String serviceName = "ConsulTest77Service"; - assertTrue(consulServiceDiscovery.getInstances(serviceName).isEmpty()); - int portA = NetUtils.getAvailablePort(); - int portB = NetUtils.getAvailablePort(); - consulServiceDiscovery.register(new DefaultServiceInstance(valueOf(System.nanoTime()), serviceName, "127.0.0.1", portA)); - consulServiceDiscovery.register(new DefaultServiceInstance(valueOf(System.nanoTime()), serviceName, "127.0.0.1", portB)); - Thread.sleep(5000); - Assertions.assertFalse(consulServiceDiscovery.getInstances(serviceName).isEmpty()); - List r = convertToIpPort(consulServiceDiscovery.getInstances(serviceName)); - assertTrue(r.contains("127.0.0.1:" + portA)); - assertTrue(r.contains("127.0.0.1:" + portB)); - } - - private List convertToIpPort(List serviceInstances) { - List result = new ArrayList<>(); - for (ServiceInstance serviceInstance : serviceInstances) { - result.add(serviceInstance.getHost() + ":" + serviceInstance.getPort()); - } - return result; - } -} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-default/pom.xml b/dubbo-registry/dubbo-registry-default/pom.xml deleted file mode 100644 index b2eeecb1cb..0000000000 --- a/dubbo-registry/dubbo-registry-default/pom.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-registry - ${revision} - ../pom.xml - - dubbo-registry-default - jar - ${project.artifactId} - The default registry module of dubbo project - - false - - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-rpc-injvm - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - org.apache.commons - commons-lang3 - test - - - \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java deleted file mode 100644 index ef9238ee04..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistry.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ExecutorUtil; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.registry.support.FailbackRegistry; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.Invoker; - -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantLock; - -import static org.apache.dubbo.registry.Constants.REGISTRY_RECONNECT_PERIOD_KEY; - -/** - * DubboRegistry - */ -public class DubboRegistry extends FailbackRegistry { - - private final static Logger logger = LoggerFactory.getLogger(DubboRegistry.class); - - // Reconnecting detection cycle: 3 seconds (unit:millisecond) - private static final int RECONNECT_PERIOD_DEFAULT = 3 * 1000; - - // Scheduled executor service - private final ScheduledExecutorService reconnectTimer = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboRegistryReconnectTimer", true)); - - // Reconnection timer, regular check connection is available. If unavailable, unlimited reconnection. - private final ScheduledFuture reconnectFuture; - - // The lock for client acquisition process, lock the creation process of the client instance to prevent repeated clients - private final ReentrantLock clientLock = new ReentrantLock(); - - private final Invoker registryInvoker; - - private final RegistryService registryService; - - /** - * The time in milliseconds the reconnectTimer will wait - */ - private final int reconnectPeriod; - - public DubboRegistry(Invoker registryInvoker, RegistryService registryService) { - super(registryInvoker.getUrl()); - this.registryInvoker = registryInvoker; - this.registryService = registryService; - // Start reconnection timer - this.reconnectPeriod = registryInvoker.getUrl().getParameter(REGISTRY_RECONNECT_PERIOD_KEY, RECONNECT_PERIOD_DEFAULT); - reconnectFuture = reconnectTimer.scheduleWithFixedDelay(() -> { - // Check and connect to the registry - try { - connect(); - } catch (Throwable t) { // Defensive fault tolerance - logger.error("Unexpected error occur at reconnect, cause: " + t.getMessage(), t); - } - }, reconnectPeriod, reconnectPeriod, TimeUnit.MILLISECONDS); - } - - protected final void connect() { - try { - // Check whether or not it is connected - if (isAvailable()) { - return; - } - if (logger.isInfoEnabled()) { - logger.info("Reconnect to registry " + getUrl()); - } - clientLock.lock(); - try { - // Double check whether or not it is connected - if (isAvailable()) { - return; - } - recover(); - } finally { - clientLock.unlock(); - } - } catch (Throwable t) { // Ignore all the exceptions and wait for the next retry - if (getUrl().getParameter(Constants.CHECK_KEY, true)) { - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } - throw new RuntimeException(t.getMessage(), t); - } - logger.error("Failed to connect to registry " + getUrl().getAddress() + " from provider/consumer " + NetUtils.getLocalHost() + " use dubbo " + Version.getVersion() + ", cause: " + t.getMessage(), t); - } - } - - @Override - public boolean isAvailable() { - if (registryInvoker == null) { - return false; - } - return registryInvoker.isAvailable(); - } - - @Override - public void destroy() { - super.destroy(); - try { - // Cancel the reconnection timer - ExecutorUtil.cancelScheduledFuture(reconnectFuture); - } catch (Throwable t) { - logger.warn("Failed to cancel reconnect timer", t); - } - registryInvoker.destroy(); - ExecutorUtil.gracefulShutdown(reconnectTimer, reconnectPeriod); - } - - @Override - public void doRegister(URL url) { - registryService.register(url); - } - - @Override - public void doUnregister(URL url) { - registryService.unregister(url); - } - - @Override - public void doSubscribe(URL url, NotifyListener listener) { - registryService.subscribe(url, listener); - } - - @Override - public void doUnsubscribe(URL url, NotifyListener listener) { - registryService.unsubscribe(url, listener); - } - - @Override - public List lookup(URL url) { - return registryService.lookup(url); - } - -} diff --git a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java b/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java deleted file mode 100644 index bc669c6609..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/main/java/org/apache/dubbo/registry/dubbo/DubboRegistryFactory.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.URLBuilder; -import org.apache.dubbo.common.bytecode.Wrapper; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.registry.integration.RegistryDirectory; -import org.apache.dubbo.registry.support.AbstractRegistryFactory; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.dubbo.rpc.cluster.Cluster; -import org.apache.dubbo.rpc.cluster.RouterChain; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; - -import static org.apache.dubbo.common.constants.CommonConstants.CALLBACK_INSTANCES_LIMIT_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN; -import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.LAZY_CONNECT_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; -import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.remoting.Constants.CONNECT_TIMEOUT_KEY; -import static org.apache.dubbo.remoting.Constants.RECONNECT_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; - -/** - * DubboRegistryFactory - * - */ -public class DubboRegistryFactory extends AbstractRegistryFactory { - - private Protocol protocol; - private ProxyFactory proxyFactory; - private Cluster cluster; - - private static URL getRegistryURL(URL url) { - return URLBuilder.from(url) - .setPath(RegistryService.class.getName()) - .removeParameter(EXPORT_KEY).removeParameter(REFER_KEY) - .addParameter(INTERFACE_KEY, RegistryService.class.getName()) - .addParameter(CLUSTER_STICKY_KEY, "true") - .addParameter(LAZY_CONNECT_KEY, "true") - .addParameter(RECONNECT_KEY, "false") - .addParameterIfAbsent(TIMEOUT_KEY, "10000") - .addParameterIfAbsent(CALLBACK_INSTANCES_LIMIT_KEY, "10000") - .addParameterIfAbsent(CONNECT_TIMEOUT_KEY, "10000") - .addParameter(METHODS_KEY, StringUtils.join(new HashSet<>(Arrays.asList(Wrapper.getWrapper(RegistryService.class).getDeclaredMethodNames())), ",")) - //.addParameter(Constants.STUB_KEY, RegistryServiceStub.class.getName()) - //.addParameter(Constants.STUB_EVENT_KEY, Boolean.TRUE.toString()) //for event dispatch - //.addParameter(Constants.ON_DISCONNECT_KEY, "disconnect") - .addParameter("subscribe.1.callback", "true") - .addParameter("unsubscribe.1.callback", "false") - .build(); - } - - public void setProtocol(Protocol protocol) { - this.protocol = protocol; - } - - public void setProxyFactory(ProxyFactory proxyFactory) { - this.proxyFactory = proxyFactory; - } - - public void setCluster(Cluster cluster) { - this.cluster = cluster; - } - - @Override - public Registry createRegistry(URL url) { - url = getRegistryURL(url); - List urls = new ArrayList<>(); - urls.add(url.removeParameter(BACKUP_KEY)); - String backup = url.getParameter(BACKUP_KEY); - if (backup != null && backup.length() > 0) { - String[] addresses = COMMA_SPLIT_PATTERN.split(backup); - for (String address : addresses) { - urls.add(url.setAddress(address)); - } - } - RegistryDirectory directory = new RegistryDirectory<>(RegistryService.class, url.addParameter(INTERFACE_KEY, RegistryService.class.getName()).addParameterAndEncoded(REFER_KEY, url.toParameterString())); - Invoker registryInvoker = cluster.join(directory); - RegistryService registryService = proxyFactory.getProxy(registryInvoker); - DubboRegistry registry = new DubboRegistry(registryInvoker, registryService); - directory.setRegistry(registry); - directory.setProtocol(protocol); - directory.setRouterChain(RouterChain.buildChain(url)); - directory.notify(urls); - directory.subscribe(new URL(CONSUMER_PROTOCOL, NetUtils.getLocalHost(), 0, RegistryService.class.getName(), url.getParameters())); - return registry; - } -} diff --git a/dubbo-registry/dubbo-registry-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory b/dubbo-registry/dubbo-registry-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory deleted file mode 100644 index a2c6f12ea0..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory +++ /dev/null @@ -1 +0,0 @@ -dubbo=org.apache.dubbo.registry.dubbo.DubboRegistryFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/AbstractRegistryService.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/AbstractRegistryService.java deleted file mode 100644 index 8b7a32a36b..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/AbstractRegistryService.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.RegistryService; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * AbstractRegistryService - * - */ -public abstract class AbstractRegistryService implements RegistryService { - - // Log output - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - // Registered services - // Map> - private final ConcurrentMap> registered = new ConcurrentHashMap>(); - - // Subscribed services - // Map - private final ConcurrentMap> subscribed = new ConcurrentHashMap>(); - - // Notified services - // Map> - private final ConcurrentMap> notified = new ConcurrentHashMap>(); - - // Listeners list for subscribed services - // Map> - private final ConcurrentMap> notifyListeners = new ConcurrentHashMap>(); - - @Override - public void register(URL url) { - if (logger.isInfoEnabled()) { - logger.info("Register service: " + url.getServiceKey() + ",url:" + url); - } - register(url.getServiceKey(), url); - } - - @Override - public void unregister(URL url) { - if (logger.isInfoEnabled()) { - logger.info("Unregister service: " + url.getServiceKey() + ",url:" + url); - } - unregister(url.getServiceKey(), url); - } - - @Override - public void subscribe(URL url, NotifyListener listener) { - if (logger.isInfoEnabled()) { - logger.info("Subscribe service: " + url.getServiceKey() + ",url:" + url); - } - subscribe(url.getServiceKey(), url, listener); - } - - @Override - public void unsubscribe(URL url, NotifyListener listener) { - if (logger.isInfoEnabled()) { - logger.info("Unsubscribe service: " + url.getServiceKey() + ",url:" + url); - } - unsubscribe(url.getServiceKey(), url, listener); - } - - @Override - public List lookup(URL url) { - return getRegistered(url.getServiceKey()); - } - - public void register(String service, URL url) { - if (service == null) { - throw new IllegalArgumentException("service == null"); - } - if (url == null) { - throw new IllegalArgumentException("url == null"); - } - List urls = registered.computeIfAbsent(service, k -> new CopyOnWriteArrayList<>()); - if (!urls.contains(url)) { - urls.add(url); - } - } - - public void unregister(String service, URL url) { - if (service == null) { - throw new IllegalArgumentException("service == null"); - } - if (url == null) { - throw new IllegalArgumentException("url == null"); - } - List urls = registered.get(service); - if (urls != null) { - URL deleteURL = null; - for (URL u : urls) { - if (u.toIdentityString().equals(url.toIdentityString())) { - deleteURL = u; - break; - } - } - if (deleteURL != null) { - urls.remove(deleteURL); - } - } - } - - public void subscribe(String service, URL url, NotifyListener listener) { - if (service == null) { - throw new IllegalArgumentException("service == null"); - } - if (url == null) { - throw new IllegalArgumentException("parameters == null"); - } - if (listener == null) { - throw new IllegalArgumentException("listener == null"); - } - subscribed.put(service, url.getParameters()); - addListener(service, listener); - } - - public void unsubscribe(String service, URL url, NotifyListener listener) { - if (service == null) { - throw new IllegalArgumentException("service == null"); - } - if (url == null) { - throw new IllegalArgumentException("parameters == null"); - } - if (listener == null) { - throw new IllegalArgumentException("listener == null"); - } - subscribed.remove(service); - removeListener(service, listener); - } - - //The listener of the consumer and the provider can be stored together, all based on the service name - private void addListener(final String service, final NotifyListener listener) { - if (listener == null) { - return; - } - List listeners = notifyListeners.computeIfAbsent(service, k -> new CopyOnWriteArrayList<>()); - if (!listeners.contains(listener)) { - listeners.add(listener); - } - } - - private void removeListener(final String service, final NotifyListener listener) { - if (listener == null) { - return; - } - List listeners = notifyListeners.get(service); - if (listeners != null) { - listeners.remove(listener); - } - } - - private void doNotify(String service, List urls) { - notified.put(service, urls); - List listeners = notifyListeners.get(service); - if (listeners != null) { - for (NotifyListener listener : listeners) { - try { - notify(service, urls, listener); - } catch (Throwable t) { - logger.error("Failed to notify registry event, service: " + service + ", urls: " + urls + ", cause: " + t.getMessage(), t); - } - } - } - } - - protected void notify(String service, List urls, NotifyListener listener) { - listener.notify(urls); - } - - protected final void forbid(String service) { - doNotify(service, new ArrayList(0)); - } - - protected final void notify(String service, List urls) { - if (service == null || service.length() == 0 - || urls == null || urls.size() == 0) { - return; - } - doNotify(service, urls); - } - - public Map> getRegistered() { - return Collections.unmodifiableMap(registered); - } - - public List getRegistered(String service) { - return Collections.unmodifiableList(registered.get(service)); - } - - public Map> getSubscribed() { - return Collections.unmodifiableMap(subscribed); - } - - public Map getSubscribed(String service) { - return subscribed.get(service); - } - - public Map> getNotified() { - return Collections.unmodifiableMap(notified); - } - - public List getNotified(String service) { - return Collections.unmodifiableList(notified.get(service)); - } - - public Map> getListeners() { - return Collections.unmodifiableMap(notifyListeners); - } - -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoService.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoService.java deleted file mode 100644 index f47febb970..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoService.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -/** - * TestService - */ - -public interface DemoService { - void sayHello(String name); - - int plus(int a, int b); -} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoServiceImpl.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoServiceImpl.java deleted file mode 100644 index 5b928726cd..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DemoServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -/** - * - */ -public class DemoServiceImpl implements DemoService { - @Override - public void sayHello(String name) { - - } - - @Override - public int plus(int a, int b) { - return 0; - } -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java deleted file mode 100644 index b757d4accf..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/DubboRegistryTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.registry.support.FailbackRegistry; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_PROTOCOL; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.mock; - -public class DubboRegistryTest { - - private static final Logger logger = LoggerFactory.getLogger(DubboRegistryTest.class); - - private DubboRegistry dubboRegistry; - - private URL registryURL; - - private URL serviceURL; - - private NotifyListener notifyListener; - - private Invoker invoker; - - private RegistryService registryService; - - @BeforeEach - public void setUp() { - registryURL = new URL(REGISTRY_PROTOCOL, NetUtils.getLocalHost(), NetUtils.getAvailablePort()) - .addParameter(Constants.CHECK_KEY, false) - .setServiceInterface(RegistryService.class.getName()); - serviceURL = new URL(DubboProtocol.NAME, NetUtils.getLocalHost(), NetUtils.getAvailablePort()) - .addParameter(Constants.CHECK_KEY, false) - .setServiceInterface(RegistryService.class.getName()); - - registryService = new MockDubboRegistry(registryURL); - - invoker = mock(Invoker.class); - given(invoker.getUrl()).willReturn(serviceURL); - given(invoker.getInterface()).willReturn(RegistryService.class); - given(invoker.invoke(new RpcInvocation())).willReturn(null); - - dubboRegistry = new DubboRegistry(invoker, registryService); - notifyListener = mock(NotifyListener.class); - } - - @Test - public void testRegister() { - dubboRegistry.register(serviceURL); - assertEquals(1, getRegisteredSize()); - } - - @Test - public void testUnRegister() { - assertEquals(0, getRegisteredSize()); - dubboRegistry.register(serviceURL); - assertEquals(1, getRegisteredSize()); - dubboRegistry.unregister(serviceURL); - assertEquals(0, getRegisteredSize()); - } - - @Test - public void testSubscribe() { - dubboRegistry.register(serviceURL); - assertEquals(1, getRegisteredSize()); - dubboRegistry.subscribe(serviceURL, notifyListener); - assertEquals(1, getSubscribedSize()); - assertEquals(1, getNotifiedListeners()); - } - - @Test - public void testUnsubscribe() { - dubboRegistry.subscribe(serviceURL, notifyListener); - assertEquals(1, getSubscribedSize()); - assertEquals(1, getNotifiedListeners()); - dubboRegistry.unsubscribe(serviceURL, notifyListener); - assertEquals(0, getNotifiedListeners()); - } - - private class MockDubboRegistry extends FailbackRegistry { - - private volatile boolean isAvailable = false; - - public MockDubboRegistry(URL url) { - super(url); - } - - @Override - public void doRegister(URL url) { - logger.info("Begin to register: " + url); - isAvailable = true; - } - - @Override - public void doUnregister(URL url) { - logger.info("Begin to ungister: " + url); - isAvailable = false; - } - - @Override - public void doSubscribe(URL url, NotifyListener listener) { - logger.info("Begin to subscribe: " + url); - } - - @Override - public void doUnsubscribe(URL url, NotifyListener listener) { - logger.info("Begin to unSubscribe: " + url); - } - - @Override - public boolean isAvailable() { - return isAvailable; - } - } - - private int getNotifiedListeners() { - return dubboRegistry.getSubscribed().get(serviceURL).size(); - } - - private int getRegisteredSize() { - return dubboRegistry.getRegistered().size(); - } - - private int getSubscribedSize() { - return dubboRegistry.getSubscribed().size(); - } -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockChannel.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockChannel.java deleted file mode 100644 index e563da616c..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockChannel.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeChannel; -import org.apache.dubbo.remoting.exchange.ExchangeHandler; - -import java.net.InetSocketAddress; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; - -public class MockChannel implements ExchangeChannel { - - public static boolean closed = false; - public static boolean closing = true; - final InetSocketAddress localAddress; - final InetSocketAddress remoteAddress; - - public MockChannel(String localHostname, int localPort, String remoteHostName, int remotePort) { - localAddress = new InetSocketAddress(localHostname, localPort); - remoteAddress = new InetSocketAddress(remoteHostName, remotePort); - closed = false; - } - - @Override - public InetSocketAddress getLocalAddress() { - return localAddress; - } - - @Override - public InetSocketAddress getRemoteAddress() { - return remoteAddress; - } - - @Override - public boolean isConnected() { - return true; - } - - @Override - public void close() { - closed = true; - } - - @Override - public void send(Object message) throws RemotingException { - } - - @Override - public void close(int timeout) { - } - - @Override - public void startClose() { - closing = true; - } - - @Override - public URL getUrl() { - return null; - } - - public CompletableFuture send(Object request, int timeout) throws RemotingException { - return null; - } - - @Override - public ChannelHandler getChannelHandler() { - return null; - } - - public CompletableFuture request(Object request) throws RemotingException { - return null; - } - - public CompletableFuture request(Object request, int timeout) throws RemotingException { - return null; - } - - @Override - public CompletableFuture request(Object request, ExecutorService executor) throws RemotingException { - return null; - } - - @Override - public CompletableFuture request(Object request, int timeout, ExecutorService executor) throws RemotingException { - return null; - } - - public ExchangeHandler getExchangeHandler() { - return null; - } - - @Override - public Object getAttribute(String key) { - return null; - } - - @Override - public void setAttribute(String key, Object value) { - - } - - @Override - public boolean hasAttribute(String key) { - return false; - } - - @Override - public boolean isClosed() { - return false; - } - - @Override - public void removeAttribute(String key) { - - } - - @Override - public void send(Object message, boolean sent) throws RemotingException { - - } - -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockedClient.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockedClient.java deleted file mode 100644 index ad06cd2096..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/MockedClient.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.Codec; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeClient; -import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.exchange.support.Replier; - -import java.net.InetSocketAddress; -import java.util.Map; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeoutException; - -/** - * MockedClient - * - */ -public class MockedClient implements ExchangeClient { - - //private String host; - - //private int port; - - private boolean connected; - - private Object received; - - private Object sent; - - private Object invoked; - - private Replier handler; - - private InetSocketAddress address; - - private boolean closed = false; - - //private ChannelListener listener; - - public MockedClient(String host, int port, boolean connected) { - this(host, port, connected, null); - } - - public MockedClient(String host, int port, boolean connected, Object received) { - this.address = new InetSocketAddress(host, port); - this.connected = connected; - this.received = received; - } - - public void open() { - } - - @Override - public void close() { - this.closed = true; - } - - @Override - public void send(Object msg) throws RemotingException { - this.sent = msg; - } - - public CompletableFuture request(Object msg) throws RemotingException { - return request(msg, null); - } - - public CompletableFuture request(Object msg, int timeout) throws RemotingException { - return this.request(msg, timeout, null); - } - - @Override - public CompletableFuture request(Object msg, ExecutorService executor) throws RemotingException { - return this.request(msg, 0, executor); - } - - @Override - public CompletableFuture request(Object msg, int timeout, ExecutorService executor) throws RemotingException { - this.invoked = msg; - return new CompletableFuture() { - public Object get() throws InterruptedException, ExecutionException { - return received; - } - - public Object get(int timeoutInMillis) throws InterruptedException, ExecutionException, TimeoutException { - return received; - } - - public boolean isDone() { - return true; - } - }; - } - - public void registerHandler(Replier handler) { - this.handler = handler; - } - - public void unregisterHandler(Replier handler) { - //this.handler = null; - } - - public void addChannelListener(ChannelHandler listener) { - //this.listener = listener; - } - - public void removeChannelListener(ChannelHandler listener) { - //this.listener = null; - } - - @Override - public boolean isConnected() { - return connected; - } - - /** - * @param connected the connected to set - */ - public void setConnected(boolean connected) { - this.connected = connected; - } - - public Object getSent() { - return sent; - } - - public Replier getHandler() { - return handler; - } - - public Object getInvoked() { - return invoked; - } - - @Override - public InetSocketAddress getRemoteAddress() { - return address; - } - - public String getName() { - return "mocked"; - } - - @Override - public InetSocketAddress getLocalAddress() { - return null; - } - - public int getTimeout() { - return 0; - } - - public void setTimeout(int timeout) { - } - - @Override - public void close(int timeout) { - close(); - } - - @Override - public void startClose() { - - } - - public boolean isOpen() { - return closed; - } - - public Codec getCodec() { - return null; - } - - public void setCodec(Codec codec) { - } - - public String getHost() { - return null; - } - - public void setHost(String host) { - } - - public int getPort() { - return 0; - } - - public void setPort(int port) { - } - - public int getThreadCount() { - return 0; - } - - public void setThreadCount(int threadCount) { - } - - @Override - public URL getUrl() { - return null; - } - - public Replier getReceiver() { - return null; - } - - @Override - public ChannelHandler getChannelHandler() { - return null; - } - - public void reset(Map parameters) { - } - - public Channel getChannel() { - return this; - } - - public ExchangeHandler getExchangeHandler() { - return null; - } - - @Override - public void reconnect() throws RemotingException { - } - - @Override - public Object getAttribute(String key) { - return null; - } - - @Override - public void setAttribute(String key, Object value) { - - } - - @Override - public boolean hasAttribute(String key) { - return false; - } - - @Override - public boolean isClosed() { - return closed; - } - - @Override - public void removeAttribute(String key) { - - } - - /** - * @return the received - */ - public Object getReceived() { - return received; - } - - /** - * @param received the received to set - */ - public void setReceived(Object received) { - this.received = received; - } - - @Override - public void send(Object message, boolean sent) throws RemotingException { - } - - @Override - public void reset(URL url) { - } - - @Deprecated - public void reset(org.apache.dubbo.common.Parameters parameters) { - } - -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java deleted file mode 100644 index 9cc954e95a..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryDirectoryTest.java +++ /dev/null @@ -1,1143 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.LogUtil; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.RegistryFactory; -import org.apache.dubbo.registry.integration.RegistryDirectory; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.cluster.RouterChain; -import org.apache.dubbo.rpc.cluster.loadbalance.LeastActiveLoadBalance; -import org.apache.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance; -import org.apache.dubbo.rpc.cluster.router.script.ScriptRouterFactory; -import org.apache.dubbo.rpc.cluster.support.wrapper.MockClusterInvoker; -import org.apache.dubbo.rpc.model.ApplicationModel; -import org.apache.dubbo.rpc.service.GenericService; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.mockito.Mockito; - -import javax.script.ScriptEngineManager; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CountDownLatch; - -import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; -import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; -import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; -import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.LOADBALANCE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.ROUTE_PROTOCOL; -import static org.apache.dubbo.rpc.Constants.MOCK_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.INVOCATION_NEED_MOCK; -import static org.apache.dubbo.rpc.cluster.Constants.MOCK_PROTOCOL; -import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.RULE_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.TYPE_KEY; -import static org.junit.jupiter.api.Assertions.fail; - -@SuppressWarnings({"rawtypes", "unchecked"}) -public class RegistryDirectoryTest { - - private static boolean isScriptUnsupported = new ScriptEngineManager().getEngineByName("javascript") == null; - RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - String service = DemoService.class.getName(); - RpcInvocation invocation = new RpcInvocation(); - URL noMeaningUrl = URL.valueOf("notsupport:/" + service + "?refer=" + URL.encode("interface=" + service)); - URL SERVICEURL = URL.valueOf("dubbo://127.0.0.1:9091/" + service + "?lazy=true&side=consumer&application=mockName"); - URL SERVICEURL2 = URL.valueOf("dubbo://127.0.0.1:9092/" + service + "?lazy=true&side=consumer&application=mockName"); - URL SERVICEURL3 = URL.valueOf("dubbo://127.0.0.1:9093/" + service + "?lazy=true&side=consumer&application=mockName"); - URL SERVICEURL_DUBBO_NOPATH = URL.valueOf("dubbo://127.0.0.1:9092" + "?lazy=true&side=consumer&application=mockName"); - - private Registry registry = Mockito.mock(Registry.class); - - @BeforeEach - public void setUp() { - ApplicationModel.setApplication("RegistryDirectoryTest"); - } - - private RegistryDirectory getRegistryDirectory(URL url) { - RegistryDirectory registryDirectory = new RegistryDirectory(URL.class, url); - registryDirectory.setProtocol(protocol); - registryDirectory.setRegistry(registry); - registryDirectory.setRouterChain(RouterChain.buildChain(url)); - registryDirectory.subscribe(url); - // asert empty - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(0, invokers.size()); - Assertions.assertFalse(registryDirectory.isAvailable()); - return registryDirectory; - } - - private RegistryDirectory getRegistryDirectory() { - return getRegistryDirectory(noMeaningUrl); - } - - @Test - public void test_Constructor_WithErrorParam() { - try { - new RegistryDirectory(null, null); - fail(); - } catch (IllegalArgumentException e) { - - } - try { - // null url - new RegistryDirectory(null, noMeaningUrl); - fail(); - } catch (IllegalArgumentException e) { - - } - try { - // no servicekey - new RegistryDirectory(RegistryDirectoryTest.class, URL.valueOf("dubbo://10.20.30.40:9090")); - fail(); - } catch (IllegalArgumentException e) { - - } - } - - @Test - public void test_Constructor_CheckStatus() throws Exception { - URL url = URL.valueOf("notsupported://10.20.30.40/" + service + "?a=b").addParameterAndEncoded(REFER_KEY, - "foo=bar"); - RegistryDirectory reg = getRegistryDirectory(url); - Field field = reg.getClass().getDeclaredField("queryMap"); - field.setAccessible(true); - Map queryMap = (Map) field.get(reg); - Assertions.assertEquals("bar", queryMap.get("foo")); - Assertions.assertEquals(url.clearParameters().addParameter("foo", "bar"), reg.getConsumerUrl()); - } - - @Test - public void testNotified_Normal() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - test_Notified2invokers(registryDirectory); - test_Notified1invokers(registryDirectory); - test_Notified3invokers(registryDirectory); - testforbid(registryDirectory); - } - - /** - * Test push only router - */ - @Test - public void testNotified_Normal_withRouters() { - LogUtil.start(); - RegistryDirectory registryDirectory = getRegistryDirectory(); - test_Notified1invokers(registryDirectory); - test_Notified_only_routers(registryDirectory); - Assertions.assertTrue(registryDirectory.isAvailable()); - Assertions.assertTrue(LogUtil.checkNoError(), "notify no invoker urls ,should not error"); - LogUtil.stop(); - test_Notified2invokers(registryDirectory); - - } - - @Test - public void testNotified_WithError() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - List serviceUrls = new ArrayList(); - // ignore error log - URL badurl = URL.valueOf("notsupported://127.0.0.1/" + service); - serviceUrls.add(badurl); - serviceUrls.add(SERVICEURL); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - } - - @Test - public void testNotified_WithDuplicateUrls() { - List serviceUrls = new ArrayList(); - // ignore error log - serviceUrls.add(SERVICEURL); - serviceUrls.add(SERVICEURL); - - RegistryDirectory registryDirectory = getRegistryDirectory(); - registryDirectory.notify(serviceUrls); - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - } - - // forbid - private void testforbid(RegistryDirectory registryDirectory) { - invocation = new RpcInvocation(); - List serviceUrls = new ArrayList(); - serviceUrls.add(new URL(EMPTY_PROTOCOL, ANYHOST_VALUE, 0, service, CATEGORY_KEY, PROVIDERS_CATEGORY)); - registryDirectory.notify(serviceUrls); - Assertions.assertFalse(registryDirectory.isAvailable(), - "invokers size=0 ,then the registry directory is not available"); - try { - registryDirectory.list(invocation); - fail("forbid must throw RpcException"); - } catch (RpcException e) { - Assertions.assertEquals(RpcException.FORBIDDEN_EXCEPTION, e.getCode()); - } - } - - //The test call is independent of the path of the registry url - @Test - public void test_NotifiedDubbo1() { - URL errorPathUrl = URL.valueOf("notsupport:/" + "xxx" + "?refer=" + URL.encode("interface=" + service)); - RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl); - List serviceUrls = new ArrayList(); - URL Dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true"); - serviceUrls.add(Dubbo1URL.addParameter("methods", "getXXX")); - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - - invocation.setMethodName("getXXX"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - Assertions.assertEquals(DemoService.class.getName(), invokers.get(0).getUrl().getPath()); - } - - // notify one invoker - private void test_Notified_only_routers(RegistryDirectory registryDirectory) { - List serviceUrls = new ArrayList(); - serviceUrls.add(URL.valueOf("empty://127.0.0.1/?category=routers")); - registryDirectory.notify(serviceUrls); - } - - // notify one invoker - private void test_Notified1invokers(RegistryDirectory registryDirectory) { - - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1").addParameter(APPLICATION_KEY, "mockApplicationName"));// .addParameter("refer.autodestroy", "true") - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - invocation = new RpcInvocation(); - - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - - invocation.setMethodName("getXXX"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - - invocation.setMethodName("getXXX1"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - - invocation.setMethodName("getXXX2"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - } - - // 2 invokers=================================== - private void test_Notified2invokers(RegistryDirectory registryDirectory) { - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - invocation = new RpcInvocation(); - - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - invocation.setMethodName("getXXX"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - invocation.setMethodName("getXXX1"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - } - - // 3 invoker notifications=================================== - private void test_Notified3invokers(RegistryDirectory registryDirectory) { - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1,getXXX2,getXXX3")); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - invocation = new RpcInvocation(); - - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(3, invokers.size()); - - invocation.setMethodName("getXXX"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(3, invokers.size()); - - invocation.setMethodName("getXXX1"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(3, invokers.size()); - - invocation.setMethodName("getXXX2"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(3, invokers.size()); - - invocation.setMethodName("getXXX3"); - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(3, invokers.size()); - } - - @Test - public void testParametersMerge() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - URL regurl = noMeaningUrl.addParameter("test", "reg").addParameterAndEncoded(REFER_KEY, - "key=query&" + LOADBALANCE_KEY + "=" + LeastActiveLoadBalance.NAME); - RegistryDirectory registryDirectory2 = new RegistryDirectory( - RegistryDirectoryTest.class, - regurl); - registryDirectory2.setProtocol(protocol); - - List serviceUrls = new ArrayList(); - // The parameters of the inspection registry need to be cleared - { - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation(); - List invokers = registryDirectory.list(invocation); - - Invoker invoker = (Invoker) invokers.get(0); - URL url = invoker.getUrl(); - Assertions.assertNull(url.getParameter("key")); - } - // The parameters of the provider for the inspection service need merge - { - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX2").addParameter("key", "provider")); - - registryDirectory.notify(serviceUrls); - invocation = new RpcInvocation(); - List invokers = registryDirectory.list(invocation); - - Invoker invoker = (Invoker) invokers.get(0); - URL url = invoker.getUrl(); - Assertions.assertEquals("provider", url.getParameter("key")); - } - // The parameters of the test service query need to be with the providermerge. - { - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX3").addParameter("key", "provider")); - registryDirectory2.setRegistry(registry); - registryDirectory2.setRouterChain(RouterChain.buildChain(noMeaningUrl)); - registryDirectory2.subscribe(noMeaningUrl); - registryDirectory2.notify(serviceUrls); - invocation = new RpcInvocation(); - List invokers = registryDirectory2.list(invocation); - - Invoker invoker = (Invoker) invokers.get(0); - URL url = invoker.getUrl(); - Assertions.assertEquals("query", url.getParameter("key")); - } - - { - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation(); - List invokers = registryDirectory.list(invocation); - - Invoker invoker = (Invoker) invokers.get(0); - URL url = invoker.getUrl(); - Assertions.assertFalse(url.getParameter(Constants.CHECK_KEY, false)); - } - { - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter(LOADBALANCE_KEY, RoundRobinLoadBalance.NAME)); - registryDirectory2.notify(serviceUrls); - - invocation = new RpcInvocation(); - invocation.setMethodName("get"); - List invokers = registryDirectory2.list(invocation); - - Invoker invoker = (Invoker) invokers.get(0); - URL url = invoker.getUrl(); - Assertions.assertEquals(LeastActiveLoadBalance.NAME, url.getMethodParameter("get", LOADBALANCE_KEY)); - } - //test geturl - { - Assertions.assertNull(registryDirectory2.getUrl().getParameter("mock")); - serviceUrls.clear(); - serviceUrls.add(SERVICEURL.addParameter(MOCK_KEY, "true")); - registryDirectory2.notify(serviceUrls); - - Assertions.assertEquals("true", registryDirectory2.getConsumerUrl().getParameter("mock")); - } - } - - /** - * When destroying, RegistryDirectory should: 1. be disconnected from Registry 2. destroy all invokers - */ - @Test - public void testDestroy() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1,getXXX2,getXXX3")); - - registryDirectory.notify(serviceUrls); - List invokers = registryDirectory.list(invocation); - Assertions.assertTrue(registryDirectory.isAvailable()); - Assertions.assertTrue(invokers.get(0).isAvailable()); - - registryDirectory.destroy(); - Assertions.assertFalse(registryDirectory.isAvailable()); - Assertions.assertFalse(invokers.get(0).isAvailable()); - registryDirectory.destroy(); - - List> cachedInvokers = registryDirectory.getInvokers(); - Map> urlInvokerMap = registryDirectory.getUrlInvokerMap(); - - Assertions.assertNull(cachedInvokers); - Assertions.assertEquals(0, urlInvokerMap.size()); - // List urls = mockRegistry.getSubscribedUrls(); - - RpcInvocation inv = new RpcInvocation(); - try { - registryDirectory.list(inv); - fail(); - } catch (RpcException e) { - Assertions.assertTrue(e.getMessage().contains("already destroyed")); - } - } - - @Test - public void testDestroy_WithDestroyRegistry() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - CountDownLatch latch = new CountDownLatch(1); - registryDirectory.setRegistry(new MockRegistry(latch)); - registryDirectory.subscribe(URL.valueOf("consumer://" + NetUtils.getLocalHost() + "/DemoService?category=providers")); - registryDirectory.destroy(); - Assertions.assertEquals(0, latch.getCount()); - } - - @Test - public void testDestroy_WithDestroyRegistry_WithError() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - registryDirectory.setRegistry(new MockRegistry(true)); - registryDirectory.destroy(); - } - - @Test - public void testDubbo1UrlWithGenericInvocation() { - - RegistryDirectory registryDirectory = getRegistryDirectory(); - - List serviceUrls = new ArrayList(); - URL serviceURL = SERVICEURL_DUBBO_NOPATH.addParameter("methods", "getXXX1,getXXX2,getXXX3"); - serviceUrls.add(serviceURL); - - registryDirectory.notify(serviceUrls); - - // Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException; - invocation = new RpcInvocation($INVOKE, GenericService.class.getName(), new Class[]{String.class, String[].class, Object[].class}, - new Object[]{"getXXX1", "", new Object[]{}}); - - List invokers = registryDirectory.list(invocation); - - Assertions.assertEquals(1, invokers.size()); -// Assertions.assertEquals( -// serviceURL.setPath(service).addParameters("check", "false", "interface", DemoService.class.getName(), REMOTE_APPLICATION_KEY, serviceURL.getParameter(APPLICATION_KEY)) -// , invokers.get(0).getUrl() -// ); - - } - - /** - * When the first arg of a method is String or Enum, Registry server can do parameter-value-based routing. - */ - @Disabled("Parameter routing is not available at present.") - @Test - public void testParmeterRoute() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1.napoli")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1.MORGAN,getXXX2")); - serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1.morgan,getXXX2,getXXX3")); - - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation($INVOKE, GenericService.class.getName(), - new Class[]{String.class, String[].class, Object[].class}, - new Object[]{"getXXX1", new String[]{"Enum"}, new Object[]{Param.MORGAN}}); - - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - } - - /** - * Empty notify cause forbidden, non-empty notify cancels forbidden state - */ - @Test - public void testEmptyNotifyCauseForbidden() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - List invokers = null; - - List serviceUrls = new ArrayList(); - registryDirectory.notify(serviceUrls); - - RpcInvocation inv = new RpcInvocation(); - try { - invokers = registryDirectory.list(inv); - } catch (RpcException e) { - Assertions.assertEquals(RpcException.FORBIDDEN_EXCEPTION, e.getCode()); - Assertions.assertFalse(registryDirectory.isAvailable()); - } - - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1,getXXX2,getXXX3")); - - registryDirectory.notify(serviceUrls); - inv.setMethodName("getXXX2"); - invokers = registryDirectory.list(inv); - Assertions.assertTrue(registryDirectory.isAvailable()); - Assertions.assertEquals(3, invokers.size()); - } - - /** - * 1. notify twice, the second time notified router rules should completely replace the former one. 2. notify with - * no router url, do nothing to current routers 3. notify with only one router url, with router=clean, clear all - * current routers - */ - @Test - public void testNotifyRouterUrls() { - if (isScriptUnsupported) return; - RegistryDirectory registryDirectory = getRegistryDirectory(); - URL routerurl = URL.valueOf(ROUTE_PROTOCOL + "://127.0.0.1:9096/"); - URL routerurl2 = URL.valueOf(ROUTE_PROTOCOL + "://127.0.0.1:9097/"); - - List serviceUrls = new ArrayList(); - // without ROUTER_KEY, the first router should not be created. - serviceUrls.add(routerurl.addParameter(CATEGORY_KEY, ROUTERS_CATEGORY).addParameter(TYPE_KEY, "javascript").addParameter(ROUTER_KEY, "notsupported").addParameter(RULE_KEY, "function test1(){}")); - serviceUrls.add(routerurl2.addParameter(CATEGORY_KEY, ROUTERS_CATEGORY).addParameter(TYPE_KEY, "javascript").addParameter(ROUTER_KEY, - ScriptRouterFactory.NAME).addParameter(RULE_KEY, - "function test1(){}")); - - // FIXME - /*registryDirectory.notify(serviceUrls); - RouterChain routerChain = registryDirectory.getRouterChain(); - //default invocation selector - Assertions.assertEquals(1 + 1, routers.size()); - Assertions.assertTrue(ScriptRouter.class == routers.get(1).getClass() || ScriptRouter.class == routers.get(0).getClass()); - - registryDirectory.notify(new ArrayList()); - routers = registryDirectory.getRouters(); - Assertions.assertEquals(1 + 1, routers.size()); - Assertions.assertTrue(ScriptRouter.class == routers.get(1).getClass() || ScriptRouter.class == routers.get(0).getClass()); - - serviceUrls.clear(); - serviceUrls.add(routerurl.addParameter(Constants.ROUTER_KEY, Constants.ROUTER_TYPE_CLEAR)); - registryDirectory.notify(serviceUrls); - routers = registryDirectory.getRouters(); - Assertions.assertEquals(0 + 1, routers.size());*/ - } - - /** - * Test whether the override rule have a high priority - * Scene: first push override , then push invoker - */ - @Test - public void testNotifyoverrideUrls_beforeInvoker() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - List overrideUrls = new ArrayList(); - overrideUrls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); - registryDirectory.notify(overrideUrls); - //The registry is initially pushed to override only, and the dirctory state should be false because there is no invoker. - Assertions.assertFalse(registryDirectory.isAvailable()); - - //After pushing two provider, the directory state is restored to true - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("timeout", "1000")); - serviceUrls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10")); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - //Start validation of parameter values - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - Assertions.assertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority"); - Assertions.assertEquals("5", invokers.get(0).getUrl().getParameter("connections"), "override rute must be first priority"); - } - - /** - * Test whether the override rule have a high priority - * Scene: first push override , then push invoker - */ - @Test - public void testNotifyoverrideUrls_afterInvoker() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - - //After pushing two provider, the directory state is restored to true - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("timeout", "1000")); - serviceUrls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10")); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - List overrideUrls = new ArrayList(); - overrideUrls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); - registryDirectory.notify(overrideUrls); - - //Start validation of parameter values - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - Assertions.assertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority"); - Assertions.assertEquals("5", invokers.get(0).getUrl().getParameter("connections"), "override rute must be first priority"); - } - - /** - * Test whether the override rule have a high priority - * Scene: push override rules with invoker - */ - @Test - public void testNotifyoverrideUrls_withInvoker() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.addParameter("timeout", "1000")); - durls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10")); - durls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); - - registryDirectory.notify(durls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - //Start validation of parameter values - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - Assertions.assertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority"); - Assertions.assertEquals("5", invokers.get(0).getUrl().getParameter("connections"), "override rute must be first priority"); - } - - /** - * Test whether the override rule have a high priority - * Scene: the rules of the push are the same as the parameters of the provider - * Expectation: no need to be re-referenced - */ - @Test - public void testNotifyoverrideUrls_Nouse() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.addParameter("timeout", "1"));//One is the same, one is different - durls.add(SERVICEURL2.addParameter("timeout", "1").addParameter("connections", "5")); - registryDirectory.notify(durls); - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - Map> map = new HashMap<>(); - map.put(invokers.get(0).getUrl().getAddress(), invokers.get(0)); - map.put(invokers.get(1).getUrl().getAddress(), invokers.get(1)); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5")); - registryDirectory.notify(durls); - Assertions.assertTrue(registryDirectory.isAvailable()); - - invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - Map> map2 = new HashMap<>(); - map2.put(invokers.get(0).getUrl().getAddress(), invokers.get(0)); - map2.put(invokers.get(1).getUrl().getAddress(), invokers.get(1)); - - //The parameters are different and must be rereferenced. - Assertions.assertNotSame(map.get(SERVICEURL.getAddress()), map2.get(SERVICEURL.getAddress()), - "object should not same"); - - //The parameters can not be rereferenced - Assertions.assertSame(map.get(SERVICEURL2.getAddress()), map2.get(SERVICEURL2.getAddress()), - "object should not same"); - } - - /** - * Test override rules for a certain provider - */ - @Test - public void testNofityOverrideUrls_Provider() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1").addParameter(SIDE_KEY, CONSUMER_SIDE));//One is the same, one is different - durls.add(SERVICEURL2.setHost("10.20.30.141").addParameter("timeout", "2").addParameter(SIDE_KEY, CONSUMER_SIDE)); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=3")); - durls.add(URL.valueOf("override://10.20.30.141:9092?timeout=4")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - URL aUrl = invokers.get(0).getUrl(); - URL bUrl = invokers.get(1).getUrl(); - Assertions.assertEquals(aUrl.getHost().equals("10.20.30.140") ? "3" : "4", aUrl.getParameter("timeout")); - Assertions.assertEquals(bUrl.getHost().equals("10.20.30.141") ? "4" : "3", bUrl.getParameter("timeout")); - } - - /** - * Test cleanup override rules, and sent remove rules and other override rules - * Whether the test can be restored to the providerUrl when it is pushed - */ - @Test - public void testNofityOverrideUrls_Clean1() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1")); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=1000")); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=3")); - durls.add(URL.valueOf("override://0.0.0.0")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - Invoker aInvoker = invokers.get(0); - //Need to be restored to the original providerUrl - Assertions.assertEquals("3", aInvoker.getUrl().getParameter("timeout")); - } - - /** - * The test clears the override rule and only sends the override cleanup rules - * Whether the test can be restored to the providerUrl when it is pushed - */ - @Test - public void testNofityOverrideUrls_CleanOnly() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1")); - registryDirectory.notify(durls); - Assertions.assertNull(registryDirectory.getConsumerUrl().getParameter("mock")); - - //override - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=1000&mock=fail")); - registryDirectory.notify(durls); - List> invokers = registryDirectory.list(invocation); - Invoker aInvoker = invokers.get(0); - Assertions.assertEquals("1000", aInvoker.getUrl().getParameter("timeout")); - Assertions.assertEquals("fail", registryDirectory.getConsumerUrl().getParameter("mock")); - - //override clean - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0/dubbo.test.api.HelloService")); - registryDirectory.notify(durls); - invokers = registryDirectory.list(invocation); - aInvoker = invokers.get(0); - //Need to be restored to the original providerUrl - Assertions.assertEquals("1", aInvoker.getUrl().getParameter("timeout")); - - Assertions.assertNull(registryDirectory.getConsumerUrl().getParameter("mock")); - } - - /** - * Test the simultaneous push to clear the override and the override for a certain provider - * See if override can take effect - */ - @Test - public void testNofityOverrideUrls_CleanNOverride() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1")); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?timeout=3")); - durls.add(URL.valueOf("override://0.0.0.0")); - durls.add(URL.valueOf("override://10.20.30.140:9091?timeout=4")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - Invoker aInvoker = invokers.get(0); - Assertions.assertEquals("4", aInvoker.getUrl().getParameter("timeout")); - } - - /** - * Test override disables all service providers through enable=false - * Expectation: all service providers can not be disabled through override. - */ - @Test - public void testNofityOverrideUrls_disabled_allProvider() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140")); - durls.add(SERVICEURL.setHost("10.20.30.141")); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://0.0.0.0?" + ENABLED_KEY + "=false")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - //All service providers can not be disabled through override. - Assertions.assertEquals(2, invokers.size()); - } - - /** - * Test override disables a specified service provider through enable=false - * It is expected that a specified service provider can be disable. - */ - @Test - public void testNofityOverrideUrls_disabled_specifiedProvider() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140")); - durls.add(SERVICEURL.setHost("10.20.30.141")); - registryDirectory.notify(durls); - - durls = new ArrayList(); - durls.add(URL.valueOf("override://10.20.30.140:9091?" + DISABLED_KEY + "=true")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - Assertions.assertEquals("10.20.30.141", invokers.get(0).getUrl().getHost()); - - durls = new ArrayList(); - durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + CATEGORY_KEY + "=" + CONFIGURATORS_CATEGORY)); - registryDirectory.notify(durls); - List> invokers2 = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers2.size()); - } - - /** - * Test override disables a specified service provider through enable=false - * It is expected that a specified service provider can be disable. - */ - @Test - public void testNofity_To_Decrease_provider() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140")); - durls.add(SERVICEURL.setHost("10.20.30.141")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140")); - registryDirectory.notify(durls); - List> invokers2 = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers2.size()); - Assertions.assertEquals("10.20.30.140", invokers2.get(0).getUrl().getHost()); - - durls = new ArrayList(); - durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + CATEGORY_KEY + "=" + CONFIGURATORS_CATEGORY)); - registryDirectory.notify(durls); - List> invokers3 = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers3.size()); - } - - /** - * Test override disables a specified service provider through enable=false - * It is expected that a specified service provider can be disable. - */ - @Test - public void testNofity_disabled_specifiedProvider() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - invocation = new RpcInvocation(); - - // Initially disable - List durls = new ArrayList(); - durls.add(SERVICEURL.setHost("10.20.30.140").addParameter(ENABLED_KEY, "false")); - durls.add(SERVICEURL.setHost("10.20.30.141")); - registryDirectory.notify(durls); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - Assertions.assertEquals("10.20.30.141", invokers.get(0).getUrl().getHost()); - - //Enabled by override rule - durls = new ArrayList(); - durls.add(URL.valueOf("override://10.20.30.140:9091?" + DISABLED_KEY + "=false")); - registryDirectory.notify(durls); - List> invokers2 = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers2.size()); - } - - @Test - public void testNotifyRouterUrls_Clean() { - if (isScriptUnsupported) return; - RegistryDirectory registryDirectory = getRegistryDirectory(); - URL routerurl = URL.valueOf(ROUTE_PROTOCOL + "://127.0.0.1:9096/").addParameter(ROUTER_KEY, - "javascript").addParameter(RULE_KEY, - "function test1(){}").addParameter(ROUTER_KEY, - "script"); // FIX - // BAD - - List serviceUrls = new ArrayList(); - // without ROUTER_KEY, the first router should not be created. - serviceUrls.add(routerurl); - registryDirectory.notify(serviceUrls); - // FIXME - /* List routers = registryDirectory.getRouters(); - Assertions.assertEquals(1 + 1, routers.size()); - - serviceUrls.clear(); - serviceUrls.add(routerurl.addParameter(Constants.ROUTER_KEY, Constants.ROUTER_TYPE_CLEAR)); - registryDirectory.notify(serviceUrls); - routers = registryDirectory.getRouters(); - Assertions.assertEquals(0 + 1, routers.size());*/ - } - - /** - * Test mock provider distribution - */ - @Test - public void testNotify_MockProviderOnly() { - RegistryDirectory registryDirectory = getRegistryDirectory(); - - List serviceUrls = new ArrayList(); - serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1")); - serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2")); - serviceUrls.add(SERVICEURL.setProtocol(MOCK_PROTOCOL)); - - registryDirectory.notify(serviceUrls); - Assertions.assertTrue(registryDirectory.isAvailable()); - invocation = new RpcInvocation(); - - List invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - - RpcInvocation mockinvocation = new RpcInvocation(); - mockinvocation.setAttachment(INVOCATION_NEED_MOCK, "true"); - invokers = registryDirectory.list(mockinvocation); - Assertions.assertEquals(1, invokers.size()); - } - - // mock protocol - - //Test the matching of protocol and select only the matched protocol for refer - @Test - public void test_Notified_acceptProtocol0() { - URL errorPathUrl = URL.valueOf("notsupport:/xxx?refer=" + URL.encode("interface=" + service)); - RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl); - List serviceUrls = new ArrayList(); - URL dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true&methods=getXXX"); - URL dubbo2URL = URL.valueOf("injvm://127.0.0.1:9099?lazy=true&methods=getXXX"); - serviceUrls.add(dubbo1URL); - serviceUrls.add(dubbo2URL); - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - } - - //Test the matching of protocol and select only the matched protocol for refer - @Test - public void test_Notified_acceptProtocol1() { - URL errorPathUrl = URL.valueOf("notsupport:/xxx"); - errorPathUrl = errorPathUrl.addParameterAndEncoded(REFER_KEY, "interface=" + service + "&protocol=dubbo"); - RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl); - List serviceUrls = new ArrayList(); - URL dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true&methods=getXXX"); - URL dubbo2URL = URL.valueOf("injvm://127.0.0.1:9098?lazy=true&methods=getXXX"); - serviceUrls.add(dubbo1URL); - serviceUrls.add(dubbo2URL); - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(1, invokers.size()); - } - - //Test the matching of protocol and select only the matched protocol for refer - @Test - public void test_Notified_acceptProtocol2() { - URL errorPathUrl = URL.valueOf("notsupport:/xxx"); - errorPathUrl = errorPathUrl.addParameterAndEncoded(REFER_KEY, "interface=" + service + "&protocol=dubbo,injvm"); - RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl); - List serviceUrls = new ArrayList(); - URL dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true&methods=getXXX"); - URL dubbo2URL = URL.valueOf("injvm://127.0.0.1:9099?lazy=true&methods=getXXX"); - serviceUrls.add(dubbo1URL); - serviceUrls.add(dubbo2URL); - registryDirectory.notify(serviceUrls); - - invocation = new RpcInvocation(); - - List> invokers = registryDirectory.list(invocation); - Assertions.assertEquals(2, invokers.size()); - } - - @Test - public void test_Notified_withGroupFilter() { - URL directoryUrl = noMeaningUrl.addParameterAndEncoded(REFER_KEY, "interface" + service + "&group=group1,group2"); - RegistryDirectory directory = this.getRegistryDirectory(directoryUrl); - URL provider1 = URL.valueOf("dubbo://10.134.108.1:20880/" + service + "?methods=getXXX&group=group1&mock=false&application=mockApplication"); - URL provider2 = URL.valueOf("dubbo://10.134.108.1:20880/" + service + "?methods=getXXX&group=group2&mock=false&application=mockApplication"); - - List providers = new ArrayList<>(); - providers.add(provider1); - providers.add(provider2); - directory.notify(providers); - - invocation = new RpcInvocation(); - invocation.setMethodName("getXXX"); - List> invokers = directory.list(invocation); - - Assertions.assertEquals(2, invokers.size()); - Assertions.assertTrue(invokers.get(0) instanceof MockClusterInvoker); - Assertions.assertTrue(invokers.get(1) instanceof MockClusterInvoker); - - directoryUrl = noMeaningUrl.addParameterAndEncoded(REFER_KEY, "interface" + service + "&group=group1"); - directory = this.getRegistryDirectory(directoryUrl); - directory.notify(providers); - - invokers = directory.list(invocation); - - Assertions.assertEquals(2, invokers.size()); - Assertions.assertFalse(invokers.get(0) instanceof MockClusterInvoker); - Assertions.assertFalse(invokers.get(1) instanceof MockClusterInvoker); - } - - enum Param { - MORGAN, - } - - private interface DemoService { - } - - private static class MockRegistry implements Registry { - - CountDownLatch latch; - boolean destroyWithError; - - public MockRegistry(CountDownLatch latch) { - this.latch = latch; - } - - public MockRegistry(boolean destroyWithError) { - this.destroyWithError = destroyWithError; - } - - @Override - public void register(URL url) { - - } - - @Override - public void unregister(URL url) { - - } - - @Override - public void subscribe(URL url, NotifyListener listener) { - - } - - @Override - public void unsubscribe(URL url, NotifyListener listener) { - if (latch != null) latch.countDown(); - } - - @Override - public List lookup(URL url) { - return null; - } - - public URL getUrl() { - return null; - } - - @Override - public boolean isAvailable() { - return true; - } - - @Override - public void destroy() { - if (destroyWithError) { - throw new RpcException("test exception ignore."); - } - } - } -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java deleted file mode 100644 index 8d08b3dfdb..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryProtocolTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.RegistryFactory; -import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.registry.integration.RegistryProtocol; -import org.apache.dubbo.registry.support.AbstractRegistry; -import org.apache.dubbo.remoting.exchange.ExchangeClient; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.model.ApplicationModel; -import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.apache.dubbo.rpc.protocol.AbstractInvoker; -import org.apache.dubbo.rpc.protocol.dubbo.DubboInvoker; -import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; - -import org.apache.commons.lang3.ArrayUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.apache.dubbo.registry.integration.RegistryProtocol.DEFAULT_REGISTER_PROVIDER_KEYS; -import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * RegistryProtocolTest - */ -public class RegistryProtocolTest { - - static { - SimpleRegistryExporter.exportIfAbsent(9090); - } - - final String service = DemoService.class.getName() + ":1.0.0"; - final String serviceUrl = "dubbo://127.0.0.1:9453/" + service + "?notify=true&methods=test1,test2&side=con&side=consumer"; - final URL registryUrl = URL.valueOf("registry://127.0.0.1:9090/"); - final private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - - public static RegistryProtocol getRegistryProtocol() { - return RegistryProtocol.getRegistryProtocol(); - } - - @BeforeEach - public void setUp() { - ApplicationModel.setApplication("RegistryProtocolTest"); - ApplicationModel.getServiceRepository().registerService(RegistryService.class); - } - - @Test - public void testDefaultPort() { - RegistryProtocol registryProtocol = getRegistryProtocol(); - assertEquals(9090, registryProtocol.getDefaultPort()); - } - - @Test - public void testExportUrlNull() { - Assertions.assertThrows(IllegalArgumentException.class, () -> { - RegistryProtocol registryProtocol = getRegistryProtocol(); -// registryProtocol.setCluster(new FailfastCluster()); - - Protocol dubboProtocol = DubboProtocol.getDubboProtocol(); - registryProtocol.setProtocol(dubboProtocol); - Invoker invoker = new DubboInvoker(DemoService.class, - registryUrl, new ExchangeClient[]{new MockedClient("10.20.20.20", 2222, true)}); - registryProtocol.export(invoker); - }); - } - - @Test - public void testExport() { - RegistryProtocol registryProtocol = getRegistryProtocol(); -// registryProtocol.setCluster(new FailfastCluster()); - registryProtocol.setRegistryFactory(ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension()); - - Protocol dubboProtocol = DubboProtocol.getDubboProtocol(); - registryProtocol.setProtocol(dubboProtocol); - URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl); - DubboInvoker invoker = new DubboInvoker(DemoService.class, - newRegistryUrl, new ExchangeClient[]{new MockedClient("10.20.20.20", 2222, true)}); - Exporter exporter = registryProtocol.export(invoker); - Exporter exporter2 = registryProtocol.export(invoker); - //The same invoker, exporter that multiple exported are different - Assertions.assertNotSame(exporter, exporter2); - exporter.unexport(); - exporter2.unexport(); - - } - -// @Test -// public void testNotifyOverride() throws Exception { -// URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl); -// Invoker invoker = new MockInvoker(RegistryProtocolTest.class, newRegistryUrl); -// -// ServiceDescriptor descriptor = ApplicationModel.getServiceRepository().registerService(DemoService.class); -// ApplicationModel.getServiceRepository().registerProvider(service, new DemoServiceImpl(), descriptor, null, null); -// -// Exporter exporter = protocol.export(invoker); -// RegistryProtocol rprotocol = getRegistryProtocol(); -// NotifyListener listener = getListener(rprotocol); -// List urls = new ArrayList(); -// urls.add(URL.valueOf("override://0.0.0.0/?timeout=1000")); -// urls.add(URL.valueOf("override://0.0.0.0/" + service + "?timeout=100")); -// urls.add(URL.valueOf("override://0.0.0.0/" + service + "?x=y")); -// listener.notify(urls); -// -// assertTrue(exporter.getInvoker().isAvailable()); -// assertEquals("100", exporter.getInvoker().getUrl().getParameter("timeout")); -// assertEquals("y", exporter.getInvoker().getUrl().getParameter("x")); -// -// exporter.unexport(); -//// int timeout = ConfigUtils.getServerShutdownTimeout(); -//// Thread.sleep(timeout + 1000); -//// assertEquals(false, exporter.getInvoker().isAvailable()); -// destroyRegistryProtocol(); -// -// } - - - /** - * The name of the service does not match and can't override invoker - * Service name matching, service version number mismatch - */ - @Test - public void testNotifyOverride_notmatch() throws Exception { - URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl); - Invoker invoker = new MockInvoker(RegistryProtocolTest.class, newRegistryUrl); - - ServiceDescriptor descriptor = ApplicationModel.getServiceRepository().registerService(DemoService.class); - ApplicationModel.getServiceRepository().registerProvider(service, new DemoServiceImpl(), descriptor, null, null); - - Exporter exporter = protocol.export(invoker); - RegistryProtocol rprotocol = getRegistryProtocol(); - NotifyListener listener = getListener(rprotocol); - List urls = new ArrayList(); - urls.add(URL.valueOf("override://0.0.0.0/org.apache.dubbo.registry.protocol.HackService?timeout=100")); - listener.notify(urls); - assertTrue(exporter.getInvoker().isAvailable()); - assertNull(exporter.getInvoker().getUrl().getParameter("timeout")); - exporter.unexport(); - destroyRegistryProtocol(); - } - - /** - * Test destory registry, exporter can be normal by destroyed - */ - @Test - public void testDestoryRegistry() { - URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl); - Invoker invoker = new MockInvoker(RegistryProtocolTest.class, newRegistryUrl); - Exporter exporter = protocol.export(invoker); - destroyRegistryProtocol(); - try { - Thread.sleep(ConfigurationUtils.getServerShutdownTimeout() + 100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - assertFalse(exporter.getInvoker().isAvailable()); - - } - - @Test - public void testGetParamsToRegistry() { - RegistryProtocol registryProtocol = getRegistryProtocol(); - String[] additionalParams = new String[]{"key1", "key2"}; - String[] registryParams = registryProtocol.getParamsToRegistry(DEFAULT_REGISTER_PROVIDER_KEYS, additionalParams); - String[] expectParams = ArrayUtils.addAll(DEFAULT_REGISTER_PROVIDER_KEYS, additionalParams); - Assertions.assertArrayEquals(expectParams, registryParams); - } - - private void destroyRegistryProtocol() { - Protocol registry = getRegistryProtocol(); - registry.destroy(); - } - - private NotifyListener getListener(RegistryProtocol protocol) throws Exception { - return protocol.getOverrideListeners().values().iterator().next(); - } - - static class MockInvoker extends AbstractInvoker { - public MockInvoker(Class type, URL url) { - super(type, url); - } - - @Override - protected Result doInvoke(Invocation invocation) throws Throwable { - //do nothing - return null; - } - } - - static class MockRegistry extends AbstractRegistry { - - public MockRegistry(URL url) { - super(url); - } - - @Override - public boolean isAvailable() { - return true; - } - } - -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryStatusCheckerTest.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryStatusCheckerTest.java deleted file mode 100644 index 3f7d5c68c7..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/RegistryStatusCheckerTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.status.Status; -import org.apache.dubbo.registry.RegistryFactory; -import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.registry.status.RegistryStatusChecker; -import org.apache.dubbo.registry.support.AbstractRegistryFactory; -import org.apache.dubbo.rpc.model.ApplicationModel; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -/** - * StatusTest - * - */ -public class RegistryStatusCheckerTest { - - static { - SimpleRegistryExporter.exportIfAbsent(9090); - SimpleRegistryExporter.exportIfAbsent(9091); - } - - URL registryUrl = URL.valueOf("dubbo://cat:cat@127.0.0.1:9090/"); - URL registryUrl2 = URL.valueOf("dubbo://cat:cat@127.0.0.1:9091"); - - @BeforeEach - public void setUp() { - AbstractRegistryFactory.clearRegistryNotDestroy(); - ApplicationModel.getServiceRepository().registerService(RegistryService.class); - } - - @Test - public void testCheckUnknown() { - assertEquals(Status.Level.UNKNOWN, new RegistryStatusChecker().check().getLevel()); - } - - @Test - public void testCheckOK() { - ApplicationModel.setApplication("testCheckOK"); - ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension().getRegistry(registryUrl); - ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension().getRegistry(registryUrl2); - assertEquals(Status.Level.OK, new RegistryStatusChecker().check().getLevel()); - String message = new RegistryStatusChecker().check().getMessage(); - Assertions.assertTrue(message.contains(registryUrl.getAddress() + "(connected)")); - Assertions.assertTrue(message.contains(registryUrl2.getAddress() + "(connected)")); - } -} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java deleted file mode 100644 index 9a0a95fa3f..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryExporter.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.URLBuilder; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.dubbo.rpc.model.ApplicationModel; -import org.apache.dubbo.rpc.model.ServiceDescriptor; -import org.apache.dubbo.rpc.model.ServiceRepository; - -import java.io.IOException; -import java.net.ServerSocket; - -import static org.apache.dubbo.common.constants.CommonConstants.CALLBACK_INSTANCES_LIMIT_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL; -import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; - -/** - * SimpleRegistryExporter - * - */ -public class SimpleRegistryExporter { - - private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - - private static final ProxyFactory PROXY_FACTORY = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - - public synchronized static Exporter exportIfAbsent(int port) { - try { - new ServerSocket(port).close(); - return export(port); - } catch (IOException e) { - return null; - } - } - - public static Exporter export(int port) { - return export(port, new SimpleRegistryService()); - } - - public static Exporter export(int port, RegistryService registryService) { - return protocol.export(PROXY_FACTORY.getInvoker(registryService, RegistryService.class, - new URLBuilder(DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.class.getName()) - .setPath(RegistryService.class.getName()) - .addParameter(INTERFACE_KEY, RegistryService.class.getName()) - .addParameter(CLUSTER_STICKY_KEY, "true") - .addParameter(CALLBACK_INSTANCES_LIMIT_KEY, "1000") - .addParameter("ondisconnect", "disconnect") - .addParameter("subscribe.1.callback", "true") - .addParameter("unsubscribe.1.callback", "false") - .build())); - } - - private void registerProvider(URL url, RegistryService registryService) { - ServiceRepository repository = ApplicationModel.getServiceRepository(); - ServiceDescriptor serviceDescriptor = repository.registerService(RegistryService.class); - repository.registerProvider( - url.getServiceKey(), - registryService, - serviceDescriptor, - null, - null - ); - } - -} diff --git a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryService.java b/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryService.java deleted file mode 100644 index 40c37b074d..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/java/org/apache/dubbo/registry/dubbo/SimpleRegistryService.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * 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.apache.dubbo.registry.dubbo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.common.utils.UrlUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.RegistryService; -import org.apache.dubbo.rpc.RpcContext; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - * SimpleRegistryService - * - */ -public class SimpleRegistryService extends AbstractRegistryService { - - private final static Logger logger = LoggerFactory.getLogger(SimpleRegistryService.class); - private final ConcurrentMap> remoteRegistered = new ConcurrentHashMap>(); - private final ConcurrentMap> remoteListeners = new ConcurrentHashMap>(); - private List registries; - - public SimpleRegistryService() { - - } - - @Override - public void register(String service, URL url) { - super.register(service, url); - String client = RpcContext.getContext().getRemoteAddressString(); - Map urls = remoteRegistered.computeIfAbsent(client, k -> new ConcurrentHashMap<>()); - urls.put(service, url); - notify(service, getRegistered().get(service)); - } - - @Override - public void unregister(String service, URL url) { - super.unregister(service, url); - String client = RpcContext.getContext().getRemoteAddressString(); - Map urls = remoteRegistered.get(client); - if (urls != null && urls.size() > 0) { - urls.remove(service); - } - notify(service, getRegistered().get(service)); - } - - @Override - public void subscribe(String service, URL url, NotifyListener listener) { - String client = RpcContext.getContext().getRemoteAddressString(); - if (logger.isInfoEnabled()) { - logger.info("[subscribe] service: " + service + ",client:" + client); - } - List urls = getRegistered().get(service); - if ((RegistryService.class.getName() + ":0.0.0").equals(service) - && (urls == null || urls.size() == 0)) { - register(service, new URL("dubbo", - NetUtils.getLocalHost(), - RpcContext.getContext().getLocalPort(), - org.apache.dubbo.registry.RegistryService.class.getName(), - url.getParameters())); - List rs = registries; - if (rs != null && rs.size() > 0) { - for (String registry : rs) { - register(service, UrlUtils.parseURL(registry, url.getParameters())); - } - } - } - super.subscribe(service, url, listener); - - Map listeners = remoteListeners.computeIfAbsent(client, k -> new ConcurrentHashMap<>()); - listeners.put(service, listener); - urls = getRegistered().get(service); - if (urls != null && urls.size() > 0) { - listener.notify(urls); - } - - - } - - @Override - public void unsubscribe(String service, URL url, NotifyListener listener) { - super.unsubscribe(service, url, listener); - String client = RpcContext.getContext().getRemoteAddressString(); - Map listeners = remoteListeners.get(client); - if (listeners != null && listeners.size() > 0) { - listeners.remove(service); - } - List urls = getRegistered().get(service); - if (urls != null && urls.size() > 0) { - listener.notify(urls); - } - } - - public void disconnect() { - String client = RpcContext.getContext().getRemoteAddressString(); - if (logger.isInfoEnabled()) { - logger.info("Disconnected " + client); - } - ConcurrentMap urls = remoteRegistered.get(client); - if (urls != null && urls.size() > 0) { - for (Map.Entry entry : urls.entrySet()) { - super.unregister(entry.getKey(), entry.getValue()); - } - } - Map listeners = remoteListeners.get(client); - if (listeners != null && listeners.size() > 0) { - for (Map.Entry entry : listeners.entrySet()) { - String service = entry.getKey(); - super.unsubscribe(service, new URL("subscribe", - RpcContext.getContext().getRemoteHost(), - RpcContext.getContext().getRemotePort(), - org.apache.dubbo.registry.RegistryService.class.getName(), getSubscribed(service)), entry.getValue()); - } - } - } - - public List getRegistries() { - return registries; - } - - public void setRegistries(List registries) { - this.registries = registries; - } - -} \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-default/src/test/resources/log4j.xml b/dubbo-registry/dubbo-registry-default/src/test/resources/log4j.xml deleted file mode 100644 index 91905fd10b..0000000000 --- a/dubbo-registry/dubbo-registry-default/src/test/resources/log4j.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-etcd3/pom.xml b/dubbo-registry/dubbo-registry-etcd3/pom.xml deleted file mode 100644 index 4464685274..0000000000 --- a/dubbo-registry/dubbo-registry-etcd3/pom.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - - - 4.0.0 - - dubbo-registry - org.apache.dubbo - ${revision} - ../pom.xml - - - dubbo-registry-etcd3 - jar - ${project.artifactId} - The etcd3 registry module of Dubbo project - - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-etcd3 - ${project.parent.version} - - - - - \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java deleted file mode 100644 index a15d7d561d..0000000000 --- a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistry.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * 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.apache.dubbo.registry.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ConcurrentHashSet; -import org.apache.dubbo.common.utils.UrlUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.support.FailbackRegistry; -import org.apache.dubbo.remoting.etcd.ChildListener; -import org.apache.dubbo.remoting.etcd.Constants; -import org.apache.dubbo.remoting.etcd.EtcdClient; -import org.apache.dubbo.remoting.etcd.EtcdTransporter; -import org.apache.dubbo.remoting.etcd.StateListener; -import org.apache.dubbo.remoting.etcd.option.OptionUtil; -import org.apache.dubbo.rpc.RpcException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; -import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; -import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; -import static org.apache.dubbo.remoting.Constants.CHECK_KEY; - - -/** - * Support for ectd3 registry. - */ -public class EtcdRegistry extends FailbackRegistry { - - private final static Logger logger = LoggerFactory.getLogger(EtcdRegistry.class); - - private final static int DEFAULT_ETCD_PORT = 2379; - - private final static String DEFAULT_ROOT = "dubbo"; - - private final String root; - - private final Set anyServices = new ConcurrentHashSet<>(); - - private final ConcurrentMap> etcdListeners = new ConcurrentHashMap<>(); - private final EtcdClient etcdClient; - - public EtcdRegistry(URL url, EtcdTransporter etcdTransporter) { - super(url); - if (url.isAnyHost()) { - throw new IllegalStateException("registry address is invalid, actual: '" + url.getHost() + "'"); - } - String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); - if (!group.startsWith(PATH_SEPARATOR)) { - group = PATH_SEPARATOR + group; - } - this.root = group; - etcdClient = etcdTransporter.connect(url); - - etcdClient.addStateListener(state -> { - if (state == StateListener.CONNECTED) { - try { - recover(); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - } - }); - } - - protected static String appendDefaultPort(String address) { - if (address != null && address.length() > 0) { - int i = address.indexOf(':'); - if (i < 0) { - return address + ":" + DEFAULT_ETCD_PORT; - } else if (Integer.parseInt(address.substring(i + 1)) == 0) { - return address.substring(0, i + 1) + DEFAULT_ETCD_PORT; - } - } - return address; - } - - @Override - public void doRegister(URL url) { - try { - String path = toUrlPath(url); - if (url.getParameter(DYNAMIC_KEY, true)) { - etcdClient.createEphemeral(path); - return; - } - etcdClient.create(path); - } catch (Throwable e) { - throw new RpcException("Failed to register " + url + " to etcd " + getUrl() - + ", cause: " + (OptionUtil.isProtocolError(e) - ? "etcd3 registry may not be supported yet or etcd3 registry is not available." - : e.getMessage()), e); - } - } - - @Override - public void doUnregister(URL url) { - try { - String path = toUrlPath(url); - etcdClient.delete(path); - } catch (Throwable e) { - throw new RpcException("Failed to unregister " + url + " to etcd " + getUrl() + ", cause: " + e.getMessage(), e); - } - } - - @Override - public void doSubscribe(URL url, NotifyListener listener) { - try { - if (ANY_VALUE.equals(url.getServiceInterface())) { - String root = toRootPath(); - - /* - * if we are interested in all interfaces, - * find out the current container or create one for the url, put or get only once. - */ - ConcurrentMap listeners = - Optional.ofNullable(etcdListeners.get(url)) - .orElseGet(() -> { - ConcurrentMap container, prev; - prev = etcdListeners.putIfAbsent(url, container = new ConcurrentHashMap<>()); - return prev != null ? prev : container; - }); - - /* - * if we have no interface watcher listener, - * find the current listener or create one for the current root, put or get only once. - */ - ChildListener interfaceListener = - Optional.ofNullable(listeners.get(listener)) - .orElseGet(() -> { - ChildListener childListener, prev; - prev = listeners.putIfAbsent(listener, childListener = (parentPath, currentChildren) -> { - /* - * because etcd3 does not support direct children watch events, - * we should filter not interface events. if we watch /dubbo - * and /dubbo/interface, when we put a key-value pair {/dubbo/interface/hello hello}, - * we will got events in watching path /dubbo. - */ - for (String child : currentChildren) { - child = URL.decode(child); - if (!anyServices.contains(child)) { - anyServices.add(child); - /* - * if new interface event arrived, we watch their direct children, - * eg: /dubbo/interface, /dubbo/interface and so on. - */ - subscribe(url.setPath(child).addParameters(INTERFACE_KEY, child, - CHECK_KEY, String.valueOf(false)), listener); - } - } - }); - return prev != null ? prev : childListener; - }); - - etcdClient.create(root); - /* - * at the first time, we want to pull already interface and then watch their direct children, - * eg: /dubbo/interface, /dubbo/interface and so on. - */ - List services = etcdClient.addChildListener(root, interfaceListener); - for (String service : services) { - service = URL.decode(service); - anyServices.add(service); - subscribe(url.setPath(service).addParameters(INTERFACE_KEY, service, - CHECK_KEY, String.valueOf(false)), listener); - } - } else { - List urls = new ArrayList<>(); - for (String path : toCategoriesPath(url)) { - - /* - * if we are interested in special categories (providers, consumers, routers and so on), - * we find out the current container or create one for the url, put or get only once. - */ - ConcurrentMap listeners = - Optional.ofNullable(etcdListeners.get(url)) - .orElseGet(() -> { - ConcurrentMap container, prev; - prev = etcdListeners.putIfAbsent(url, - container = new ConcurrentHashMap<>()); - return prev != null ? prev : container; - }); - - /* - * if we have no category watcher listener, - * we find out the current listener or create one for the current category, put or get only once. - */ - ChildListener childListener = - Optional.ofNullable(listeners.get(listener)) - .orElseGet(() -> { - ChildListener watchListener, prev; - prev = listeners.putIfAbsent(listener, watchListener = (parentPath, currentChildren) -> EtcdRegistry.this.notify(url, listener, - toUrlsWithEmpty(url, parentPath, currentChildren))); - return prev != null ? prev : watchListener; - }); - - etcdClient.create(path); - /* - * at the first time, we want to pull already category and then watch their direct children, - * eg: /dubbo/interface/providers, /dubbo/interface/consumers and so on. - */ - List children = etcdClient.addChildListener(path, childListener); - if (children != null) { - urls.addAll(toUrlsWithEmpty(url, path, children)); - } - } - notify(url, listener, urls); - } - } catch (Throwable e) { - throw new RpcException("Failed to subscribe " + url + " to etcd " + getUrl() - + ", cause: " + (OptionUtil.isProtocolError(e) - ? "etcd3 registry may not be supported yet or etcd3 registry is not available." - : e.getMessage()), e); - } - } - - @Override - public void doUnsubscribe(URL url, NotifyListener listener) { - ConcurrentMap listeners = etcdListeners.get(url); - if (listeners != null) { - ChildListener etcdListener = listeners.get(listener); - if (etcdListener != null) { - // maybe url has many subscribed paths - for (String path : toUnsubscribedPath(url)) { - etcdClient.removeChildListener(path, etcdListener); - } - } - } - } - - @Override - public boolean isAvailable() { - return etcdClient.isConnected(); - } - - @Override - public void destroy() { - super.destroy(); - try { - etcdClient.close(); - } catch (Exception e) { - logger.warn("Failed to close etcd client " + getUrl() + ", cause: " + e.getMessage(), e); - } - } - - protected String toRootDir() { - if (root.startsWith(PATH_SEPARATOR)) { - return root; - } - return PATH_SEPARATOR + root; - } - - protected String toRootPath() { - return root; - } - - protected String toServicePath(URL url) { - String name = url.getServiceInterface(); - if (ANY_VALUE.equals(name)) { - return toRootPath(); - } - return toRootDir() + PATH_SEPARATOR + URL.encode(name); - } - - protected String[] toCategoriesPath(URL url) { - String[] categories; - if (ANY_VALUE.equals(url.getParameter(CATEGORY_KEY))) { - categories = new String[]{PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY}; - } else { - categories = url.getParameter(CATEGORY_KEY, new String[]{DEFAULT_CATEGORY}); - } - String[] paths = new String[categories.length]; - for (int i = 0; i < categories.length; i++) { - paths[i] = toServicePath(url) + PATH_SEPARATOR + categories[i]; - } - return paths; - } - - protected String toCategoryPath(URL url) { - return toServicePath(url) + PATH_SEPARATOR + url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); - } - - protected String toUrlPath(URL url) { - return toCategoryPath(url) + PATH_SEPARATOR + URL.encode(url.toFullString()); - } - - protected List toUnsubscribedPath(URL url) { - List categories = new ArrayList<>(); - if (ANY_VALUE.equals(url.getServiceInterface())) { - String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); - if (!group.startsWith(PATH_SEPARATOR)) { - group = PATH_SEPARATOR + group; - } - categories.add(group); - return categories; - } else { - categories.addAll(Arrays.asList(toCategoriesPath(url))); - } - return categories; - } - - protected List toUrlsWithoutEmpty(URL consumer, List providers) { - List urls = new ArrayList<>(); - if (providers != null && providers.size() > 0) { - for (String provider : providers) { - provider = URL.decode(provider); - if (provider.contains(Constants.HTTP_SUBFIX_KEY)) { - URL url = URL.valueOf(provider); - if (UrlUtils.isMatch(consumer, url)) { - urls.add(url); - } - } - } - } - return urls; - } - - protected List toUrlsWithEmpty(URL consumer, String path, List providers) { - List urls = toUrlsWithoutEmpty(consumer, providers); - if (urls == null || urls.isEmpty()) { - int i = path.lastIndexOf('/'); - String category = i < 0 ? path : path.substring(i + 1); - URL empty = consumer.setProtocol(EMPTY_PROTOCOL).addParameter(CATEGORY_KEY, category); - urls.add(empty); - } - return urls; - } -} diff --git a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistryFactory.java b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistryFactory.java deleted file mode 100644 index a7d00b38fd..0000000000 --- a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdRegistryFactory.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.apache.dubbo.registry.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.support.AbstractRegistryFactory; -import org.apache.dubbo.remoting.etcd.EtcdTransporter; - -public class EtcdRegistryFactory extends AbstractRegistryFactory { - - private EtcdTransporter etcdTransporter; - - @Override - protected Registry createRegistry(URL url) { - return new EtcdRegistry(url, etcdTransporter); - } - - public void setEtcdTransporter(EtcdTransporter etcdTransporter) { - this.etcdTransporter = etcdTransporter; - } -} diff --git a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdServiceDiscovery.java b/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdServiceDiscovery.java deleted file mode 100644 index 7916de2115..0000000000 --- a/dubbo-registry/dubbo-registry-etcd3/src/main/java/org/apache/dubbo/registry/etcd/EtcdServiceDiscovery.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * 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.apache.dubbo.registry.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.common.utils.ConcurrentHashSet; -import org.apache.dubbo.event.EventDispatcher; -import org.apache.dubbo.event.EventListener; -import org.apache.dubbo.registry.client.DefaultServiceInstance; -import org.apache.dubbo.registry.client.ServiceDiscovery; -import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; -import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener; -import org.apache.dubbo.remoting.etcd.ChildListener; -import org.apache.dubbo.remoting.etcd.EtcdClient; -import org.apache.dubbo.remoting.etcd.EtcdTransporter; -import org.apache.dubbo.remoting.etcd.StateListener; -import org.apache.dubbo.remoting.etcd.option.OptionUtil; -import org.apache.dubbo.rpc.RpcException; - -import com.google.gson.Gson; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -/** - * 2019-07-08 - */ -public class EtcdServiceDiscovery implements ServiceDiscovery, EventListener { - - private final static Logger logger = LoggerFactory.getLogger(EtcdServiceDiscovery.class); - - private final String root = "/services"; - - private final Set services = new ConcurrentHashSet<>(); - private final Map childListenerMap = new ConcurrentHashMap<>(); - - EtcdClient etcdClient; - EventDispatcher dispatcher; - ServiceInstance serviceInstance; - - @Override - public void onEvent(ServiceInstancesChangedEvent event) { - registerServiceWatcher(event.getServiceName()); - } - - @Override - public void initialize(URL registryURL) throws Exception { - - EtcdTransporter etcdTransporter = ExtensionLoader.getExtensionLoader(EtcdTransporter.class).getAdaptiveExtension(); - - if (registryURL.isAnyHost()) { - throw new IllegalStateException("Service discovery address is invalid, actual: '" + registryURL.getHost() + "'"); - } - - etcdClient = etcdTransporter.connect(registryURL); - - etcdClient.addStateListener(state -> { - if (state == StateListener.CONNECTED) { - try { - recover(); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - } - }); - - this.dispatcher = EventDispatcher.getDefaultExtension(); - this.dispatcher.addEventListener(this); - } - - @Override - public void destroy() { - if (etcdClient != null && etcdClient.isConnected()) { - etcdClient.close(); - } - } - - @Override - public void register(ServiceInstance serviceInstance) throws RuntimeException { - try { - this.serviceInstance = serviceInstance; - String path = toPath(serviceInstance); -// etcdClient.createEphemeral(path); - etcdClient.putEphemeral(path, new Gson().toJson(serviceInstance)); - services.add(serviceInstance.getServiceName()); - } catch (Throwable e) { - throw new RpcException("Failed to register " + serviceInstance + " to etcd " + etcdClient.getUrl() - + ", cause: " + (OptionUtil.isProtocolError(e) - ? "etcd3 registry may not be supported yet or etcd3 registry is not available." - : e.getMessage()), e); - } - } - - String toPath(ServiceInstance serviceInstance) { - return root + File.separator + serviceInstance.getServiceName() + File.separator + serviceInstance.getHost() - + ":" + serviceInstance.getPort(); - } - - String toParentPath(String serviceName) { - return root + File.separator + serviceName; - } - - @Override - public void update(ServiceInstance serviceInstance) throws RuntimeException { - try { - String path = toPath(serviceInstance); - etcdClient.putEphemeral(path, new Gson().toJson(serviceInstance)); - services.add(serviceInstance.getServiceName()); - } catch (Throwable e) { - throw new RpcException("Failed to register " + serviceInstance + " to etcd " + etcdClient.getUrl() - + ", cause: " + (OptionUtil.isProtocolError(e) - ? "etcd3 registry may not be supported yet or etcd3 registry is not available." - : e.getMessage()), e); - } - } - - @Override - public void unregister(ServiceInstance serviceInstance) throws RuntimeException { - try { - String path = toPath(serviceInstance); - etcdClient.delete(path); - services.remove(serviceInstance.getServiceName()); - this.serviceInstance = null; - } catch (Throwable e) { - throw new RpcException("Failed to unregister " + serviceInstance + " to etcd " + etcdClient.getUrl() + ", cause: " + e.getMessage(), e); - } - } - - @Override - public Set getServices() { - return Collections.unmodifiableSet(services); - } - - @Override - public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener) throws NullPointerException, IllegalArgumentException { - registerServiceWatcher(listener.getServiceNames()); - } - - @Override - public List getInstances(String serviceName) { - List children = etcdClient.getChildren(toParentPath(serviceName)); - if (CollectionUtils.isEmpty(children)) { - return Collections.EMPTY_LIST; - } - List list = new ArrayList<>(children.size()); - for (String child : children) { - ServiceInstance serviceInstance = new Gson().fromJson(etcdClient.getKVValue(child), DefaultServiceInstance.class); - list.add(serviceInstance); - } - return list; - } - - - protected void registerServiceWatcher(String serviceName) { - String path = root + File.separator + serviceName; - /* - * if we have no category watcher listener, - * we find out the current listener or create one for the current category, put or get only once. - */ - ChildListener childListener = - Optional.ofNullable(childListenerMap.get(serviceName)) - .orElseGet(() -> { - ChildListener watchListener, prev; - prev = childListenerMap.putIfAbsent(serviceName, watchListener = (parentPath, currentChildren) -> - dispatchServiceInstancesChangedEvent(serviceName)); - return prev != null ? prev : watchListener; - }); - - etcdClient.create(path); - - etcdClient.addChildListener(path, childListener); - } - - private void recover() throws Exception { - // register - if (serviceInstance != null) { - if (logger.isInfoEnabled()) { - logger.info("Recover application register: " + serviceInstance); - } - register(serviceInstance); - } - } -} diff --git a/dubbo-registry/dubbo-registry-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory b/dubbo-registry/dubbo-registry-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory deleted file mode 100644 index 4a6d09c9f0..0000000000 --- a/dubbo-registry/dubbo-registry-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory +++ /dev/null @@ -1 +0,0 @@ -etcd3=org.apache.dubbo.registry.etcd.EtcdRegistryFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery b/dubbo-registry/dubbo-registry-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery deleted file mode 100644 index 804f787815..0000000000 --- a/dubbo-registry/dubbo-registry-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery +++ /dev/null @@ -1 +0,0 @@ -etcd3=org.apache.dubbo.registry.etcd.EtcdServiceDiscovery diff --git a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java deleted file mode 100644 index 079aadd789..0000000000 --- a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdRegistryTest.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * 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. - */ - -/* - * 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. - */ - -/* - * 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.apache.dubbo.registry.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.RegistryFactory; -import org.apache.dubbo.registry.support.AbstractRegistryFactory; -import org.apache.dubbo.remoting.Constants; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; -import static org.apache.dubbo.common.constants.CommonConstants.CLASSIFIER_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.CONSUMERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.ROUTERS_CATEGORY; -import static org.apache.dubbo.registry.Constants.ADMIN_PROTOCOL; - -@Disabled -public class EtcdRegistryTest { - - String service = "org.apache.dubbo.internal.test.DemoServie"; - String outerService = "org.apache.dubbo.outer.test.OuterDemoServie"; - URL serviceUrl = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + "/" + service + "?methods=test1,test2"); - URL serviceUrl2 = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + "/" + service + "?methods=test1,test2,test3"); - URL serviceUrl3 = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + "/" + outerService + "?methods=test1,test2"); - URL registryUrl = URL.valueOf("etcd3://127.0.0.1:2379/org.apache.dubbo.registry.RegistryService"); - URL consumerUrl = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2018" + "/" + service + "?methods=test1,test2"); - RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class).getAdaptiveExtension(); - EtcdRegistry registry; - URL subscribe = new URL( - ADMIN_PROTOCOL, NetUtils.getLocalHost(), 0, "", - INTERFACE_KEY, ANY_VALUE, - GROUP_KEY, ANY_VALUE, - VERSION_KEY, ANY_VALUE, - CLASSIFIER_KEY, ANY_VALUE, - CATEGORY_KEY, PROVIDERS_CATEGORY + "," + CONSUMERS_CATEGORY + "," + ROUTERS_CATEGORY + "," + CONFIGURATORS_CATEGORY, - ENABLED_KEY, ANY_VALUE, - Constants.CHECK_KEY, String.valueOf(false)); - - @Test - public void test_register() { - - registry.register(serviceUrl); - Set registered = registry.getRegistered(); - Assertions.assertEquals(1, registered.size()); - Assertions.assertTrue(registered.contains(serviceUrl)); - - registry.unregister(serviceUrl); - } - - @Test - public void test_unregister() { - - registry.register(serviceUrl); - Set registered = registry.getRegistered(); - Assertions.assertEquals(1, registered.size()); - Assertions.assertTrue(registered.contains(serviceUrl)); - - registry.unregister(serviceUrl); - - registered = registry.getRegistered(); - Assertions.assertEquals(0, registered.size()); - } - - @Test - public void test_subscribe() { - - registry.register(serviceUrl); - - final AtomicReference notifiedUrl = new AtomicReference(); - registry.subscribe(consumerUrl, new NotifyListener() { - public void notify(List urls) { - notifiedUrl.set(urls.get(0)); - } - }); - Assertions.assertEquals(serviceUrl.toFullString(), notifiedUrl.get().toFullString()); - Map> arg = registry.getSubscribed(); - Assertions.assertEquals(consumerUrl, arg.keySet().iterator().next()); - } - - @Test - public void test_subscribe_when_register() throws InterruptedException { - - Assertions.assertEquals(0, registry.getRegistered().size()); - Assertions.assertEquals(0, registry.getSubscribed().size()); - - CountDownLatch notNotified = new CountDownLatch(2); - - final AtomicReference notifiedUrl = new AtomicReference(); - registry.subscribe(consumerUrl, new NotifyListener() { - public void notify(List urls) { - notifiedUrl.set(urls.get(0)); - notNotified.countDown(); - } - }); - - registry.register(serviceUrl); - - Assertions.assertTrue(notNotified.await(15, TimeUnit.SECONDS)); - - Assertions.assertEquals(serviceUrl.toFullString(), notifiedUrl.get().toFullString()); - Map> subscribed = registry.getSubscribed(); - Assertions.assertEquals(consumerUrl, subscribed.keySet().iterator().next()); - } - - @Test - public void test_subscribe_when_register0() throws InterruptedException { - - Assertions.assertEquals(0, registry.getRegistered().size()); - Assertions.assertEquals(0, registry.getSubscribed().size()); - - CountDownLatch notNotified = new CountDownLatch(3); - ConcurrentHashMap notifiedUrls = new ConcurrentHashMap<>(); - registry.subscribe(consumerUrl, new NotifyListener() { - public void notify(List urls) { - if (urls != null && urls.size() > 0) { - if (!urls.get(0).getProtocol().equals("empty")) { - for (Iterator iterator = urls.iterator(); iterator.hasNext(); ) { - notifiedUrls.put(iterator.next(), true); - } - } - } - - notNotified.countDown(); - } - }); - - registry.register(serviceUrl); - registry.register(serviceUrl2); - - Assertions.assertTrue(notNotified.await(15, TimeUnit.SECONDS)); - - Assertions.assertTrue(notifiedUrls.containsKey(serviceUrl)); - Assertions.assertTrue(notifiedUrls.containsKey(serviceUrl2)); - Map> subscribed = registry.getSubscribed(); - Assertions.assertEquals(consumerUrl, subscribed.keySet().iterator().next()); - } - - @Test - public void test_subscribe_when_register1() throws InterruptedException { - - Assertions.assertEquals(0, registry.getRegistered().size()); - Assertions.assertEquals(0, registry.getSubscribed().size()); - - CountDownLatch notNotified = new CountDownLatch(2); - - final AtomicReference notifiedUrls = new AtomicReference(); - registry.subscribe(consumerUrl, new NotifyListener() { - public void notify(List urls) { - notifiedUrls.set(urls.get(0)); - notNotified.countDown(); - } - }); - - registry.register(serviceUrl); - // register service3 should not trigger notify - registry.register(serviceUrl3); - - Assertions.assertTrue(notNotified.await(15, TimeUnit.SECONDS)); - - Assertions.assertEquals(serviceUrl, notifiedUrls.get()); - Map> subscribed = registry.getSubscribed(); - Assertions.assertEquals(consumerUrl, subscribed.keySet().iterator().next()); - } - - @Test - public void test_subscribe_when_register2() throws InterruptedException { - - Assertions.assertEquals(0, registry.getRegistered().size()); - Assertions.assertEquals(0, registry.getSubscribed().size()); - - CountDownLatch notNotified = new CountDownLatch(3); - - ConcurrentHashMap notifiedUrls = new ConcurrentHashMap<>(); - - registry.subscribe(subscribe, new NotifyListener() { - public void notify(List urls) { - if (urls != null && urls.size() > 0) { - if (!urls.get(0).getProtocol().equals("empty")) { - for (Iterator iterator = urls.iterator(); iterator.hasNext(); ) { - notifiedUrls.put(iterator.next(), true); - } - notNotified.countDown(); - } - } - } - }); - - registry.register(serviceUrl); - registry.register(serviceUrl2); - // service3 interface is not equals server2 - registry.register(serviceUrl3); - - Assertions.assertTrue(notNotified.await(15, TimeUnit.SECONDS)); - Assertions.assertEquals(3, notifiedUrls.size()); - Assertions.assertTrue(notifiedUrls.containsKey(serviceUrl)); - Assertions.assertTrue(notifiedUrls.containsKey(serviceUrl2)); - Assertions.assertTrue(notifiedUrls.containsKey(serviceUrl3)); - } - - @Test - public void test_unsubscribe() throws InterruptedException { - - Assertions.assertEquals(0, registry.getRegistered().size()); - Assertions.assertEquals(0, registry.getSubscribed().size()); - - CountDownLatch notNotified = new CountDownLatch(2); - - final AtomicReference notifiedUrl = new AtomicReference(); - - NotifyListener listener = new NotifyListener() { - public void notify(List urls) { - if (urls != null) { - for (Iterator iterator = urls.iterator(); iterator.hasNext(); ) { - URL url = iterator.next(); - if (!url.getProtocol().equals("empty")) { - notifiedUrl.set(url); - notNotified.countDown(); - } - } - } - } - }; - registry.subscribe(consumerUrl, listener); - registry.unsubscribe(consumerUrl, listener); - - registry.register(serviceUrl); - - Assertions.assertFalse(notNotified.await(2, TimeUnit.SECONDS)); - // expect nothing happen - Assertions.assertNull(notifiedUrl.get()); - } - - @BeforeEach - public void setUp() { - registry = (EtcdRegistry) registryFactory.getRegistry(registryUrl); - Assertions.assertNotNull(registry); - if (!registry.isAvailable()) { - AbstractRegistryFactory.destroyAll(); - registry = (EtcdRegistry) registryFactory.getRegistry(registryUrl); - } - } - - @AfterEach - public void tearDown() { - - registry.unregister(serviceUrl); - registry.unregister(serviceUrl2); - registry.unregister(serviceUrl3); - registry.unregister(subscribe); - - registry.destroy(); - } - - -} diff --git a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdServiceDiscoveryTest.java deleted file mode 100644 index abc438ed0d..0000000000 --- a/dubbo-registry/dubbo-registry-etcd3/src/test/java/org/apache/dubbo/registry/etcd/EtcdServiceDiscoveryTest.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * 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.apache.dubbo.registry.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.registry.client.DefaultServiceInstance; -import org.apache.dubbo.registry.client.ServiceInstance; - -import com.google.gson.Gson; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.List; - -import static java.lang.String.valueOf; - -/** - * 2019-08-30 - *

    - * There is no embedded server. so it works depend on etcd local server. - */ -@Disabled -public class EtcdServiceDiscoveryTest { - - static EtcdServiceDiscovery etcdServiceDiscovery; - - @BeforeAll - public static void setUp() throws Exception { - URL url = URL.valueOf("etcd3://127.0.0.1:2379/org.apache.dubbo.registry.RegistryService"); - etcdServiceDiscovery = new EtcdServiceDiscovery(); - Assertions.assertNull(etcdServiceDiscovery.etcdClient); - etcdServiceDiscovery.initialize(url); - } - - @AfterAll - public static void destroy() throws Exception { -// etcdServiceDiscovery.destroy(); - } - - - @Test - public void testLifecycle() throws Exception { - URL url = URL.valueOf("etcd3://127.0.0.1:2233/org.apache.dubbo.registry.RegistryService"); - EtcdServiceDiscovery etcdServiceDiscoveryTmp = new EtcdServiceDiscovery(); - Assertions.assertNull(etcdServiceDiscoveryTmp.etcdClient); - etcdServiceDiscoveryTmp.initialize(url); - Assertions.assertNotNull(etcdServiceDiscoveryTmp.etcdClient); - Assertions.assertTrue(etcdServiceDiscoveryTmp.etcdClient.isConnected()); - etcdServiceDiscoveryTmp.destroy(); - Assertions.assertFalse(etcdServiceDiscoveryTmp.etcdClient.isConnected()); - } - - @Test - public void testRegistry() throws Exception { - ServiceInstance serviceInstance = new DefaultServiceInstance(valueOf(System.nanoTime()), "EtcdTestService", "127.0.0.1", 8080); - Assertions.assertNull(etcdServiceDiscovery.etcdClient.getKVValue(etcdServiceDiscovery.toPath(serviceInstance))); - etcdServiceDiscovery.register(serviceInstance); - Assertions.assertNotNull(etcdServiceDiscovery.etcdClient.getKVValue(etcdServiceDiscovery.toPath(serviceInstance))); - } - - @Test - public void testUnRegistry() throws Exception { - ServiceInstance serviceInstance = new DefaultServiceInstance(valueOf(System.nanoTime()), "EtcdTest2Service", "127.0.0.1", 8080); - Assertions.assertNull(etcdServiceDiscovery.etcdClient.getKVValue(etcdServiceDiscovery.toPath(serviceInstance))); - etcdServiceDiscovery.register(serviceInstance); - Assertions.assertNotNull(etcdServiceDiscovery.etcdClient.getKVValue(etcdServiceDiscovery.toPath(serviceInstance))); - etcdServiceDiscovery.unregister(serviceInstance); - Assertions.assertNull(etcdServiceDiscovery.etcdClient.getKVValue(etcdServiceDiscovery.toPath(serviceInstance))); - } - - @Test - public void testUpdate() throws Exception { - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(valueOf(System.nanoTime()), "EtcdTest34Service", "127.0.0.1", 8080); - Assertions.assertNull(etcdServiceDiscovery.etcdClient.getKVValue(etcdServiceDiscovery.toPath(serviceInstance))); - etcdServiceDiscovery.register(serviceInstance); - Assertions.assertNotNull(etcdServiceDiscovery.etcdClient.getKVValue(etcdServiceDiscovery.toPath(serviceInstance))); - Assertions.assertEquals(etcdServiceDiscovery.etcdClient.getKVValue(etcdServiceDiscovery.toPath(serviceInstance)), - new Gson().toJson(serviceInstance)); - serviceInstance.setPort(9999); - etcdServiceDiscovery.update(serviceInstance); - Assertions.assertNotNull(etcdServiceDiscovery.etcdClient.getKVValue(etcdServiceDiscovery.toPath(serviceInstance))); - Assertions.assertEquals(etcdServiceDiscovery.etcdClient.getKVValue(etcdServiceDiscovery.toPath(serviceInstance)), - new Gson().toJson(serviceInstance)); - } - - @Test - public void testGetInstances() throws Exception { - String serviceName = "EtcdTest77Service"; - Assertions.assertTrue(etcdServiceDiscovery.getInstances(serviceName).isEmpty()); - etcdServiceDiscovery.register(new DefaultServiceInstance(valueOf(System.nanoTime()), serviceName, "127.0.0.1", 8080)); - etcdServiceDiscovery.register(new DefaultServiceInstance(valueOf(System.nanoTime()), serviceName, "127.0.0.1", 9809)); - Assertions.assertFalse(etcdServiceDiscovery.getInstances(serviceName).isEmpty()); - List r = convertToIpPort(etcdServiceDiscovery.getInstances(serviceName)); - Assertions.assertTrue(r.contains("127.0.0.1:8080")); - Assertions.assertTrue(r.contains("127.0.0.1:9809")); - } - - private List convertToIpPort(List serviceInstances) { - List result = new ArrayList<>(); - for (ServiceInstance serviceInstance : serviceInstances) { - result.add(serviceInstance.getHost() + ":" + serviceInstance.getPort()); - } - return result; - } - -} diff --git a/dubbo-registry/dubbo-registry-eureka/pom.xml b/dubbo-registry/dubbo-registry-eureka/pom.xml deleted file mode 100644 index 4c040f7814..0000000000 --- a/dubbo-registry/dubbo-registry-eureka/pom.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-registry - ${revision} - ../pom.xml - - - dubbo-registry-eureka - jar - ${project.artifactId} - The Eureka registry module of Dubbo project - - - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - - - - - com.netflix.eureka - eureka-client - - - javax.ws.rs - jsr311-api - - - - - - - - - - javax.inject - javax.inject - 1 - - - com.netflix.eureka - eureka-core - - - - - com.thoughtworks.xstream - xstream - 1.4.10 - - - com.sun.jersey.contribs - jersey-apache-client4 - 1.19.1 - - - com.netflix.archaius - archaius-core - 0.7.6 - - - - \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/ConfigurableEurekaInstanceConfig.java b/dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/ConfigurableEurekaInstanceConfig.java deleted file mode 100644 index 8e0324d76c..0000000000 --- a/dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/ConfigurableEurekaInstanceConfig.java +++ /dev/null @@ -1,369 +0,0 @@ -/* - * 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.apache.dubbo.registry.eureka; - -import com.netflix.appinfo.DataCenterInfo; -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.appinfo.MyDataCenterInfo; - -import java.util.HashMap; -import java.util.Map; - -/** - * Configurable {@link EurekaInstanceConfig} implementation - */ -class ConfigurableEurekaInstanceConfig implements EurekaInstanceConfig { - - private String appname; - - private String appGroupName; - - private boolean instanceEnabledOnit; - - private int nonSecurePort; - - private int securePort; - - private boolean nonSecurePortEnabled = true; - - private boolean securePortEnabled; - - private int leaseRenewalIntervalInSeconds = 30; - - private int leaseExpirationDurationInSeconds = 90; - - private String virtualHostName = "unknown"; - - private String instanceId; - - private String secureVirtualHostName = "unknown"; - - private String aSGName; - - private Map metadataMap = new HashMap<>(); - - private DataCenterInfo dataCenterInfo = new MyDataCenterInfo(DataCenterInfo.Name.MyOwn); - - private String ipAddress; - - private String statusPageUrlPath; - - private String statusPageUrl; - - private String homePageUrlPath = "/"; - - private String homePageUrl; - - private String healthCheckUrlPath; - - private String healthCheckUrl; - - private String secureHealthCheckUrl; - - private String namespace = "eureka"; - - private String hostname; - - private boolean preferIpAddress = false; - - private InstanceInfo.InstanceStatus initialStatus = InstanceInfo.InstanceStatus.UP; - - private String[] defaultAddressResolutionOrder = new String[0]; - - @Override - public String getAppname() { - return appname; - } - - public ConfigurableEurekaInstanceConfig setAppname(String appname) { - this.appname = appname; - return this; - } - - @Override - public String getAppGroupName() { - return appGroupName; - } - - public ConfigurableEurekaInstanceConfig setAppGroupName(String appGroupName) { - this.appGroupName = appGroupName; - return this; - } - - @Override - public boolean isInstanceEnabledOnit() { - return instanceEnabledOnit; - } - - public ConfigurableEurekaInstanceConfig setInstanceEnabledOnit(boolean instanceEnabledOnit) { - this.instanceEnabledOnit = instanceEnabledOnit; - return this; - } - - @Override - public int getNonSecurePort() { - return nonSecurePort; - } - - public ConfigurableEurekaInstanceConfig setNonSecurePort(int nonSecurePort) { - this.nonSecurePort = nonSecurePort; - return this; - } - - @Override - public int getSecurePort() { - return securePort; - } - - public ConfigurableEurekaInstanceConfig setSecurePort(int securePort) { - this.securePort = securePort; - return this; - } - - @Override - public boolean isNonSecurePortEnabled() { - return nonSecurePortEnabled; - } - - @Override - public boolean getSecurePortEnabled() { - return securePortEnabled; - } - - public ConfigurableEurekaInstanceConfig setNonSecurePortEnabled(boolean nonSecurePortEnabled) { - this.nonSecurePortEnabled = nonSecurePortEnabled; - return this; - } - - public ConfigurableEurekaInstanceConfig setSecurePortEnabled(boolean securePortEnabled) { - this.securePortEnabled = securePortEnabled; - return this; - } - - @Override - public int getLeaseRenewalIntervalInSeconds() { - return leaseRenewalIntervalInSeconds; - } - - public ConfigurableEurekaInstanceConfig setLeaseRenewalIntervalInSeconds(int leaseRenewalIntervalInSeconds) { - this.leaseRenewalIntervalInSeconds = leaseRenewalIntervalInSeconds; - return this; - } - - @Override - public int getLeaseExpirationDurationInSeconds() { - return leaseExpirationDurationInSeconds; - } - - public ConfigurableEurekaInstanceConfig setLeaseExpirationDurationInSeconds(int leaseExpirationDurationInSeconds) { - this.leaseExpirationDurationInSeconds = leaseExpirationDurationInSeconds; - return this; - } - - @Override - public String getVirtualHostName() { - return virtualHostName; - } - - public ConfigurableEurekaInstanceConfig setVirtualHostName(String virtualHostName) { - this.virtualHostName = virtualHostName; - return this; - } - - @Override - public String getInstanceId() { - return instanceId; - } - - public ConfigurableEurekaInstanceConfig setInstanceId(String instanceId) { - this.instanceId = instanceId; - return this; - } - - @Override - public String getSecureVirtualHostName() { - return secureVirtualHostName; - } - - @Override - public String getASGName() { - return aSGName; - } - - @Override - public String getHostName(boolean refresh) { - return null; - } - - public ConfigurableEurekaInstanceConfig setSecureVirtualHostName(String secureVirtualHostName) { - this.secureVirtualHostName = secureVirtualHostName; - return this; - } - - public ConfigurableEurekaInstanceConfig setASGName(String aSGName) { - this.aSGName = aSGName; - return this; - } - - @Override - public Map getMetadataMap() { - return metadataMap; - } - - public ConfigurableEurekaInstanceConfig setMetadataMap(Map metadataMap) { - this.metadataMap = metadataMap; - return this; - } - - @Override - public DataCenterInfo getDataCenterInfo() { - return dataCenterInfo; - } - - public ConfigurableEurekaInstanceConfig setDataCenterInfo(DataCenterInfo dataCenterInfo) { - this.dataCenterInfo = dataCenterInfo; - return this; - } - - @Override - public String getIpAddress() { - return ipAddress; - } - - public ConfigurableEurekaInstanceConfig setIpAddress(String ipAddress) { - this.ipAddress = ipAddress; - return this; - } - - @Override - public String getStatusPageUrlPath() { - return statusPageUrlPath; - } - - public ConfigurableEurekaInstanceConfig setStatusPageUrlPath(String statusPageUrlPath) { - this.statusPageUrlPath = statusPageUrlPath; - return this; - } - - @Override - public String getStatusPageUrl() { - return statusPageUrl; - } - - public ConfigurableEurekaInstanceConfig setStatusPageUrl(String statusPageUrl) { - this.statusPageUrl = statusPageUrl; - return this; - } - - @Override - public String getHomePageUrlPath() { - return homePageUrlPath; - } - - public ConfigurableEurekaInstanceConfig setHomePageUrlPath(String homePageUrlPath) { - this.homePageUrlPath = homePageUrlPath; - return this; - } - - @Override - public String getHomePageUrl() { - return homePageUrl; - } - - public ConfigurableEurekaInstanceConfig setHomePageUrl(String homePageUrl) { - this.homePageUrl = homePageUrl; - return this; - } - - @Override - public String getHealthCheckUrlPath() { - return healthCheckUrlPath; - } - - public ConfigurableEurekaInstanceConfig setHealthCheckUrlPath(String healthCheckUrlPath) { - this.healthCheckUrlPath = healthCheckUrlPath; - return this; - } - - @Override - public String getHealthCheckUrl() { - return healthCheckUrl; - } - - public ConfigurableEurekaInstanceConfig setHealthCheckUrl(String healthCheckUrl) { - this.healthCheckUrl = healthCheckUrl; - return this; - } - - @Override - public String getSecureHealthCheckUrl() { - return secureHealthCheckUrl; - } - - public ConfigurableEurekaInstanceConfig setSecureHealthCheckUrl(String secureHealthCheckUrl) { - this.secureHealthCheckUrl = secureHealthCheckUrl; - return this; - } - - @Override - public String getNamespace() { - return namespace; - } - - public ConfigurableEurekaInstanceConfig setNamespace(String namespace) { - this.namespace = namespace; - return this; - } - - public String getHostname() { - return hostname; - } - - public ConfigurableEurekaInstanceConfig setHostname(String hostname) { - this.hostname = hostname; - return this; - } - - public boolean isPreferIpAddress() { - return preferIpAddress; - } - - public ConfigurableEurekaInstanceConfig setPreferIpAddress(boolean preferIpAddress) { - this.preferIpAddress = preferIpAddress; - return this; - } - - public InstanceInfo.InstanceStatus getInitialStatus() { - return initialStatus; - } - - public ConfigurableEurekaInstanceConfig setInitialStatus(InstanceInfo.InstanceStatus initialStatus) { - this.initialStatus = initialStatus; - return this; - } - - @Override - public String[] getDefaultAddressResolutionOrder() { - return defaultAddressResolutionOrder; - } - - public ConfigurableEurekaInstanceConfig setDefaultAddressResolutionOrder(String[] defaultAddressResolutionOrder) { - this.defaultAddressResolutionOrder = defaultAddressResolutionOrder; - return this; - } -} diff --git a/dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/EurekaServiceDiscovery.java b/dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/EurekaServiceDiscovery.java deleted file mode 100644 index 516c9e5584..0000000000 --- a/dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/EurekaServiceDiscovery.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * 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.apache.dubbo.registry.eureka; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.event.EventDispatcher; -import org.apache.dubbo.registry.client.DefaultServiceInstance; -import org.apache.dubbo.registry.client.ServiceDiscovery; -import org.apache.dubbo.registry.client.ServiceInstance; -import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent; - -import com.netflix.appinfo.ApplicationInfoManager; -import com.netflix.appinfo.EurekaInstanceConfig; -import com.netflix.appinfo.InstanceInfo; -import com.netflix.config.ConfigurationManager; -import com.netflix.discovery.CacheRefreshedEvent; -import com.netflix.discovery.DefaultEurekaClientConfig; -import com.netflix.discovery.DiscoveryClient; -import com.netflix.discovery.EurekaClient; -import com.netflix.discovery.EurekaClientConfig; -import com.netflix.discovery.EurekaEvent; -import com.netflix.discovery.shared.Application; -import com.netflix.discovery.shared.Applications; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Properties; -import java.util.Set; - -import static java.util.Collections.emptyList; -import static org.apache.dubbo.event.EventDispatcher.getDefaultExtension; -import static org.apache.dubbo.registry.client.ServiceDiscoveryRegistry.getSubscribedServices; - -/** - * Eureka {@link ServiceDiscovery} implementation based on Eureka API - */ -public class EurekaServiceDiscovery implements ServiceDiscovery { - - private final EventDispatcher eventDispatcher = getDefaultExtension(); - - private ApplicationInfoManager applicationInfoManager; - - private EurekaClient eurekaClient; - - private Set subscribedServices; - - /** - * last apps hash code is used to identify the {@link Applications} is changed or not - */ - private String lastAppsHashCode; - - @Override - public void initialize(URL registryURL) throws Exception { - Properties eurekaConfigProperties = buildEurekaConfigProperties(registryURL); - initConfigurationManager(eurekaConfigProperties); - initSubscribedServices(registryURL); - } - - /** - * Build the Properties whose {@link java.util.Map.Entry entries} are retrieved from - * {@link URL#getParameters() the parameters of the specified URL}, which will be used in the Eureka's {@link ConfigurationManager} - * - * @param registryURL the {@link URL url} to connect Eureka - * @return non-null - */ - private Properties buildEurekaConfigProperties(URL registryURL) { - Properties properties = new Properties(); - Map parameters = registryURL.getParameters(); - setDefaultProperties(registryURL, properties); - parameters.entrySet().stream() - .filter(this::filterEurekaProperty) - .forEach(propertyEntry -> { - properties.setProperty(propertyEntry.getKey(), propertyEntry.getValue()); - }); - return properties; - } - - /** - * Initialize {@link #subscribedServices} property - * - * @param registryURL the {@link URL url} to connect Eureka - */ - private void initSubscribedServices(URL registryURL) { - this.subscribedServices = getSubscribedServices(registryURL); - } - - private boolean filterEurekaProperty(Map.Entry propertyEntry) { - String propertyName = propertyEntry.getKey(); - return propertyName.startsWith("eureka."); - } - - private void setDefaultProperties(URL registryURL, Properties properties) { - setDefaultServiceURL(registryURL, properties); - setDefaultInitialInstanceInfoReplicationIntervalSeconds(properties); - } - - private void setDefaultServiceURL(URL registryURL, Properties properties) { - StringBuilder defaultServiceURLBuilder = new StringBuilder("http://") - .append(registryURL.getHost()) - .append(":") - .append(registryURL.getPort()) - .append("/eureka"); - properties.setProperty("eureka.serviceUrl.default", defaultServiceURLBuilder.toString()); - } - - /** - * Set the default property for {@link EurekaClientConfig#getInitialInstanceInfoReplicationIntervalSeconds()} - * which means do register immediately - * - * @param properties {@link Properties} - */ - private void setDefaultInitialInstanceInfoReplicationIntervalSeconds(Properties properties) { - properties.setProperty("eureka.appinfo.initial.replicate.time", "0"); - } - - /** - * Initialize {@link ConfigurationManager} - * - * @param eurekaConfigProperties the Eureka's {@link ConfigurationManager} - */ - private void initConfigurationManager(Properties eurekaConfigProperties) { - ConfigurationManager.loadProperties(eurekaConfigProperties); - } - - private void initApplicationInfoManager(ServiceInstance serviceInstance) { - EurekaInstanceConfig eurekaInstanceConfig = buildEurekaInstanceConfig(serviceInstance); - this.applicationInfoManager = new ApplicationInfoManager(eurekaInstanceConfig, (ApplicationInfoManager.OptionalArgs) null); - } - - /** - * Initialize {@link #eurekaClient} property - * - * @param serviceInstance {@link ServiceInstance} - */ - private void initEurekaClient(ServiceInstance serviceInstance) { - if (eurekaClient != null) { - return; - } - initApplicationInfoManager(serviceInstance); - EurekaClient eurekaClient = createEurekaClient(); - registerEurekaEventListener(eurekaClient); - // set eurekaClient - this.eurekaClient = eurekaClient; - } - - private void registerEurekaEventListener(EurekaClient eurekaClient) { - eurekaClient.registerEventListener(this::onEurekaEvent); - } - - private void onEurekaEvent(EurekaEvent event) { - if (event instanceof CacheRefreshedEvent) { - onCacheRefreshedEvent(CacheRefreshedEvent.class.cast(event)); - } - } - - private void onCacheRefreshedEvent(CacheRefreshedEvent event) { - synchronized (this) { // Make sure thread-safe in async execution - Applications applications = eurekaClient.getApplications(); - String appsHashCode = applications.getAppsHashCode(); - if (!Objects.equals(lastAppsHashCode, appsHashCode)) { // Changed - // Dispatch Events - dispatchServiceInstancesChangedEvent(); - lastAppsHashCode = appsHashCode; // update current result - } - } - } - - private void dispatchServiceInstancesChangedEvent() { - subscribedServices.forEach((serviceName) -> { - eventDispatcher.dispatch(new ServiceInstancesChangedEvent(serviceName, getInstances(serviceName))); - }); - } - - private EurekaClient createEurekaClient() { - EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig(); - DiscoveryClient eurekaClient = new DiscoveryClient(applicationInfoManager, eurekaClientConfig); - return eurekaClient; - } - - @Override - public void destroy() throws Exception { - if (eurekaClient != null) { - this.eurekaClient.shutdown(); - } - } - - @Override - public void register(ServiceInstance serviceInstance) throws RuntimeException { - initEurekaClient(serviceInstance); - setInstanceStatus(InstanceInfo.InstanceStatus.UP); - } - - private void setInstanceStatus(InstanceInfo.InstanceStatus status) { - if (applicationInfoManager != null) { - this.applicationInfoManager.setInstanceStatus(status); - } - } - - @Override - public void update(ServiceInstance serviceInstance) throws RuntimeException { - setInstanceStatus(serviceInstance.isHealthy() ? InstanceInfo.InstanceStatus.UP : - InstanceInfo.InstanceStatus.UNKNOWN); - } - - @Override - public void unregister(ServiceInstance serviceInstance) throws RuntimeException { - setInstanceStatus(InstanceInfo.InstanceStatus.OUT_OF_SERVICE); - } - - @Override - public Set getServices() { - Applications applications = this.eurekaClient.getApplications(); - if (applications == null) { - return Collections.emptySet(); - } - List registered = applications.getRegisteredApplications(); - Set names = new LinkedHashSet<>(); - for (Application app : registered) { - if (app.getInstances().isEmpty()) { - continue; - } - names.add(app.getName().toLowerCase()); - } - return names; - } - - @Override - public List getInstances(String serviceName) throws NullPointerException { - Application application = this.eurekaClient.getApplication(serviceName); - - if (application == null) { - return emptyList(); - } - - List infos = application.getInstances(); - List instances = new ArrayList<>(); - for (InstanceInfo info : infos) { - instances.add(buildServiceInstance(info)); - } - return instances; - } - - private ServiceInstance buildServiceInstance(InstanceInfo instance) { - DefaultServiceInstance serviceInstance = new DefaultServiceInstance(instance.getId(), instance.getAppName(), - instance.getHostName(), - instance.isPortEnabled(InstanceInfo.PortType.SECURE) ? instance.getSecurePort() : instance.getPort()); - serviceInstance.setMetadata(instance.getMetadata()); - return serviceInstance; - } - - private EurekaInstanceConfig buildEurekaInstanceConfig(ServiceInstance serviceInstance) { - ConfigurableEurekaInstanceConfig eurekaInstanceConfig = new ConfigurableEurekaInstanceConfig() - .setInstanceId(serviceInstance.getId()) - .setAppname(serviceInstance.getServiceName()) - .setIpAddress(serviceInstance.getHost()) - .setNonSecurePort(serviceInstance.getPort()) - .setMetadataMap(serviceInstance.getMetadata()); - return eurekaInstanceConfig; - } -} diff --git a/dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/package-info.java b/dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/package-info.java deleted file mode 100644 index f803f9e473..0000000000 --- a/dubbo-registry/dubbo-registry-eureka/src/main/java/org/apache/dubbo/registry/eureka/package-info.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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. - */ -/** - * The package contains the registry implementations for Netflix Eureka - * - * @since 2.7.5 - */ -package org.apache.dubbo.registry.eureka; diff --git a/dubbo-registry/dubbo-registry-eureka/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery b/dubbo-registry/dubbo-registry-eureka/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery deleted file mode 100644 index 51be37ccc1..0000000000 --- a/dubbo-registry/dubbo-registry-eureka/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.client.ServiceDiscovery +++ /dev/null @@ -1 +0,0 @@ -eureka=org.apache.dubbo.registry.eureka.EurekaServiceDiscovery \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-eureka/src/test/java/org/apache/dubbo/registry/eureka/EurekaServiceDiscoveryTest.java b/dubbo-registry/dubbo-registry-eureka/src/test/java/org/apache/dubbo/registry/eureka/EurekaServiceDiscoveryTest.java deleted file mode 100644 index fa733557f9..0000000000 --- a/dubbo-registry/dubbo-registry-eureka/src/test/java/org/apache/dubbo/registry/eureka/EurekaServiceDiscoveryTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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.apache.dubbo.registry.eureka; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.client.DefaultServiceInstance; -import org.apache.dubbo.registry.client.ServiceInstance; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertNotNull; - -/** - * {@link EurekaServiceDiscovery} Test - * - * @since 2.7.5 - */ -public class EurekaServiceDiscoveryTest { - - private EurekaServiceDiscovery serviceDiscovery; - - private ServiceInstance serviceInstance; - - private URL registryURL = URL.valueOf("eureka://127.0.0.1:" + NetUtils.getAvailablePort() + "/eureka"); - - @BeforeEach - public void init() throws Exception { - serviceDiscovery = new EurekaServiceDiscovery(); - serviceDiscovery.initialize(registryURL); - serviceInstance = new DefaultServiceInstance("test", "127.0.0.1", NetUtils.getAvailablePort()); - serviceDiscovery.register(serviceInstance); - } - - @AfterEach - public void destroy() throws Exception { - serviceDiscovery.destroy(); - } - - @Test - public void testGetServices() { - assertNotNull(serviceDiscovery.getServices()); - } - - @Test - public void testGetInstances() { - serviceDiscovery.getServices().forEach(serviceName -> { - assertNotNull(serviceDiscovery.getInstances(serviceName)); - }); - } -} diff --git a/dubbo-registry/dubbo-registry-nacos/pom.xml b/dubbo-registry/dubbo-registry-nacos/pom.xml index 9dd5ced786..f381bba33c 100644 --- a/dubbo-registry/dubbo-registry-nacos/pom.xml +++ b/dubbo-registry/dubbo-registry-nacos/pom.xml @@ -18,8 +18,7 @@ org.apache.dubbo dubbo-registry - ${revision} - ../pom.xml + 2.7.7-SNAPSHOT 4.0.0 diff --git a/dubbo-registry/dubbo-registry-redis/pom.xml b/dubbo-registry/dubbo-registry-redis/pom.xml deleted file mode 100644 index 0971cb870b..0000000000 --- a/dubbo-registry/dubbo-registry-redis/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-registry - ${revision} - ../pom.xml - - dubbo-registry-redis - jar - ${project.artifactId} - The redis registry module of dubbo project - - false - - - - org.apache.dubbo - dubbo-registry-api - ${project.parent.version} - - - redis.clients - jedis - - - com.github.kstyrc - embedded-redis - test - - - org.apache.commons - commons-lang3 - test - - - \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java b/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java deleted file mode 100644 index 0938a3904e..0000000000 --- a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistry.java +++ /dev/null @@ -1,661 +0,0 @@ -/* - * 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.apache.dubbo.registry.redis; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.URLBuilder; -import org.apache.dubbo.common.constants.RemotingConstants; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ArrayUtils; -import org.apache.dubbo.common.utils.CollectionUtils; -import org.apache.dubbo.common.utils.ExecutorUtil; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.common.utils.UrlUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.support.FailbackRegistry; -import org.apache.dubbo.rpc.RpcException; - -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPubSub; -import redis.clients.jedis.JedisSentinelPool; -import redis.clients.util.Pool; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -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.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; -import static org.apache.dubbo.common.constants.CommonConstants.ANY_VALUE; -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; -import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.CATEGORY_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY; -import static org.apache.dubbo.common.constants.RegistryConstants.DYNAMIC_KEY; -import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL; -import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY_RECONNECT_PERIOD; -import static org.apache.dubbo.registry.Constants.DEFAULT_SESSION_TIMEOUT; -import static org.apache.dubbo.registry.Constants.REGISTER; -import static org.apache.dubbo.registry.Constants.REGISTRY_RECONNECT_PERIOD_KEY; -import static org.apache.dubbo.registry.Constants.SESSION_TIMEOUT_KEY; -import static org.apache.dubbo.registry.Constants.UNREGISTER; - -/** - * RedisRegistry - */ -public class RedisRegistry extends FailbackRegistry { - - private static final Logger logger = LoggerFactory.getLogger(RedisRegistry.class); - - private static final int DEFAULT_REDIS_PORT = 6379; - - private final static String DEFAULT_ROOT = "dubbo"; - - private static final String REDIS_MASTER_NAME_KEY = "master-name"; - - private final ScheduledExecutorService expireExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("DubboRegistryExpireTimer", true)); - - private final ScheduledFuture expireFuture; - - private final String root; - - private final Map> jedisPools = new ConcurrentHashMap<>(); - - private final ConcurrentMap notifiers = new ConcurrentHashMap<>(); - - private final int reconnectPeriod; - - private final int expirePeriod; - - private volatile boolean admin = false; - - private boolean replicate; - - public RedisRegistry(URL url) { - super(url); - if (url.isAnyHost()) { - throw new IllegalStateException("registry address == null"); - } - GenericObjectPoolConfig config = new GenericObjectPoolConfig(); - config.setTestOnBorrow(url.getParameter("test.on.borrow", true)); - config.setTestOnReturn(url.getParameter("test.on.return", false)); - config.setTestWhileIdle(url.getParameter("test.while.idle", false)); - if (url.getParameter("max.idle", 0) > 0) { - config.setMaxIdle(url.getParameter("max.idle", 0)); - } - if (url.getParameter("min.idle", 0) > 0) { - config.setMinIdle(url.getParameter("min.idle", 0)); - } - if (url.getParameter("max.active", 0) > 0) { - config.setMaxTotal(url.getParameter("max.active", 0)); - } - if (url.getParameter("max.total", 0) > 0) { - config.setMaxTotal(url.getParameter("max.total", 0)); - } - if (url.getParameter("max.wait", url.getParameter("timeout", 0)) > 0) { - config.setMaxWaitMillis(url.getParameter("max.wait", url.getParameter("timeout", 0))); - } - if (url.getParameter("num.tests.per.eviction.run", 0) > 0) { - config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0)); - } - if (url.getParameter("time.between.eviction.runs.millis", 0) > 0) { - config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0)); - } - if (url.getParameter("min.evictable.idle.time.millis", 0) > 0) { - config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0)); - } - - String cluster = url.getParameter("cluster", "failover"); - if (!"failover".equals(cluster) && !"replicate".equals(cluster)) { - throw new IllegalArgumentException("Unsupported redis cluster: " + cluster + ". The redis cluster only supported failover or replicate."); - } - replicate = "replicate".equals(cluster); - - List addresses = new ArrayList<>(); - addresses.add(url.getAddress()); - String[] backups = url.getParameter(RemotingConstants.BACKUP_KEY, new String[0]); - if (ArrayUtils.isNotEmpty(backups)) { - addresses.addAll(Arrays.asList(backups)); - } - //获得Redis主节点名称 - String masterName = url.getParameter(REDIS_MASTER_NAME_KEY); - if (StringUtils.isEmpty(masterName)) { - //单机版redis - for (String address : addresses) { - int i = address.indexOf(':'); - String host; - int port; - if (i > 0) { - host = address.substring(0, i); - port = Integer.parseInt(address.substring(i + 1)); - } else { - host = address; - port = DEFAULT_REDIS_PORT; - } - this.jedisPools.put(address, new JedisPool(config, host, port, - url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT), StringUtils.isEmpty(url.getPassword()) ? null : url.getPassword(), - url.getParameter("db.index", 0))); - } - } else { - //哨兵版redis - Set sentinelSet = new HashSet<>(addresses); - int index = url.getParameter("db.index", 0); - int timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); - String password = StringUtils.isEmpty(url.getPassword()) ? null : url.getPassword(); - JedisSentinelPool pool = new JedisSentinelPool(masterName, sentinelSet, config, timeout, password, index); - this.jedisPools.put(masterName, pool); - } - - this.reconnectPeriod = url.getParameter(REGISTRY_RECONNECT_PERIOD_KEY, DEFAULT_REGISTRY_RECONNECT_PERIOD); - String group = url.getParameter(GROUP_KEY, DEFAULT_ROOT); - if (!group.startsWith(PATH_SEPARATOR)) { - group = PATH_SEPARATOR + group; - } - if (!group.endsWith(PATH_SEPARATOR)) { - group = group + PATH_SEPARATOR; - } - this.root = group; - - this.expirePeriod = url.getParameter(SESSION_TIMEOUT_KEY, DEFAULT_SESSION_TIMEOUT); - this.expireFuture = expireExecutor.scheduleWithFixedDelay(() -> { - try { - deferExpired(); // Extend the expiration time - } catch (Throwable t) { // Defensive fault tolerance - logger.error("Unexpected exception occur at defer expire time, cause: " + t.getMessage(), t); - } - }, expirePeriod / 2, expirePeriod / 2, TimeUnit.MILLISECONDS); - } - - private void deferExpired() { - for (Map.Entry> entry : jedisPools.entrySet()) { - Pool jedisPool = entry.getValue(); - try { - try (Jedis jedis = jedisPool.getResource()) { - for (URL url : new HashSet<>(getRegistered())) { - if (url.getParameter(DYNAMIC_KEY, true)) { - String key = toCategoryPath(url); - if (jedis.hset(key, url.toFullString(), String.valueOf(System.currentTimeMillis() + expirePeriod)) == 1) { - jedis.publish(key, REGISTER); - } - } - } - if (admin) { - clean(jedis); - } - if (!replicate) { - break;//  If the server side has synchronized data, just write a single machine - } - } - } catch (Throwable t) { - logger.warn("Failed to write provider heartbeat to redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t); - } - } - } - - // The monitoring center is responsible for deleting outdated dirty data - private void clean(Jedis jedis) { - Set keys = jedis.keys(root + ANY_VALUE); - if (CollectionUtils.isNotEmpty(keys)) { - for (String key : keys) { - Map values = jedis.hgetAll(key); - if (CollectionUtils.isNotEmptyMap(values)) { - boolean delete = false; - long now = System.currentTimeMillis(); - for (Map.Entry entry : values.entrySet()) { - URL url = URL.valueOf(entry.getKey()); - if (url.getParameter(DYNAMIC_KEY, true)) { - long expire = Long.parseLong(entry.getValue()); - if (expire < now) { - jedis.hdel(key, entry.getKey()); - delete = true; - if (logger.isWarnEnabled()) { - logger.warn("Delete expired key: " + key + " -> value: " + entry.getKey() + ", expire: " + new Date(expire) + ", now: " + new Date(now)); - } - } - } - } - if (delete) { - jedis.publish(key, UNREGISTER); - } - } - } - } - } - - @Override - public boolean isAvailable() { - for (Pool jedisPool : jedisPools.values()) { - try (Jedis jedis = jedisPool.getResource()) { - if (jedis.isConnected()) { - return true; // At least one single machine is available. - } - } catch (Throwable t) { - } - } - return false; - } - - @Override - public void destroy() { - super.destroy(); - try { - expireFuture.cancel(true); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - try { - for (Notifier notifier : notifiers.values()) { - notifier.shutdown(); - } - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - for (Map.Entry> entry : jedisPools.entrySet()) { - Pool jedisPool = entry.getValue(); - try { - jedisPool.destroy(); - } catch (Throwable t) { - logger.warn("Failed to destroy the redis registry client. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t); - } - } - ExecutorUtil.gracefulShutdown(expireExecutor, expirePeriod); - } - - @Override - public void doRegister(URL url) { - String key = toCategoryPath(url); - String value = url.toFullString(); - String expire = String.valueOf(System.currentTimeMillis() + expirePeriod); - boolean success = false; - RpcException exception = null; - for (Map.Entry> entry : jedisPools.entrySet()) { - Pool jedisPool = entry.getValue(); - try { - try (Jedis jedis = jedisPool.getResource()) { - jedis.hset(key, value, expire); - jedis.publish(key, REGISTER); - success = true; - if (!replicate) { - break; //  If the server side has synchronized data, just write a single machine - } - } - } catch (Throwable t) { - exception = new RpcException("Failed to register service to redis registry. registry: " + entry.getKey() + ", service: " + url + ", cause: " + t.getMessage(), t); - } - } - if (exception != null) { - if (success) { - logger.warn(exception.getMessage(), exception); - } else { - throw exception; - } - } - } - - @Override - public void doUnregister(URL url) { - String key = toCategoryPath(url); - String value = url.toFullString(); - RpcException exception = null; - boolean success = false; - for (Map.Entry> entry : jedisPools.entrySet()) { - Pool jedisPool = entry.getValue(); - try { - try (Jedis jedis = jedisPool.getResource()) { - jedis.hdel(key, value); - jedis.publish(key, UNREGISTER); - success = true; - if (!replicate) { - break; //  If the server side has synchronized data, just write a single machine - } - } - } catch (Throwable t) { - exception = new RpcException("Failed to unregister service to redis registry. registry: " + entry.getKey() + ", service: " + url + ", cause: " + t.getMessage(), t); - } - } - if (exception != null) { - if (success) { - logger.warn(exception.getMessage(), exception); - } else { - throw exception; - } - } - } - - @Override - public void doSubscribe(final URL url, final NotifyListener listener) { - String service = toServicePath(url); - Notifier notifier = notifiers.get(service); - if (notifier == null) { - Notifier newNotifier = new Notifier(service); - notifiers.putIfAbsent(service, newNotifier); - notifier = notifiers.get(service); - if (notifier == newNotifier) { - notifier.start(); - } - } - boolean success = false; - RpcException exception = null; - for (Map.Entry> entry : jedisPools.entrySet()) { - Pool jedisPool = entry.getValue(); - try { - try (Jedis jedis = jedisPool.getResource()) { - if (service.endsWith(ANY_VALUE)) { - admin = true; - Set keys = jedis.keys(service); - if (CollectionUtils.isNotEmpty(keys)) { - Map> serviceKeys = new HashMap<>(); - for (String key : keys) { - String serviceKey = toServicePath(key); - Set sk = serviceKeys.computeIfAbsent(serviceKey, k -> new HashSet<>()); - sk.add(key); - } - for (Set sk : serviceKeys.values()) { - doNotify(jedis, sk, url, Collections.singletonList(listener)); - } - } - } else { - doNotify(jedis, jedis.keys(service + PATH_SEPARATOR + ANY_VALUE), url, Collections.singletonList(listener)); - } - success = true; - break; // Just read one server's data - } - } catch (Throwable t) { // Try the next server - exception = new RpcException("Failed to subscribe service from redis registry. registry: " + entry.getKey() + ", service: " + url + ", cause: " + t.getMessage(), t); - } - } - if (exception != null) { - if (success) { - logger.warn(exception.getMessage(), exception); - } else { - throw exception; - } - } - } - - @Override - public void doUnsubscribe(URL url, NotifyListener listener) { - } - - private void doNotify(Jedis jedis, String key) { - for (Map.Entry> entry : new HashMap<>(getSubscribed()).entrySet()) { - doNotify(jedis, Collections.singletonList(key), entry.getKey(), new HashSet<>(entry.getValue())); - } - } - - private void doNotify(Jedis jedis, Collection keys, URL url, Collection listeners) { - if (keys == null || keys.isEmpty() - || listeners == null || listeners.isEmpty()) { - return; - } - long now = System.currentTimeMillis(); - List result = new ArrayList<>(); - List categories = Arrays.asList(url.getParameter(CATEGORY_KEY, new String[0])); - String consumerService = url.getServiceInterface(); - for (String key : keys) { - if (!ANY_VALUE.equals(consumerService)) { - String providerService = toServiceName(key); - if (!providerService.equals(consumerService)) { - continue; - } - } - String category = toCategoryName(key); - if (!categories.contains(ANY_VALUE) && !categories.contains(category)) { - continue; - } - List urls = new ArrayList<>(); - Map values = jedis.hgetAll(key); - if (CollectionUtils.isNotEmptyMap(values)) { - for (Map.Entry entry : values.entrySet()) { - URL u = URL.valueOf(entry.getKey()); - if (!u.getParameter(DYNAMIC_KEY, true) - || Long.parseLong(entry.getValue()) >= now) { - if (UrlUtils.isMatch(url, u)) { - urls.add(u); - } - } - } - } - if (urls.isEmpty()) { - urls.add(URLBuilder.from(url) - .setProtocol(EMPTY_PROTOCOL) - .setAddress(ANYHOST_VALUE) - .setPath(toServiceName(key)) - .addParameter(CATEGORY_KEY, category) - .build()); - } - result.addAll(urls); - if (logger.isInfoEnabled()) { - logger.info("redis notify: " + key + " = " + urls); - } - } - if (CollectionUtils.isEmpty(result)) { - return; - } - for (NotifyListener listener : listeners) { - notify(url, listener, result); - } - } - - private String toServiceName(String categoryPath) { - String servicePath = toServicePath(categoryPath); - return servicePath.startsWith(root) ? servicePath.substring(root.length()) : servicePath; - } - - private String toCategoryName(String categoryPath) { - int i = categoryPath.lastIndexOf(PATH_SEPARATOR); - return i > 0 ? categoryPath.substring(i + 1) : categoryPath; - } - - private String toServicePath(String categoryPath) { - int i; - if (categoryPath.startsWith(root)) { - i = categoryPath.indexOf(PATH_SEPARATOR, root.length()); - } else { - i = categoryPath.indexOf(PATH_SEPARATOR); - } - return i > 0 ? categoryPath.substring(0, i) : categoryPath; - } - - private String toServicePath(URL url) { - return root + url.getServiceInterface(); - } - - private String toCategoryPath(URL url) { - return toServicePath(url) + PATH_SEPARATOR + url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY); - } - - private class NotifySub extends JedisPubSub { - - private final Pool jedisPool; - - public NotifySub(Pool jedisPool) { - this.jedisPool = jedisPool; - } - - @Override - public void onMessage(String key, String msg) { - if (logger.isInfoEnabled()) { - logger.info("redis event: " + key + " = " + msg); - } - if (msg.equals(REGISTER) - || msg.equals(UNREGISTER)) { - try { - Jedis jedis = jedisPool.getResource(); - try { - doNotify(jedis, key); - } finally { - jedis.close(); - } - } catch (Throwable t) { // TODO Notification failure does not restore mechanism guarantee - logger.error(t.getMessage(), t); - } - } - } - - @Override - public void onPMessage(String pattern, String key, String msg) { - onMessage(key, msg); - } - - @Override - public void onSubscribe(String key, int num) { - } - - @Override - public void onPSubscribe(String pattern, int num) { - } - - @Override - public void onUnsubscribe(String key, int num) { - } - - @Override - public void onPUnsubscribe(String pattern, int num) { - } - - } - - private class Notifier extends Thread { - - private final String service; - private final AtomicInteger connectSkip = new AtomicInteger(); - private final AtomicInteger connectSkipped = new AtomicInteger(); - private volatile Jedis jedis; - private volatile boolean first = true; - private volatile boolean running = true; - private volatile int connectRandom; - - public Notifier(String service) { - super.setDaemon(true); - super.setName("DubboRedisSubscribe"); - this.service = service; - } - - private void resetSkip() { - connectSkip.set(0); - connectSkipped.set(0); - connectRandom = 0; - } - - private boolean isSkip() { - int skip = connectSkip.get(); // Growth of skipping times - if (skip >= 10) { // If the number of skipping times increases by more than 10, take the random number - if (connectRandom == 0) { - connectRandom = ThreadLocalRandom.current().nextInt(10); - } - skip = 10 + connectRandom; - } - if (connectSkipped.getAndIncrement() < skip) { // Check the number of skipping times - return true; - } - connectSkip.incrementAndGet(); - connectSkipped.set(0); - connectRandom = 0; - return false; - } - - @Override - public void run() { - while (running) { - try { - if (!isSkip()) { - try { - for (Map.Entry> entry : jedisPools.entrySet()) { - Pool jedisPool = entry.getValue(); - try { - if (jedisPool.isClosed()) { - continue; - } - jedis = jedisPool.getResource(); - if (!jedis.isConnected()) { - continue; - } - try { - if (service.endsWith(ANY_VALUE)) { - if (first) { - first = false; - Set keys = jedis.keys(service); - if (CollectionUtils.isNotEmpty(keys)) { - for (String s : keys) { - doNotify(jedis, s); - } - } - resetSkip(); - } - jedis.psubscribe(new NotifySub(jedisPool), service); // blocking - } else { - if (first) { - first = false; - doNotify(jedis, service); - resetSkip(); - } - jedis.psubscribe(new NotifySub(jedisPool), service + PATH_SEPARATOR + ANY_VALUE); // blocking - } - break; - } finally { - jedis.close(); - } - } catch (Throwable t) { // Retry another server - logger.warn("Failed to subscribe service from redis registry. registry: " + entry.getKey() + ", cause: " + t.getMessage(), t); - // If you only have a single redis, you need to take a rest to avoid overtaking a lot of CPU resources - sleep(reconnectPeriod); - } - } - } catch (Throwable t) { - logger.error(t.getMessage(), t); - sleep(reconnectPeriod); - } - } - } catch (Throwable t) { - logger.error(t.getMessage(), t); - } - } - } - - public void shutdown() { - try { - running = false; - jedis.disconnect(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } - - } - -} diff --git a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistryFactory.java b/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistryFactory.java deleted file mode 100644 index 0824b2244c..0000000000 --- a/dubbo-registry/dubbo-registry-redis/src/main/java/org/apache/dubbo/registry/redis/RedisRegistryFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.apache.dubbo.registry.redis; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.support.AbstractRegistryFactory; - -/** - * RedisRegistryFactory - * - */ -public class RedisRegistryFactory extends AbstractRegistryFactory { - - @Override - protected Registry createRegistry(URL url) { - return new RedisRegistry(url); - } - -} diff --git a/dubbo-registry/dubbo-registry-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory b/dubbo-registry/dubbo-registry-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory deleted file mode 100644 index 3214101ac3..0000000000 --- a/dubbo-registry/dubbo-registry-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory +++ /dev/null @@ -1 +0,0 @@ -redis=org.apache.dubbo.registry.redis.RedisRegistryFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java b/dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java deleted file mode 100644 index 755e452f17..0000000000 --- a/dubbo-registry/dubbo-registry-redis/src/test/java/org/apache/dubbo/registry/redis/RedisRegistryTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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.apache.dubbo.registry.redis; - -import org.apache.commons.lang3.SystemUtils; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.Registry; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import redis.embedded.RedisServer; -import redis.embedded.RedisServerBuilder; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - -public class RedisRegistryTest { - - private String service = "org.apache.dubbo.test.injvmServie"; - private URL serviceUrl = URL.valueOf("redis://redis/" + service + "?notify=false&methods=test1,test2"); - private RedisServer redisServer; - private RedisRegistry redisRegistry; - private URL registryUrl; - - @BeforeEach - public void setUp() throws Exception { - int redisPort = NetUtils.getAvailablePort(); - RedisServerBuilder builder = RedisServer.builder().port(redisPort); - if (SystemUtils.IS_OS_WINDOWS) { - // set maxheap to fix Windows error 0x70 while starting redis - builder.setting("maxheap 128mb"); - } - this.redisServer = builder.build(); - this.redisServer.start(); - this.registryUrl = URL.valueOf("redis://localhost:" + redisPort); - redisRegistry = (RedisRegistry) new RedisRegistryFactory().createRegistry(registryUrl); - } - - @AfterEach - public void tearDown() throws Exception { - this.redisServer.stop(); - } - - @Test - public void testRegister() { - Set registered = null; - - for (int i = 0; i < 2; i++) { - redisRegistry.register(serviceUrl); - registered = redisRegistry.getRegistered(); - assertThat(registered.contains(serviceUrl), is(true)); - } - - registered = redisRegistry.getRegistered(); - assertThat(registered.size(), is(1)); - } - - @Test - public void testAnyHost() { - Assertions.assertThrows(IllegalStateException.class, () -> { - URL errorUrl = URL.valueOf("multicast://0.0.0.0/"); - new RedisRegistryFactory().createRegistry(errorUrl); - }); - } - - - @Test - public void testSubscribeAndUnsubscribe() { - NotifyListener listener = new NotifyListener() { - @Override - public void notify(List urls) { - - } - }; - redisRegistry.subscribe(serviceUrl, listener); - - Map> subscribed = redisRegistry.getSubscribed(); - assertThat(subscribed.size(), is(1)); - assertThat(subscribed.get(serviceUrl).size(), is(1)); - - redisRegistry.unsubscribe(serviceUrl, listener); - subscribed = redisRegistry.getSubscribed(); - assertThat(subscribed.get(serviceUrl).size(), is(0)); - } - - @Test - public void testAvailable() { - redisRegistry.register(serviceUrl); - assertThat(redisRegistry.isAvailable(), is(true)); - - redisRegistry.destroy(); - assertThat(redisRegistry.isAvailable(), is(false)); - } - - @Test - public void testAvailableWithBackup() { - URL url = URL.valueOf("redis://redisOne:8880").addParameter(BACKUP_KEY, "redisTwo:8881"); - Registry registry = new RedisRegistryFactory().createRegistry(url); - - assertThat(registry.isAvailable(), is(false)); - - url = URL.valueOf(this.registryUrl.toFullString()).addParameter(BACKUP_KEY, "redisTwo:8881"); - registry = new RedisRegistryFactory().createRegistry(url); - - assertThat(registry.isAvailable(), is(true)); - } -} diff --git a/dubbo-registry/dubbo-registry-sofa/pom.xml b/dubbo-registry/dubbo-registry-sofa/pom.xml deleted file mode 100644 index 007d3f0cc1..0000000000 --- a/dubbo-registry/dubbo-registry-sofa/pom.xml +++ /dev/null @@ -1,134 +0,0 @@ - - - - org.apache.dubbo - dubbo-registry - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-registry-sofa - ${project.artifactId} - The SOFARegistry module of Dubbo project - - - 2.1 - -Dnetwork_interface_denylist=docker0 - - - - - org.apache.dubbo - dubbo-registry-api - ${project.version} - true - - - - org.apache.dubbo - dubbo-common - ${project.version} - true - - - - com.alipay.sofa - registry-client-all - - - com.alipay.sofa - sofa-common-tools - - - - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.version} - test - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.version} - test - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.version} - test - - - ch.qos.logback - logback-classic - test - - - - - com.alipay.sofa - registry-test - test - - - log4j-over-slf4j - org.slf4j - - - log4j-jcl - org.apache.logging.log4j - - - log4j-core - org.apache.logging.log4j - - - log4j-api - org.apache.logging.log4j - - - - - - org.jboss.resteasy - resteasy-jaxrs - test - - - org.jboss.resteasy - resteasy-netty4 - test - - - javax.ws.rs - javax.ws.rs-api - ${javax.ws.rs.version} - test - - - javax.xml.bind - jaxb-api - test - - - - \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java deleted file mode 100644 index 4c784b34b2..0000000000 --- a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistry.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * 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.apache.dubbo.registry.sofa; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ConfigUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.support.FailbackRegistry; - -import com.alipay.sofa.registry.client.api.RegistryClient; -import com.alipay.sofa.registry.client.api.RegistryClientConfig; -import com.alipay.sofa.registry.client.api.Subscriber; -import com.alipay.sofa.registry.client.api.model.RegistryType; -import com.alipay.sofa.registry.client.api.model.UserData; -import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; -import com.alipay.sofa.registry.client.api.registration.SubscriberRegistration; -import com.alipay.sofa.registry.client.provider.DefaultRegistryClient; -import com.alipay.sofa.registry.client.provider.DefaultRegistryClientConfigBuilder; -import com.alipay.sofa.registry.core.model.ScopeEnum; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.apache.dubbo.registry.Constants.CONSUMER_PROTOCOL; -import static org.apache.dubbo.registry.Constants.PROVIDER_PROTOCOL; -import static org.apache.dubbo.registry.Constants.REGISTER_KEY; -import static org.apache.dubbo.registry.Constants.SUBSCRIBE_KEY; -import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.ADDRESS_WAIT_TIME_KEY; -import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.DEFAULT_GROUP; -import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.LOCAL_DATA_CENTER; -import static org.apache.dubbo.registry.sofa.SofaRegistryConstants.LOCAL_REGION; - -/** - * The Sofa registry. - * - * @since 2.7.2 - */ -public class SofaRegistry extends FailbackRegistry { - - private static final Logger LOGGER = LoggerFactory.getLogger(SofaRegistry.class); - - /** - * Cache subscriber by dataId - */ - private final Map subscribers = new ConcurrentHashMap<>(); - - /** - * Direct registry client - */ - private RegistryClient registryClient; - /** - * wait address from registry - */ - private int waitAddressTimeout; - - /** - * Instantiates a new Sofa registry. - * - * @param url the url - */ - public SofaRegistry(URL url) { - super(url); - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Build sofa registry by url:" + url); - } - this.registryClient = buildClient(url); - this.waitAddressTimeout = Integer.parseInt(ConfigUtils.getProperty(ADDRESS_WAIT_TIME_KEY, "5000")); - } - - /** - * Build client registry client. - * - * @param url the url - * @return the registry client - */ - protected RegistryClient buildClient(URL url) { - RegistryClientConfig config = DefaultRegistryClientConfigBuilder.start() - .setDataCenter(LOCAL_DATA_CENTER) - .setZone(LOCAL_REGION) - .setRegistryEndpoint(url.getHost()) - .setRegistryEndpointPort(url.getPort()).build(); - - DefaultRegistryClient registryClient = new DefaultRegistryClient(config); - registryClient.init(); - return registryClient; - } - - @Override - public boolean isAvailable() { - return true; - } - - @Override - public void doRegister(URL url) { - if (!url.getParameter(REGISTER_KEY, true) - || CONSUMER_PROTOCOL.equals(url.getProtocol())) { - return; - } - - String serviceName = buildServiceName(url); - String serviceData = url.toFullString(); - - PublisherRegistration registration = new PublisherRegistration(serviceName); - addAttributesForPub(registration); - - registryClient.register(registration, serviceData); - } - - /** - * Add attributes for pub. - * - * @param publisherRegistration the publisher registration - */ - protected void addAttributesForPub(PublisherRegistration publisherRegistration) { - publisherRegistration.setGroup(DEFAULT_GROUP); - } - - @Override - public void doUnregister(URL url) { - if (!url.getParameter(REGISTER_KEY, true) - || CONSUMER_PROTOCOL.equals(url.getProtocol())) { - return; - } - String serviceName = buildServiceName(url); - registryClient.unregister(serviceName, DEFAULT_GROUP, RegistryType.PUBLISHER); - } - - @Override - public void doSubscribe(URL url, final NotifyListener listener) { - if (!url.getParameter(SUBSCRIBE_KEY, true) - || PROVIDER_PROTOCOL.equals(url.getProtocol())) { - return; - } - - String serviceName = buildServiceName(url); - // com.alipay.test.TestService:1.0:group@dubbo - Subscriber listSubscriber = subscribers.get(serviceName); - - if (listSubscriber != null) { - LOGGER.warn("Service name [" + serviceName + "] have bean registered in SOFARegistry."); - - CountDownLatch countDownLatch = new CountDownLatch(1); - handleRegistryData(listSubscriber.peekData(), listener, countDownLatch); - waitAddress(serviceName, countDownLatch); - return; - } - - final CountDownLatch latch = new CountDownLatch(1); - SubscriberRegistration subscriberRegistration = new SubscriberRegistration(serviceName, - (dataId, data) -> { - //record change - printAddressData(dataId, data); - handleRegistryData(data, listener, latch); - }); - - addAttributesForSub(subscriberRegistration); - listSubscriber = registryClient.register(subscriberRegistration); - - subscribers.put(serviceName, listSubscriber); - - waitAddress(serviceName, latch); - } - - private void waitAddress(String serviceName, CountDownLatch countDownLatch) { - try { - if (!countDownLatch.await(waitAddressTimeout, TimeUnit.MILLISECONDS)) { - LOGGER.warn("Subscribe data failed by dataId " + serviceName); - } - } catch (Exception e) { - LOGGER.error("Error when wait Address!", e); - } - } - - @Override - public void doUnsubscribe(URL url, NotifyListener listener) { - if (!url.getParameter(SUBSCRIBE_KEY, true) - || PROVIDER_PROTOCOL.equals(url.getProtocol())) { - return; - } - String serviceName = buildServiceName(url); - - registryClient.unregister(serviceName, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - } - - private void handleRegistryData(UserData data, NotifyListener notifyListener, - CountDownLatch latch) { - try { - List urls = new ArrayList<>(); - if (null != data) { - - List datas = flatUserData(data); - for (String serviceUrl : datas) { - URL url = URL.valueOf(serviceUrl); - String serverApplication = url.getParameter(APPLICATION_KEY); - if (StringUtils.isNotEmpty(serverApplication)) { - url = url.addParameter("dstApp", serverApplication); - } - urls.add(url); - } - } - notifyListener.notify(urls); - } finally { - latch.countDown(); - } - } - - private String buildServiceName(URL url) { - // return url.getServiceKey(); - StringBuilder buf = new StringBuilder(); - buf.append(url.getServiceInterface()); - String version = url.getParameter(VERSION_KEY); - if (StringUtils.isNotEmpty(version)) { - buf.append(":").append(version); - } - String group = url.getParameter(GROUP_KEY); - if (StringUtils.isNotEmpty(group)) { - buf.append(":").append(group); - } - buf.append("@").append(DUBBO); - return buf.toString(); - } - - /** - * Print address data. - * - * @param dataId the data id - * @param userData the user data - */ - protected void printAddressData(String dataId, UserData userData) { - - List datas; - if (userData == null) { - datas = new ArrayList<>(0); - } else { - datas = flatUserData(userData); - } - - StringBuilder sb = new StringBuilder(); - for (String provider : datas) { - sb.append(" >>> ").append(provider).append("\n"); - } - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Receive updated RPC service addresses: service[" + dataId - + "]\n .Available target addresses size [" + datas.size() + "]\n" - + sb.toString()); - } - } - - /** - * Add attributes for sub. - * - * @param subscriberRegistration the subscriber registration - */ - protected void addAttributesForSub(SubscriberRegistration subscriberRegistration) { - subscriberRegistration.setGroup(DEFAULT_GROUP); - subscriberRegistration.setScopeEnum(ScopeEnum.global); - } - - /** - * Flat user data list. - * - * @param userData the user data - * @return the list - */ - protected List flatUserData(UserData userData) { - List result = new ArrayList<>(); - Map> zoneData = userData.getZoneData(); - - for (Map.Entry> entry : zoneData.entrySet()) { - result.addAll(entry.getValue()); - } - - return result; - } -} diff --git a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryConstants.java b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryConstants.java deleted file mode 100644 index f832e802f6..0000000000 --- a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryConstants.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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.apache.dubbo.registry.sofa; - -/** - * @since 2.7.2 - */ -public class SofaRegistryConstants { - - /** - * Default data center - */ - public static final String LOCAL_DATA_CENTER = "DefaultDataCenter"; - - /** - * Default region - */ - public static final String LOCAL_REGION = "DEFAULT_ZONE"; - - /** - * Default group - */ - public static final String DEFAULT_GROUP = "SOFA"; - - /** - * parameter for address.wait.time of rpc reference - */ - public static final String ADDRESS_WAIT_TIME_KEY = "rpc.reference.address.wait.time"; -} diff --git a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryFactory.java b/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryFactory.java deleted file mode 100644 index 18a7809ea5..0000000000 --- a/dubbo-registry/dubbo-registry-sofa/src/main/java/org/apache/dubbo/registry/sofa/SofaRegistryFactory.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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.apache.dubbo.registry.sofa; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.registry.Registry; -import org.apache.dubbo.registry.support.AbstractRegistryFactory; - -/** - * @since 2.7.2 - */ -public class SofaRegistryFactory extends AbstractRegistryFactory { - - @Override - protected Registry createRegistry(URL url) { - initEnvironment(url); - return new SofaRegistry(url); - } - - /** - * For extension, such as load zone/accessKey/secretKey/... - * - * @param url URL - */ - protected void initEnvironment(URL url) { - } -} diff --git a/dubbo-registry/dubbo-registry-sofa/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory b/dubbo-registry/dubbo-registry-sofa/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory deleted file mode 100644 index dff4cbb8c5..0000000000 --- a/dubbo-registry/dubbo-registry-sofa/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.registry.RegistryFactory +++ /dev/null @@ -1 +0,0 @@ -sofa=org.apache.dubbo.registry.sofa.SofaRegistryFactory \ No newline at end of file diff --git a/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloService.java b/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloService.java deleted file mode 100644 index cc66a5ede5..0000000000 --- a/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloService.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * 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.apache.dubbo.registry.sofa; - -/** - */ -public interface HelloService { - - String sayHello(String name); -} diff --git a/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloServiceImpl.java b/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloServiceImpl.java deleted file mode 100644 index a9fb0ca707..0000000000 --- a/dubbo-registry/dubbo-registry-sofa/src/test/java/org/apache/dubbo/registry/sofa/HelloServiceImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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.apache.dubbo.registry.sofa; - -import com.alipay.sofa.registry.server.test.TestRegistryMain; - -/** - */ -public class HelloServiceImpl implements HelloService { - - private final String result; - - public HelloServiceImpl(String result) { - this.result = result; - } - - @Override - public String sayHello(String name) { - return result != null ? result : "hello, " + name + "!"; - } - - public static void main(String[] args) { - TestRegistryMain registryMain = new TestRegistryMain(); - try { - registryMain.startRegistry(); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/dubbo-registry/dubbo-registry-sofa/src/test/resources/log4j.properties b/dubbo-registry/dubbo-registry-sofa/src/test/resources/log4j.properties deleted file mode 100644 index 15a0900f0d..0000000000 --- a/dubbo-registry/dubbo-registry-sofa/src/test/resources/log4j.properties +++ /dev/null @@ -1,7 +0,0 @@ -###set log levels### -log4j.rootLogger=info, stdout -###output to the console### -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{dd/MM/yy HH:mm:ss:SSS z}] %t %5p %c{2}: %m%n \ No newline at end of file diff --git a/dubbo-registry/pom.xml b/dubbo-registry/pom.xml index 5ab688ae74..3f9b247117 100644 --- a/dubbo-registry/pom.xml +++ b/dubbo-registry/pom.xml @@ -31,15 +31,9 @@ dubbo-registry-api - - + dubbo-registry-multicast dubbo-registry-zookeeper - - - - - - - + dubbo-registry-nacos + dubbo-registry-multiple diff --git a/dubbo-remoting/dubbo-remoting-etcd3/pom.xml b/dubbo-remoting/dubbo-remoting-etcd3/pom.xml deleted file mode 100644 index 1e4980b4e4..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/pom.xml +++ /dev/null @@ -1,107 +0,0 @@ - - - - - 4.0.0 - - dubbo-remoting - org.apache.dubbo - ${revision} - ../pom.xml - - dubbo-remoting-etcd3 - jar - ${project.artifactId} - The etcd3 remoting module of Dubbo project - - false - 3.13.2 - true - - - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - io.etcd - jetcd-core - - - io.grpc - grpc-core - - - io.grpc - grpc-netty - - - io.grpc - grpc-protobuf - - - io.grpc - grpc-stub - - - io.grpc - grpc-grpclb - - - - io.etcd - jetcd-launcher - test - - - - io.netty - netty-all - - - org.assertj - assertj-core - ${assertj.version} - test - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - ${skipIntegrationTests} - - - - - - - diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/AbstractRetryPolicy.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/AbstractRetryPolicy.java deleted file mode 100644 index b084ba3624..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/AbstractRetryPolicy.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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.apache.dubbo.remoting.etcd; - -public abstract class AbstractRetryPolicy implements RetryPolicy { - - private final int maxRetried; - - protected AbstractRetryPolicy(int maxRetried) { - this.maxRetried = maxRetried; - } - - @Override - public boolean shouldRetry(int retried, long elapsed, boolean sleep) { - if (retried < maxRetried) { - try { - if (sleep) { - Thread.sleep(getSleepTime(retried, elapsed)); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return false; - } - return true; - } - return false; - } - - protected abstract long getSleepTime(int retried, long elapsed); - -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/ChildListener.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/ChildListener.java deleted file mode 100644 index 46a0af8cee..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/ChildListener.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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.apache.dubbo.remoting.etcd; - -import java.util.List; - -public interface ChildListener { - - void childChanged(String path, List children); - -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java deleted file mode 100644 index 3450bb5b36..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/Constants.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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.apache.dubbo.remoting.etcd; - -import static org.apache.dubbo.remoting.Constants.DEFAULT_IO_THREADS; - -public interface Constants { - String ETCD3_NOTIFY_MAXTHREADS_KEYS = "etcd3.notify.maxthreads"; - - int DEFAULT_ETCD3_NOTIFY_THREADS = DEFAULT_IO_THREADS; - - String DEFAULT_ETCD3_NOTIFY_QUEUES_KEY = "etcd3.notify.queues"; - - int DEFAULT_GRPC_QUEUES = 300_0000; - - String RETRY_PERIOD_KEY = "retry.period"; - - int DEFAULT_RETRY_PERIOD = 5 * 1000; - - int DEFAULT_SESSION_TIMEOUT = 60 * 1000; - - String HTTP_SUBFIX_KEY = "://"; - - String HTTP_KEY = "http://"; - - int DEFAULT_KEEPALIVE_TIMEOUT = DEFAULT_SESSION_TIMEOUT / 2; - - String SESSION_TIMEOUT_KEY = "session"; - - int DEFAULT_RECONNECT_PERIOD = 3 * 1000; - - String ROUTERS_CATEGORY = "routers"; - - String PROVIDERS_CATEGORY = "providers"; - - String CONSUMERS_CATEGORY = "consumers"; - - String CONFIGURATORS_CATEGORY = "configurators"; -} - diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdClient.java deleted file mode 100644 index 7dc20ff34c..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdClient.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * 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. - */ - -/* - * 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.apache.dubbo.remoting.etcd; - -import org.apache.dubbo.common.URL; - -import java.util.List; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -public interface EtcdClient { - - /** - * save the specified path to the etcd registry. - * - * @param path the path to be saved - */ - void create(String path); - - /** - * save the specified path to the etcd registry. - * if node disconnect from etcd, it will be deleted - * automatically by etcd when session timeout. - * - * @param path the path to be saved - * @return the lease of current path. - */ - long createEphemeral(String path); - - /** - * remove the specified from etcd registry. - * - * @param path the path to be removed - */ - void delete(String path); - - /** - * find direct children directory, excluding path self, - * Never return null. - * - * @param path the path to be found direct children. - * @return direct children directory, contains zero element - * list if children directory not exists. - */ - List getChildren(String path); - - /** - * register children listener for specified path. - * - * @param path the path to be watched when children is added, delete or update. - * @param listener when children is changed , listener will be trigged. - * @return direct children directory, contains zero element - * list if children directory not exists. - */ - List addChildListener(String path, ChildListener listener); - - /** - * find watcher of the children listener for specified path. - * - * @param path the path to be watched when children is added, delete or update. - * @param listener when children is changed , listener will be trigged. - * @return watcher if find else null - */ - T getChildListener(String path, ChildListener listener); - - /** - * unregister children lister for specified path. - * - * @param path the path to be unwatched . - * @param listener when children is changed , lister will be trigged. - */ - void removeChildListener(String path, ChildListener listener); - - /** - * support connection notify if connection state was changed. - * - * @param listener if state changed, listener will be triggered. - */ - void addStateListener(StateListener listener); - - /** - * remove connection notify if connection state was changed. - * - * @param listener remove already registered listener, if listener - * not exists nothing happened. - */ - void removeStateListener(StateListener listener); - - /** - * test if current client is active. - * - * @return true if connection is active else false. - */ - boolean isConnected(); - - /** - * close current client and release all resourses. - */ - void close(); - - URL getUrl(); - - /*** - * create new lease from specified second ,it should be waiting if failed.

    - * - * @param second lease time (support second only). - * @return lease id from etcd - */ - long createLease(long second); - - /*** - * create new lease from specified ttl second before waiting specified timeout.

    - * - * @param ttl lease time (support second only). - * @param timeout the maximum time to wait - * @param unit the time unit of the timeout argument - * @throws CancellationException if this future was cancelled - * @throws ExecutionException if this future completed exceptionally - * @throws InterruptedException if the current thread was interrupted - * while waiting - * @throws TimeoutException if the wait timed out - * @return lease id from etcd - */ - long createLease(long ttl, long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException; - - /** - * revoke specified lease, any associated path will removed automatically. - * - * @param lease to be removed lease - */ - void revokeLease(long lease); - - - /** - * Get the value of the specified key. - * @param key the specified key - * @return null if the value is not found - */ - String getKVValue(String key); - - /** - * Put the key value pair to etcd - * @param key the specified key - * @param value the paired value - * @return true if put success - */ - boolean put(String key, String value); - - /** - * Put the key value pair to etcd (Ephemeral) - * @param key the specified key - * @param value the paired value - * @return true if put success - */ - boolean putEphemeral(String key, String value); - -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java deleted file mode 100644 index 754ba64662..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/EtcdTransporter.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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. - */ - -/* - * 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.apache.dubbo.remoting.etcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Adaptive; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.remoting.Constants; - -@SPI("jetcd") -public interface EtcdTransporter { - - @Adaptive({Constants.CLIENT_KEY, Constants.TRANSPORTER_KEY}) - EtcdClient connect(URL url); - -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/RetryPolicy.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/RetryPolicy.java deleted file mode 100644 index 6133ab713c..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/RetryPolicy.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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.apache.dubbo.remoting.etcd; - -public interface RetryPolicy { - - /** - * Whether retry is supported when operation fails. - * - * @param retried the number of times retried so far - * @param elapsed the elapsed time in millisecond since the operation was attempted - * @param sleep should be sleep - * @return true should be retry - */ - boolean shouldRetry(int retried, long elapsed, boolean sleep); - -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/StateListener.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/StateListener.java deleted file mode 100644 index 4358083739..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/StateListener.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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.apache.dubbo.remoting.etcd; - -public interface StateListener { - - int DISCONNECTED = 0; - - int CONNECTED = 1; - - void stateChanged(int connected); - -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/ConnectionStateListener.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/ConnectionStateListener.java deleted file mode 100644 index 788aa401e9..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/ConnectionStateListener.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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.apache.dubbo.remoting.etcd.jetcd; - -import io.etcd.jetcd.Client; - -public interface ConnectionStateListener { - - /** - * Called when there is a state change in the connection - * - * @param client the client - * @param newState the new state - */ - void stateChanged(Client client, int newState); -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java deleted file mode 100644 index 0da56fa5a8..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClient.java +++ /dev/null @@ -1,473 +0,0 @@ -/* - * 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.apache.dubbo.remoting.etcd.jetcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ExecutorUtil; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.remoting.etcd.ChildListener; -import org.apache.dubbo.remoting.etcd.StateListener; -import org.apache.dubbo.remoting.etcd.option.OptionUtil; -import org.apache.dubbo.remoting.etcd.support.AbstractEtcdClient; - -import com.google.protobuf.ByteString; -import io.etcd.jetcd.ByteSequence; -import io.etcd.jetcd.api.Event; -import io.etcd.jetcd.api.KeyValue; -import io.etcd.jetcd.api.WatchCancelRequest; -import io.etcd.jetcd.api.WatchCreateRequest; -import io.etcd.jetcd.api.WatchGrpc; -import io.etcd.jetcd.api.WatchRequest; -import io.etcd.jetcd.api.WatchResponse; -import io.etcd.jetcd.common.exception.ClosedClientException; -import io.grpc.ManagedChannel; -import io.grpc.Status; -import io.grpc.stub.StreamObserver; -import io.netty.util.internal.ConcurrentSet; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Random; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.locks.ReentrantLock; - -import static java.util.stream.Collectors.toList; -import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; -import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_ETCD3_NOTIFY_QUEUES_KEY; -import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_ETCD3_NOTIFY_THREADS; -import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_GRPC_QUEUES; -import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_RETRY_PERIOD; -import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_SESSION_TIMEOUT; -import static org.apache.dubbo.remoting.etcd.Constants.ETCD3_NOTIFY_MAXTHREADS_KEYS; -import static org.apache.dubbo.remoting.etcd.Constants.RETRY_PERIOD_KEY; -import static org.apache.dubbo.remoting.etcd.jetcd.JEtcdClientWrapper.UTF_8; - -/** - * etcd3 client. - */ -public class JEtcdClient extends AbstractEtcdClient { - - private JEtcdClientWrapper clientWrapper; - private ScheduledExecutorService reconnectSchedule; - - private ExecutorService notifyExecutor; - - private int delayPeriod; - private Logger logger = LoggerFactory.getLogger(JEtcdClient.class); - - public JEtcdClient(URL url) { - super(url); - try { - clientWrapper = new JEtcdClientWrapper(url); - clientWrapper.setConnectionStateListener((client, state) -> { - if (state == StateListener.CONNECTED) { - JEtcdClient.this.stateChanged(StateListener.CONNECTED); - } else if (state == StateListener.DISCONNECTED) { - JEtcdClient.this.stateChanged(StateListener.DISCONNECTED); - } - }); - delayPeriod = getUrl().getParameter(RETRY_PERIOD_KEY, DEFAULT_RETRY_PERIOD); - reconnectSchedule = Executors.newScheduledThreadPool(1, - new NamedThreadFactory("etcd3-watch-auto-reconnect")); - - notifyExecutor = new ThreadPoolExecutor( - 1 - , url.getParameter(ETCD3_NOTIFY_MAXTHREADS_KEYS, DEFAULT_ETCD3_NOTIFY_THREADS) - , DEFAULT_SESSION_TIMEOUT - , TimeUnit.MILLISECONDS - , new LinkedBlockingQueue(url.getParameter(DEFAULT_ETCD3_NOTIFY_QUEUES_KEY, DEFAULT_GRPC_QUEUES * 3)) - , new NamedThreadFactory("etcd3-notify", true)); - - clientWrapper.start(); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - @Override - public void doCreatePersistent(String path) { - clientWrapper.createPersistent(path); - } - - @Override - public long doCreateEphemeral(String path) { - return clientWrapper.createEphemeral(path); - } - - @Override - public boolean checkExists(String path) { - return clientWrapper.checkExists(path); - } - - @Override - public EtcdWatcher createChildWatcherListener(String path, ChildListener listener) { - return new EtcdWatcher(listener); - } - - @Override - public List addChildWatcherListener(String path, EtcdWatcher etcdWatcher) { - return etcdWatcher.forPath(path); - } - - @Override - public void removeChildWatcherListener(String path, EtcdWatcher etcdWatcher) { - etcdWatcher.unwatch(); - } - - @Override - public List getChildren(String path) { - return clientWrapper.getChildren(path); - } - - @Override - public boolean isConnected() { - return clientWrapper.isConnected(); - } - - @Override - public long createLease(long second) { - return clientWrapper.createLease(second); - } - - @Override - public long createLease(long ttl, long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - return clientWrapper.createLease(ttl, timeout, unit); - } - - @Override - public void delete(String path) { - clientWrapper.delete(path); - } - - @Override - public void revokeLease(long lease) { - clientWrapper.revokeLease(lease); - } - - @Override - public void doClose() { - try { - if (notifyExecutor != null) { - ExecutorUtil.shutdownNow(notifyExecutor, 100); - } - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - - try { - if (reconnectSchedule != null) { - ExecutorUtil.shutdownNow(reconnectSchedule, 100); - } - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } finally { - clientWrapper.doClose(); - } - } - - @Override - public String getKVValue(String key) { - return clientWrapper.getKVValue(key); - } - - @Override - public boolean put(String key, String value) { - return clientWrapper.put(key, value); - } - - @Override - public boolean putEphemeral(String key, String value) { - return clientWrapper.putEphemeral(key, value); - } - - public ManagedChannel getChannel() { - return clientWrapper.getChannel(); - } - - public class EtcdWatcher implements StreamObserver { - - protected WatchGrpc.WatchStub watchStub; - protected StreamObserver watchRequest; - protected long watchId; - protected String path; - protected Throwable throwable; - protected volatile Set urls = new ConcurrentSet<>(); - private ChildListener listener; - - protected ReentrantLock lock = new ReentrantLock(true); - - public EtcdWatcher(ChildListener listener) { - this.listener = listener; - } - - @Override - public void onNext(WatchResponse response) { - - // prevents grpc on sending watchResponse to a closed watch client. - if (!isConnected()) { - return; - } - - watchId = response.getWatchId(); - - if (listener != null) { - int modified = 0; - String service = null; - Iterator iterator = response.getEventsList().iterator(); - while (iterator.hasNext()) { - Event event = iterator.next(); - switch (event.getType()) { - case PUT: { - if (((service = find(event)) != null) - && safeUpdate(service, true)) { - modified++; - } - break; - } - case DELETE: { - if (((service = find(event)) != null) - && safeUpdate(service, false)) { - modified++; - } - break; - } - default: - break; - } - } - if (modified > 0) { - notifyExecutor.execute(() -> listener.childChanged(path, new ArrayList<>(urls))); - } - - } - } - - @Override - public void onError(Throwable e) { - tryReconnect(e); - } - - public void unwatch() { - - // prevents grpc on sending watchResponse to a closed watch client. - if (!isConnected()) { - return; - } - - try { - /** - * issue : https://github.com/apache/dubbo/issues/4115 - * - * When the network is reconnected, the listener is empty - * and the data cannot be received. - */ - // this.listener = null; - - if (watchRequest != null) { - WatchCancelRequest watchCancelRequest = - WatchCancelRequest.newBuilder().setWatchId(watchId).build(); - WatchRequest cancelRequest = WatchRequest.newBuilder() - .setCancelRequest(watchCancelRequest).build(); - this.watchRequest.onNext(cancelRequest); - } - } catch (Exception ignored) { - logger.warn("Failed to cancel watch for path '" + path + "'", ignored); - } - } - - public List forPath(String path) { - - if (!isConnected()) { - throw new ClosedClientException("watch client has been closed, path '" + path + "'"); - } - if (this.path != null) { - unwatch(); - } - - this.path = path; - - lock.lock(); - try { - - this.watchStub = WatchGrpc.newStub(clientWrapper.getChannel()); - this.watchRequest = watchStub.watch(this); - this.watchRequest.onNext(nextRequest()); - - List children = clientWrapper.getChildren(path); - /** - * caching the current service - */ - if (!children.isEmpty()) { - this.urls.addAll(filterChildren(children)); - } - - return new ArrayList<>(urls); - } finally { - lock.unlock(); - } - } - - private boolean safeUpdate(String service, boolean add) { - lock.lock(); - try { - /** - * If the collection already contains the specified service, do nothing - */ - return add ? this.urls.add(service) : this.urls.remove(service); - } finally { - lock.unlock(); - } - } - - private String find(Event event) { - KeyValue keyValue = event.getKv(); - String key = keyValue.getKey().toStringUtf8(); - - int len = path.length(), index = len, count = 0; - if (key.length() >= index) { - for (; (index = key.indexOf(PATH_SEPARATOR, index)) != -1; ++index) { - if (count++ > 1) { - break; - } - } - } - - /** - * if children changed , we should refresh invokers - */ - if (count == 1) { - /** - * remove prefix - */ - return key.substring(len + 1); - } - - return null; - } - - private List filterChildren(List children) { - if (children == null) { - return Collections.emptyList(); - } - if (children.size() <= 0) { - return children; - } - final int len = path.length(); - return children.stream().parallel() - .filter(child -> { - int index = len, count = 0; - if (child.length() > len) { - for (; (index = child.indexOf(PATH_SEPARATOR, index)) != -1; ++index) { - if (count++ > 1) { - break; - } - } - } - return count == 1; - }) - .map(child -> child.substring(len + 1)) - .collect(toList()); - } - - /** - * create new watching request for current path. - */ - protected WatchRequest nextRequest() { - - WatchCreateRequest.Builder builder = WatchCreateRequest.newBuilder() - .setKey(ByteString.copyFromUtf8(path)) - .setRangeEnd(ByteString.copyFrom( - OptionUtil.prefixEndOf(ByteSequence.from(path, UTF_8)).getBytes())) - .setProgressNotify(true); - - return WatchRequest.newBuilder().setCreateRequest(builder).build(); - } - - public void tryReconnect(Throwable e) { - - this.throwable = e; - - logger.error("watcher client has error occurred, current path '" + path + "'", e); - - // prevents grpc on sending error to a closed watch client. - if (!isConnected()) { - return; - } - - - Status status = Status.fromThrowable(e); - // system may be recover later, current connect won't be lost - if (OptionUtil.isHaltError(status) || OptionUtil.isNoLeaderError(status)) { - reconnectSchedule.schedule(this::reconnect, new Random().nextInt(delayPeriod), TimeUnit.MILLISECONDS); - return; - } - // reconnect with a delay; avoiding immediate retry on a long connection downtime. - reconnectSchedule.schedule(this::reconnect, new Random().nextInt(delayPeriod), TimeUnit.MILLISECONDS); - } - - protected synchronized void reconnect() { - this.closeWatchRequest(); - this.recreateWatchRequest(); - } - - protected void recreateWatchRequest() { - if (watchRequest == null) { - this.watchStub = WatchGrpc.newStub(clientWrapper.getChannel()); - this.watchRequest = watchStub.watch(this); - } - this.watchRequest.onNext(nextRequest()); - this.throwable = null; - logger.warn("watch client retried connect for path '" + path + "', connection status : " + isConnected()); - } - - protected void closeWatchRequest() { - if (this.watchRequest == null) { - return; - } - - try { - WatchCancelRequest watchCancelRequest = - WatchCancelRequest.newBuilder().setWatchId(watchId).build(); - WatchRequest cancelRequest = WatchRequest.newBuilder() - .setCancelRequest(watchCancelRequest).build(); - watchRequest.onNext(cancelRequest); - } finally { - this.watchRequest.onCompleted(); - this.watchRequest = null; - } - } - - @Override - public void onCompleted() { - // do not touch this method, if you want terminate this stream. - } - } -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java deleted file mode 100644 index f1c01517c2..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapper.java +++ /dev/null @@ -1,754 +0,0 @@ -/* - * 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.apache.dubbo.remoting.etcd.jetcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ConcurrentHashSet; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.remoting.etcd.RetryPolicy; -import org.apache.dubbo.remoting.etcd.StateListener; - -import io.etcd.jetcd.ByteSequence; -import io.etcd.jetcd.Client; -import io.etcd.jetcd.ClientBuilder; -import io.etcd.jetcd.CloseableClient; -import io.etcd.jetcd.KeyValue; -import io.etcd.jetcd.Observers; -import io.etcd.jetcd.common.exception.ErrorCode; -import io.etcd.jetcd.common.exception.EtcdException; -import io.etcd.jetcd.kv.GetResponse; -import io.etcd.jetcd.kv.PutResponse; -import io.etcd.jetcd.lease.LeaseKeepAliveResponse; -import io.etcd.jetcd.options.GetOption; -import io.etcd.jetcd.options.PutOption; -import io.grpc.ConnectivityState; -import io.grpc.ManagedChannel; -import io.grpc.Status; -import io.grpc.stub.StreamObserver; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.nio.charset.Charset; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; - -import static java.util.stream.Collectors.toList; -import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR; -import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; -import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_KEEPALIVE_TIMEOUT; -import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_RECONNECT_PERIOD; -import static org.apache.dubbo.remoting.etcd.Constants.DEFAULT_RETRY_PERIOD; -import static org.apache.dubbo.remoting.etcd.Constants.HTTP_KEY; -import static org.apache.dubbo.remoting.etcd.Constants.HTTP_SUBFIX_KEY; -import static org.apache.dubbo.remoting.etcd.Constants.RETRY_PERIOD_KEY; -import static org.apache.dubbo.remoting.etcd.Constants.SESSION_TIMEOUT_KEY; - -public class JEtcdClientWrapper { - - private Logger logger = LoggerFactory.getLogger(JEtcdClientWrapper.class); - - private final URL url; - private volatile Client client; - private volatile boolean started = false; - private volatile boolean connectState = false; - private ScheduledFuture future; - private ScheduledExecutorService reconnectNotify; - private AtomicReference channel; - - private ConnectionStateListener connectionStateListener; - - private long expirePeriod; - - private CompletableFuture completableFuture; - - private RetryPolicy retryPolicy; - - private RuntimeException failed; - - private final ScheduledFuture retryFuture; - private final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(1, - new NamedThreadFactory("Etcd3RegistryKeepAliveFailedRetryTimer", true)); - - private final Set failedRegistered = new ConcurrentHashSet(); - - private final Set registeredPaths = new ConcurrentHashSet<>(); - private volatile CloseableClient keepAlive = null; - - /** - * Support temporary nodes to reuse the same lease - */ - private volatile long globalLeaseId; - - private volatile boolean cancelKeepAlive = false; - - public static final Charset UTF_8 = Charset.forName("UTF-8"); - - public JEtcdClientWrapper(URL url) { - this.url = url; - this.expirePeriod = url.getParameter(SESSION_TIMEOUT_KEY, DEFAULT_KEEPALIVE_TIMEOUT) / 1000; - if (expirePeriod <= 0) { - this.expirePeriod = DEFAULT_KEEPALIVE_TIMEOUT / 1000; - } - this.channel = new AtomicReference<>(); - this.completableFuture = CompletableFuture.supplyAsync(() -> prepareClient(url)); - this.reconnectNotify = Executors.newScheduledThreadPool(1, - new NamedThreadFactory("reconnectNotify", true)); - this.retryPolicy = new RetryNTimes(1, 1000, TimeUnit.MILLISECONDS); - - this.failed = new IllegalStateException("Etcd3 registry is not connected yet, url:" + url); - int retryPeriod = url.getParameter(RETRY_PERIOD_KEY, DEFAULT_RETRY_PERIOD); - - this.retryFuture = retryExecutor.scheduleWithFixedDelay(() -> { - try { - retry(); - } catch (Throwable t) { - logger.error("Unexpected error occur at failed retry, cause: " + t.getMessage(), t); - } - }, retryPeriod, retryPeriod, TimeUnit.MILLISECONDS); - } - - private Client prepareClient(URL url) { - - int maxInboundSize = DEFAULT_INBOUND_SIZE; - if (StringUtils.isNotEmpty(System.getProperty(GRPC_MAX_INBOUND_SIZE_KEY))) { - maxInboundSize = Integer.valueOf(System.getProperty(GRPC_MAX_INBOUND_SIZE_KEY)); - } - - // TODO, uses default pick-first round robin. - ClientBuilder clientBuilder = Client.builder() - .endpoints(endPoints(url.getBackupAddress())) - .maxInboundMessageSize(maxInboundSize); - - return clientBuilder.build(); - } - - public Client getClient() { - return client; - } - - /** - * try to get current connected channel. - * - * @return connected channel. - */ - public ManagedChannel getChannel() { - if (channel.get() == null || (channel.get().isShutdown() || channel.get().isTerminated())) { - channel.set(newChannel(client)); - } - return channel.get(); - } - - /** - * find direct children directory, excluding path self, - * Never return null. - * - * @param path the path to be found direct children. - * @return direct children directory, contains zero element - * list if children directory not exists. - */ - public List getChildren(String path) { - try { - return RetryLoops.invokeWithRetry( - () -> { - requiredNotNull(client, failed); - int len = path.length(); - return client.getKVClient() - .get(ByteSequence.from(path, UTF_8), - GetOption.newBuilder().withPrefix(ByteSequence.from(path, UTF_8)).build()) - .get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS) - .getKvs().stream().parallel() - .filter(pair -> { - String key = pair.getKey().toString(UTF_8); - int index = len, count = 0; - if (key.length() > len) { - for (; (index = key.indexOf(PATH_SEPARATOR, index)) != -1; ++index) { - if (count++ > 1) { - break; - } - } - } - return count == 1; - }) - .map(pair -> pair.getKey().toString(UTF_8)) - .collect(toList()); - }, retryPolicy); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public boolean isConnected() { - return ConnectivityState.READY == (getChannel().getState(false)) - || ConnectivityState.IDLE == (getChannel().getState(false)); - } - - public long createLease(long second) { - try { - return RetryLoops.invokeWithRetry( - () -> { - requiredNotNull(client, failed); - return client.getLeaseClient() - .grant(second) - .get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS) - .getID(); - }, retryPolicy); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public void revokeLease(long lease) { - try { - RetryLoops.invokeWithRetry( - (Callable) () -> { - requiredNotNull(client, failed); - client.getLeaseClient() - .revoke(lease) - .get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS); - return null; - }, retryPolicy); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public long createLease(long ttl, long timeout, TimeUnit unit) - throws InterruptedException, ExecutionException, TimeoutException { - - if (timeout <= 0) { - return createLease(ttl); - } - - requiredNotNull(client, failed); - return client.getLeaseClient() - .grant(ttl) - .get(timeout, unit).getID(); - } - - - /** - * try to check if path exists. - */ - public boolean checkExists(String path) { - try { - return RetryLoops.invokeWithRetry( - () -> { - requiredNotNull(client, failed); - return client.getKVClient() - .get(ByteSequence.from(path, UTF_8), GetOption.newBuilder().withCountOnly(true).build()) - .get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS) - .getCount() > 0; - }, retryPolicy); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - /** - * only internal use only, maybe change in the future - */ - protected Long find(String path) { - try { - return RetryLoops.invokeWithRetry( - () -> { - requiredNotNull(client, failed); - return client.getKVClient() - .get(ByteSequence.from(path, UTF_8)) - .get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS) - .getKvs().stream() - .mapToLong(keyValue -> Long.valueOf(keyValue.getValue().toString(UTF_8))) - .findFirst().getAsLong(); - }, retryPolicy); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - public void createPersistent(String path) { - try { - RetryLoops.invokeWithRetry( - (Callable) () -> { - requiredNotNull(client, failed); - client.getKVClient() - .put(ByteSequence.from(path, UTF_8), - ByteSequence.from(String.valueOf(path.hashCode()), UTF_8)) - .get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS); - return null; - }, retryPolicy); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - /** - * create new ephemeral path save to etcd . - * if node disconnect from etcd, it will be deleted - * automatically by etcd when session timeout. - * - * @param path the path to be saved - * @return the lease of current path. - */ - public long createEphemeral(String path) { - try { - return RetryLoops.invokeWithRetry( - () -> { - requiredNotNull(client, failed); - - registeredPaths.add(path); - keepAlive(); - final long leaseId = globalLeaseId; - client.getKVClient() - .put(ByteSequence.from(path, UTF_8) - , ByteSequence.from(String.valueOf(leaseId), UTF_8) - , PutOption.newBuilder().withLeaseId(leaseId).build()) - .get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS); - return leaseId; - }, retryPolicy); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - // easy for mock - public void keepAlive(long lease) { - this.keepAlive(lease, null); - } - - @SuppressWarnings("unchecked") - private void keepAlive(long lease, Consumer onFailed) { - final StreamObserver observer = new Observers.Builder() - .onError((e) -> { - if (e instanceof EtcdException) { - EtcdException error = (EtcdException) e; - /** - * ttl has expired - */ - if (error.getErrorCode() == ErrorCode.NOT_FOUND) { - keepAlive0(onFailed); - } - } - }).onCompleted(() -> { - /** - * deadline reached. - */ - keepAlive0(onFailed); - }).build(); - - /** - * If there is already a keepalive, cancel first - */ - cancelKeepAlive(); - - /** - * create and set new keepAlive to globalKeepAliveRef - */ - this.keepAlive = client.getLeaseClient().keepAlive(lease, observer); - } - - private void keepAlive() throws Exception { - if (keepAlive == null) { - synchronized (this) { - if (keepAlive == null) { - this.globalLeaseId = client.getLeaseClient() - .grant(expirePeriod) - .get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS) - .getID(); - /** - * If the keepAlive expires, the registration will be re-attempted - */ - keepAlive(globalLeaseId, (NULL) -> recovery()); - } - } - } - } - - private void keepAlive0(Consumer onFailed) { - if (onFailed != null) { - - /** - * The following two scenarios will cause the keep-alive failure: - * - * 1. Service is offline - * 2. Local deadline check expired - * - * The multiplex lease cannot update the local deadline, - * causing the extreme scene service to be dropped. - * - */ - long leaseId = globalLeaseId; - try { - if (logger.isWarnEnabled()) { - logger.warn("Failed to keep alive for global lease '" + leaseId + "', waiting for retry again."); - } - onFailed.accept(null); - } catch (Exception ignored) { - logger.warn("Failed to recover from global lease expired or lease deadline exceeded. lease '" + leaseId + "'", ignored); - } - } - } - - private void recovery() { - - try { - /** - * The client is processing reconnection - */ - if (cancelKeepAlive) { - return; - } - - cancelKeepAlive(); - - Set ephemeralPaths = new HashSet(registeredPaths); - if (!ephemeralPaths.isEmpty()) { - for (String path : ephemeralPaths) { - try { - - /** - * The client is processing reconnection, - * cancel remaining service registration - */ - if (cancelKeepAlive) { - return; - } - - createEphemeral(path); - failedRegistered.remove(path); - } catch (Exception e) { - - /** - * waiting for retry again - */ - failedRegistered.add(path); - - Status status = Status.fromThrowable(e); - if (status.getCode() == Status.Code.NOT_FOUND) { - cancelKeepAlive(); - } - } - } - } - } catch (Throwable t) { - logger.warn("Unexpected error, failed to recover from global lease expired or deadline exceeded.", t); - } - } - - public void delete(String path) { - try { - RetryLoops.invokeWithRetry( - (Callable) () -> { - requiredNotNull(client, failed); - client.getKVClient() - .delete(ByteSequence.from(path, UTF_8)) - .get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS); - registeredPaths.remove(path); - return null; - }, retryPolicy); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } finally { - /** - * Cancel retry - */ - failedRegistered.remove(path); - } - } - - public String[] endPoints(String backupAddress) { - String[] endpoints = backupAddress.split(COMMA_SEPARATOR); - List addresses = Arrays.stream(endpoints) - .map(address -> address.contains(HTTP_SUBFIX_KEY) - ? address - : HTTP_KEY + address) - .collect(toList()); - Collections.shuffle(addresses); - return addresses.toArray(new String[0]); - } - - /** - * because jetcd's connection change callback not supported yet, we must - * loop to test if connect or disconnect event happend or not. It will be changed - * in the future if we found better choice. - */ - public void start() { - if (!started) { - try { - this.client = completableFuture.get(expirePeriod, TimeUnit.SECONDS); - this.connectState = isConnected(); - this.started = true; - } catch (Throwable t) { - logger.error("Timeout! etcd3 server can not be connected in : " + expirePeriod + " seconds! url: " + url, t); - - completableFuture.whenComplete((c, e) -> { - this.client = c; - if (e != null) { - logger.error("Got an exception when trying to create etcd3 instance, can not connect to etcd3 server, url: " + url, e); - } - }); - - } - - try { - this.future = reconnectNotify.scheduleWithFixedDelay(() -> { - boolean connected = isConnected(); - if (connectState != connected) { - int notifyState = connected ? StateListener.CONNECTED : StateListener.DISCONNECTED; - if (connectionStateListener != null) { - try { - if (connected) { - clearKeepAlive(); - } - connectionStateListener.stateChanged(getClient(), notifyState); - } finally { - cancelKeepAlive = false; - } - } - connectState = connected; - } - }, DEFAULT_RECONNECT_PERIOD, DEFAULT_RECONNECT_PERIOD, TimeUnit.MILLISECONDS); - } catch (Throwable t) { - logger.error("monitor reconnect status failed.", t); - } - } - } - - private void cancelKeepAlive() { - try { - if (keepAlive != null) { - keepAlive.close(); - } - } finally { - // help for gc - keepAlive = null; - } - } - - private void clearKeepAlive() { - cancelKeepAlive = true; - failedRegistered.clear(); - cancelKeepAlive(); - } - - protected void doClose() { - - try { - cancelKeepAlive = true; - if (globalLeaseId != 0) { - revokeLease(this.globalLeaseId); - } - } catch (Exception e) { - logger.warn("revoke global lease '" + globalLeaseId + "' failed, registry: " + url, e); - } - - try { - if (started && future != null) { - started = false; - future.cancel(true); - reconnectNotify.shutdownNow(); - } - } catch (Exception e) { - logger.warn("stop reconnect Notify failed, registry: " + url, e); - } - - try { - retryFuture.cancel(true); - retryExecutor.shutdownNow(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - - if (getClient() != null) { - getClient().close(); - } - } - - /** - * try get client's shared channel, becase all fields is private on jetcd, - * we must using it by reflect, in the future, jetcd may provider better tools. - * - * @param client get channel from current client - * @return current connection channel - */ - private ManagedChannel newChannel(Client client) { - try { - Field connectionField = client.getClass().getDeclaredField("connectionManager"); - if (!connectionField.isAccessible()) { - connectionField.setAccessible(true); - } - Object connection = connectionField.get(client); - Method channel = connection.getClass().getDeclaredMethod("getChannel"); - if (!channel.isAccessible()) { - channel.setAccessible(true); - } - return (ManagedChannel) channel.invoke(connection); - } catch (Exception e) { - throw new RuntimeException("Failed to obtain connection channel from " + url.getBackupAddress(), e); - } - } - - public ConnectionStateListener getConnectionStateListener() { - return connectionStateListener; - } - - public void setConnectionStateListener(ConnectionStateListener connectionStateListener) { - this.connectionStateListener = connectionStateListener; - } - - public static void requiredNotNull(Object obj, RuntimeException exeception) { - if (obj == null) { - throw exeception; - } - } - - public String getKVValue(String key) { - if (null == key) { - return null; - } - - CompletableFuture responseFuture = this.client.getKVClient().get(ByteSequence.from(key, UTF_8)); - - try { - List result = responseFuture.get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS).getKvs(); - if (!result.isEmpty()) { - return result.get(0).getValue().toString(UTF_8); - } - } catch (Exception e) { - // ignore - } - - return null; - } - - - public boolean put(String key, String value) { - if (key == null || value == null) { - return false; - } - CompletableFuture putFuture = - this.client.getKVClient().put(ByteSequence.from(key, UTF_8), ByteSequence.from(value, UTF_8)); - try { - putFuture.get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS); - return true; - } catch (Exception e) { - // ignore - } - return false; - } - - public boolean putEphemeral(final String key, String value) { - try { - return RetryLoops.invokeWithRetry( - () -> { - requiredNotNull(client, failed); - // recovery an retry - keepAlive(); - final long leaseId = globalLeaseId; - client.getKVClient() - .put(ByteSequence.from(key, UTF_8) - , ByteSequence.from(String.valueOf(value), UTF_8) - , PutOption.newBuilder().withLeaseId(leaseId).build()) - .get(DEFAULT_REQUEST_TIMEOUT, TimeUnit.MILLISECONDS); - return true; - }, retryPolicy); - } catch (Exception e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private void retry() { - if (!failedRegistered.isEmpty()) { - Set failed = new HashSet(failedRegistered); - if (!failed.isEmpty()) { - - if (cancelKeepAlive) { - return; - } - - if (logger.isWarnEnabled()) { - logger.warn("Retry failed register(keep alive) for path '" + failed - + "', path size: " + failed.size()); - } - try { - for (String path : failed) { - try { - - /** - * Is it currently reconnecting ? - */ - if (cancelKeepAlive) { - return; - } - - createEphemeral(path); - failedRegistered.remove(path); - } catch (Throwable e) { - - failedRegistered.add(path); - - Status status = Status.fromThrowable(e); - if (status.getCode() == Status.Code.NOT_FOUND) { - cancelKeepAlive(); - } - - logger.warn("Failed to retry register(keep alive) for path '" + path + "', waiting for again, cause: " + e.getMessage(), e); - } - } - } catch (Throwable t) { - logger.warn("Failed to retry register(keep alive) for path '" + failed + "', waiting for again, cause: " + t.getMessage(), t); - } - } - } - } - - /** - * default request timeout - */ - public static final long DEFAULT_REQUEST_TIMEOUT = obtainRequestTimeout(); - - public static final int DEFAULT_INBOUND_SIZE = 100 * 1024 * 1024; - - public static final String GRPC_MAX_INBOUND_SIZE_KEY = "grpc.max.inbound.size"; - - public static final String ETCD_REQUEST_TIMEOUT_KEY = "etcd.request.timeout"; - - private static int obtainRequestTimeout() { - if (StringUtils.isNotEmpty(System.getProperty(ETCD_REQUEST_TIMEOUT_KEY))) { - return Integer.valueOf(System.getProperty(ETCD_REQUEST_TIMEOUT_KEY)); - } - /** - * 10 seconds. - */ - return 10 * 1000; - } -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdTransporter.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdTransporter.java deleted file mode 100644 index 5ddec8ee1f..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdTransporter.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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.apache.dubbo.remoting.etcd.jetcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.etcd.EtcdClient; -import org.apache.dubbo.remoting.etcd.EtcdTransporter; - -public class JEtcdTransporter implements EtcdTransporter { - - @Override - public EtcdClient connect(URL url) { - return new JEtcdClient(url); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/RetryLoops.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/RetryLoops.java deleted file mode 100644 index 0441e44428..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/RetryLoops.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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. - */ - -/* - * 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.apache.dubbo.remoting.etcd.jetcd; - -import io.grpc.Status; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.remoting.etcd.RetryPolicy; -import org.apache.dubbo.remoting.etcd.option.OptionUtil; - -import java.util.concurrent.Callable; - -public class RetryLoops { - - private final long startTimeMs = System.currentTimeMillis(); - private boolean isDone = false; - private int retriedCount = 0; - private Logger logger = LoggerFactory.getLogger(RetryLoops.class); - - public static R invokeWithRetry(Callable task, RetryPolicy retryPolicy) throws Exception { - R result = null; - RetryLoops retryLoop = new RetryLoops(); - while (retryLoop.shouldContinue()) { - try { - result = task.call(); - retryLoop.complete(); - } catch (Exception e) { - retryLoop.fireException(e, retryPolicy); - } - } - return result; - } - - public void fireException(Exception e, RetryPolicy retryPolicy) throws Exception { - - if (e instanceof InterruptedException) { - Thread.currentThread().interrupt(); - } - - boolean rethrow = true; - if (isRetryException(e) - && retryPolicy.shouldRetry(retriedCount++, System.currentTimeMillis() - startTimeMs, true)) { - rethrow = false; - } - - if (rethrow) { - throw e; - } - } - - private boolean isRetryException(Throwable e) { - Status status = Status.fromThrowable(e); - if (OptionUtil.isRecoverable(status)) { - return true; - } - - return false; - } - - public boolean shouldContinue() { - return !isDone; - } - - public void complete() { - isDone = true; - } - -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/RetryNTimes.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/RetryNTimes.java deleted file mode 100644 index 745320830c..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/jetcd/RetryNTimes.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.apache.dubbo.remoting.etcd.jetcd; - -import org.apache.dubbo.remoting.etcd.AbstractRetryPolicy; - -import java.util.concurrent.TimeUnit; - -public class RetryNTimes extends AbstractRetryPolicy { - - private final long sleepMilliseconds; - - public RetryNTimes(int maxRetried, int sleepTime, TimeUnit unit) { - super(maxRetried); - this.sleepMilliseconds = unit.convert(sleepTime, TimeUnit.MILLISECONDS); - } - - @Override - protected long getSleepTime(int retried, long elapsed) { - return sleepMilliseconds; - } -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/OptionUtil.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/OptionUtil.java deleted file mode 100644 index 5cb13fc726..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/option/OptionUtil.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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.apache.dubbo.remoting.etcd.option; - -import io.etcd.jetcd.ByteSequence; -import io.grpc.Status; -import io.netty.handler.codec.http2.Http2Exception; - -import java.util.Arrays; - -public class OptionUtil { - - public static final byte[] NO_PREFIX_END = {0}; - - public static final ByteSequence prefixEndOf(ByteSequence prefix) { - byte[] endKey = prefix.getBytes().clone(); - for (int i = endKey.length - 1; i >= 0; i--) { - if (endKey[i] < 0xff) { - endKey[i] = (byte) (endKey[i] + 1); - return ByteSequence.from(Arrays.copyOf(endKey, i + 1)); - } - } - - return ByteSequence.from(NO_PREFIX_END); - } - - public static boolean isRecoverable(Status status) { - return isHaltError(status) - || isNoLeaderError(status) - // ephemeral is expired - || status.getCode() == Status.Code.NOT_FOUND; - } - - public static boolean isHaltError(Status status) { - // Unavailable codes mean the system will be right back. - // (e.g., can't connect, lost leader) - // Treat Internal codes as if something failed, leaving the - // system in an inconsistent state, but retrying could make progress. - // (e.g., failed in middle of send, corrupted frame) - return status.getCode() != Status.Code.UNAVAILABLE && status.getCode() != Status.Code.INTERNAL; - } - - public static boolean isNoLeaderError(Status status) { - return status.getCode() == Status.Code.UNAVAILABLE - && "etcdserver: no leader".equals(status.getDescription()); - } - - public static boolean isProtocolError(Throwable e) { - if (e == null) { - return false; - } - Throwable cause = e.getCause(); - while (cause != null) { - if (cause instanceof Http2Exception) { - Http2Exception t = (Http2Exception) cause; - if ("PROTOCOL_ERROR".equals(t.error().name())) { - return true; - } - } - cause = cause.getCause(); - } - return false; - } -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java b/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java deleted file mode 100644 index 430bc54dbc..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/java/org/apache/dubbo/remoting/etcd/support/AbstractEtcdClient.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * 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. - */ - -/* - * 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.apache.dubbo.remoting.etcd.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ConcurrentHashSet; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.remoting.etcd.ChildListener; -import org.apache.dubbo.remoting.etcd.EtcdClient; -import org.apache.dubbo.remoting.etcd.StateListener; - -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR; -import static org.apache.dubbo.remoting.etcd.Constants.CONFIGURATORS_CATEGORY; -import static org.apache.dubbo.remoting.etcd.Constants.CONSUMERS_CATEGORY; -import static org.apache.dubbo.remoting.etcd.Constants.PROVIDERS_CATEGORY; -import static org.apache.dubbo.remoting.etcd.Constants.ROUTERS_CATEGORY; - -public abstract class AbstractEtcdClient implements EtcdClient { - - protected static final Logger logger = LoggerFactory.getLogger(AbstractEtcdClient.class); - - private final URL url; - - private final Set stateListeners = new ConcurrentHashSet<>(); - - private final ConcurrentMap> childListeners = new ConcurrentHashMap<>(); - private final List categories = Arrays.asList(PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, - CONFIGURATORS_CATEGORY); - private volatile boolean closed = false; - - public AbstractEtcdClient(URL url) { - this.url = url; - } - - @Override - public URL getUrl() { - return url; - } - - @Override - public void create(String path) { - String fixedPath = fixNamespace(path); - createParentIfAbsent(fixedPath); - doCreatePersistent(fixedPath); - } - - @Override - public long createEphemeral(String path) { - String fixedPath = fixNamespace(path); - createParentIfAbsent(fixedPath); - return doCreateEphemeral(path); - } - - @Override - public void addStateListener(StateListener listener) { - stateListeners.add(listener); - } - - @Override - public void removeStateListener(StateListener listener) { - stateListeners.remove(listener); - } - - public Set getSessionListeners() { - return stateListeners; - } - - @Override - public List addChildListener(String path, final ChildListener listener) { - ConcurrentMap listeners = childListeners.computeIfAbsent(path, k -> new ConcurrentHashMap<>()); - WatcherListener targetListener = listeners.computeIfAbsent(listener, k -> createChildWatcherListener(path, k)); - return addChildWatcherListener(path, targetListener); - } - - @Override - public WatcherListener getChildListener(String path, ChildListener listener) { - ConcurrentMap listeners = childListeners.get(path); - if (listeners == null) { - return null; - } - return listeners.computeIfAbsent(listener, k -> createChildWatcherListener(path, k)); - } - - @Override - public void removeChildListener(String path, ChildListener listener) { - ConcurrentMap listeners = childListeners.get(path); - if (listeners != null) { - WatcherListener targetListener = listeners.remove(listener); - if (targetListener != null) { - removeChildWatcherListener(path, targetListener); - } - } - } - - protected void stateChanged(int state) { - for (StateListener sessionListener : getSessionListeners()) { - sessionListener.stateChanged(state); - } - } - - protected String fixNamespace(String path) { - if (StringUtils.isEmpty(path)) { - throw new IllegalArgumentException("path is required, actual null or ''"); - } - return (path.charAt(0) != '/') ? (PATH_SEPARATOR + path) : path; - } - - protected void createParentIfAbsent(String fixedPath) { - int i = fixedPath.lastIndexOf('/'); - if (i > 0) { - String parentPath = fixedPath.substring(0, i); - if (categories.stream().anyMatch(c -> fixedPath.endsWith(c))) { - if (!checkExists(parentPath)) { - this.doCreatePersistent(parentPath); - } - } else if (categories.stream().anyMatch(c -> parentPath.endsWith(c))) { - String grandfather = parentPath.substring(0, parentPath.lastIndexOf('/')); - if (!checkExists(grandfather)) { - this.doCreatePersistent(grandfather); - } - } - } - } - - @Override - public void close() { - if (closed) { - return; - } - closed = true; - try { - doClose(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } - - public abstract void doClose(); - - public abstract void doCreatePersistent(String path); - - public abstract long doCreateEphemeral(String path); - - @Override - public abstract void delete(String path); - - public abstract boolean checkExists(String path); - - public abstract WatcherListener createChildWatcherListener(String path, ChildListener listener); - - public abstract List addChildWatcherListener(String path, WatcherListener listener); - - public abstract void removeChildWatcherListener(String path, WatcherListener listener); - -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.etcd.EtcdTransporter b/dubbo-remoting/dubbo-remoting-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.etcd.EtcdTransporter deleted file mode 100644 index d10733a0dd..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.etcd.EtcdTransporter +++ /dev/null @@ -1 +0,0 @@ -jetcd=org.apache.dubbo.remoting.etcd.jetcd.JEtcdTransporter \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java deleted file mode 100644 index 9f91a82144..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientTest.java +++ /dev/null @@ -1,427 +0,0 @@ -/* - * 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. - */ - -/* - * 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.apache.dubbo.remoting.etcd.jetcd; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.etcd.ChildListener; - -import com.google.protobuf.ByteString; -import io.etcd.jetcd.ByteSequence; -import io.etcd.jetcd.Client; -import io.etcd.jetcd.Watch; -import io.etcd.jetcd.api.Event; -import io.etcd.jetcd.api.WatchCancelRequest; -import io.etcd.jetcd.api.WatchCreateRequest; -import io.etcd.jetcd.api.WatchGrpc; -import io.etcd.jetcd.api.WatchRequest; -import io.etcd.jetcd.api.WatchResponse; -import io.etcd.jetcd.common.exception.ClosedClientException; -import io.etcd.jetcd.watch.WatchEvent; -import io.grpc.ManagedChannel; -import io.grpc.Status; -import io.grpc.stub.StreamObserver; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.dubbo.remoting.etcd.Constants.SESSION_TIMEOUT_KEY; - -@Disabled -public class JEtcdClientTest { - - JEtcdClient client; - - @Test - public void test_watch_when_create_path() throws InterruptedException { - - String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers"; - String child = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers/demoService1"; - - final CountDownLatch notNotified = new CountDownLatch(1); - - ChildListener childListener = (parent, children) -> { - Assertions.assertEquals(1, children.size()); - Assertions.assertEquals(child.substring(child.lastIndexOf("/") + 1), children.get(0)); - notNotified.countDown(); - }; - - client.addChildListener(path, childListener); - - client.createEphemeral(child); - Assertions.assertTrue(notNotified.await(10, TimeUnit.SECONDS)); - - client.removeChildListener(path, childListener); - client.delete(child); - } - - @Test - public void test_watch_when_modify() { - String path = "/dubbo/config/jetcd-client-unit-test/configurators"; - String endpoint = "http://127.0.0.1:2379"; - CountDownLatch latch = new CountDownLatch(1); - ByteSequence key = ByteSequence.from(path, UTF_8); - - Watch.Listener listener = Watch.listener(response -> { - for (WatchEvent event : response.getEvents()) { - Assertions.assertEquals("PUT", event.getEventType().toString()); - Assertions.assertEquals(path, event.getKeyValue().getKey().toString(UTF_8)); - Assertions.assertEquals("Hello", event.getKeyValue().getValue().toString(UTF_8)); - latch.countDown(); - } - - }); - - try (Client client = Client.builder().endpoints(endpoint).build(); - Watch watch = client.getWatchClient(); - Watch.Watcher watcher = watch.watch(key, listener)) { - // try to modify the key - client.getKVClient().put(ByteSequence.from(path, UTF_8), ByteSequence.from("Hello", UTF_8)); - latch.await(); - } catch (Exception e) { - Assertions.fail(e.getMessage()); - } - } - - @Test - public void testWatchWithGrpc() { - String path = "/dubbo/config/test_watch_with_grpc/configurators"; - String endpoint = "http://127.0.0.1:2379"; - CountDownLatch latch = new CountDownLatch(1); - try (Client client = Client.builder().endpoints(endpoint).build()) { - ManagedChannel channel = getChannel(client); - StreamObserver observer = WatchGrpc.newStub(channel).watch(new StreamObserver() { - @Override - public void onNext(WatchResponse response) { - for (Event event : response.getEventsList()) { - Assertions.assertEquals("PUT", event.getType().toString()); - Assertions.assertEquals(path, event.getKv().getKey().toString(UTF_8)); - Assertions.assertEquals("Hello", event.getKv().getValue().toString(UTF_8)); - latch.countDown(); - } - } - - @Override - public void onError(Throwable throwable) { - - } - - @Override - public void onCompleted() { - - } - }); - WatchCreateRequest.Builder builder = WatchCreateRequest.newBuilder() - .setKey(ByteString.copyFrom(path, UTF_8)); - - observer.onNext(WatchRequest.newBuilder().setCreateRequest(builder).build()); - - // try to modify the key - client.getKVClient().put(ByteSequence.from(path, UTF_8), ByteSequence.from("Hello", UTF_8)); - latch.await(5, TimeUnit.SECONDS); - } catch (Exception e) { - Assertions.fail(e.getMessage()); - } - } - - @Test - public void testCancelWatchWithGrpc() { - String path = "/dubbo/config/testCancelWatchWithGrpc/configurators"; - String endpoint = "http://127.0.0.1:2379"; - CountDownLatch updateLatch = new CountDownLatch(1); - CountDownLatch cancelLatch = new CountDownLatch(1); - final AtomicLong watchID = new AtomicLong(-1L); - try (Client client = Client.builder().endpoints(endpoint).build()) { - ManagedChannel channel = getChannel(client); - StreamObserver observer = WatchGrpc.newStub(channel).watch(new StreamObserver() { - @Override - public void onNext(WatchResponse response) { - watchID.set(response.getWatchId()); - for (Event event : response.getEventsList()) { - Assertions.assertEquals("PUT", event.getType().toString()); - Assertions.assertEquals(path, event.getKv().getKey().toString(UTF_8)); - Assertions.assertEquals("Hello", event.getKv().getValue().toString(UTF_8)); - updateLatch.countDown(); - } - if (response.getCanceled()) { - // received the cancel response - cancelLatch.countDown(); - } - } - - @Override - public void onError(Throwable throwable) { - - } - - @Override - public void onCompleted() { - - } - }); - // create - WatchCreateRequest.Builder builder = WatchCreateRequest.newBuilder() - .setKey(ByteString.copyFrom(path, UTF_8)); - - // make the grpc call to watch the key - observer.onNext(WatchRequest.newBuilder().setCreateRequest(builder).build()); - - // try to put the value - client.getKVClient().put(ByteSequence.from(path, UTF_8), ByteSequence.from("Hello", UTF_8)); - - // response received, latch counts down to zero - updateLatch.await(); - - WatchCancelRequest watchCancelRequest = - WatchCancelRequest.newBuilder().setWatchId(watchID.get()).build(); - WatchRequest cancelRequest = WatchRequest.newBuilder() - .setCancelRequest(watchCancelRequest).build(); - observer.onNext(cancelRequest); - - // try to put the value - client.getKVClient().put(ByteSequence.from(path, UTF_8), ByteSequence.from("Hello world", UTF_8)); - - cancelLatch.await(); - } catch (Exception e) { - Assertions.fail(e.getMessage()); - } - - } - - @Test - public void test_watch_when_create_wrong_path() throws InterruptedException { - - String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers"; - String child = "/dubbo/com.alibaba.dubbo.demo.DemoService/routers/demoService1"; - - final CountDownLatch notNotified = new CountDownLatch(1); - - ChildListener childListener = (parent, children) -> { - Assertions.assertEquals(1, children.size()); - Assertions.assertEquals(child, children.get(0)); - notNotified.countDown(); - }; - - client.addChildListener(path, childListener); - - client.createEphemeral(child); - Assertions.assertFalse(notNotified.await(1, TimeUnit.SECONDS)); - - client.removeChildListener(path, childListener); - client.delete(child); - } - - @Test - public void test_watch_when_delete_path() throws InterruptedException { - - String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers"; - String child = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers/demoService1"; - - final CountDownLatch notNotified = new CountDownLatch(1); - - ChildListener childListener = (parent, children) -> { - Assertions.assertEquals(0, children.size()); - notNotified.countDown(); - }; - - client.createEphemeral(child); - - client.addChildListener(path, childListener); - client.delete(child); - - Assertions.assertTrue(notNotified.await(10, TimeUnit.SECONDS)); - client.removeChildListener(path, childListener); - } - - @Test - public void test_watch_then_unwatch() throws InterruptedException { - - String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers"; - String child = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers/demoService2"; - - final CountDownLatch notNotified = new CountDownLatch(1); - final CountDownLatch notTwiceNotified = new CountDownLatch(2); - - final Holder notified = new Holder(); - - ChildListener childListener = (parent, children) -> { - Assertions.assertEquals(1, children.size()); - Assertions.assertEquals(child.substring(child.lastIndexOf("/") + 1), children.get(0)); - notNotified.countDown(); - notTwiceNotified.countDown(); - notified.getAndIncrease(); - }; - - client.addChildListener(path, childListener); - - client.createEphemeral(child); - Assertions.assertTrue(notNotified.await(15, TimeUnit.SECONDS)); - - client.removeChildListener(path, childListener); - client.delete(child); - - Assertions.assertFalse(notTwiceNotified.await(5, TimeUnit.SECONDS)); - Assertions.assertEquals(1, notified.value); - client.delete(child); - } - - @Test - public void test_watch_on_unrecoverable_connection() throws InterruptedException { - - String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers"; - JEtcdClient.EtcdWatcher watcher = null; - try { - ChildListener childListener = (parent, children) -> { - Assertions.assertEquals(path, parent); - }; - client.addChildListener(path, childListener); - watcher = client.getChildListener(path, childListener); - watcher.watchRequest.onError(Status.ABORTED.withDescription("connection error").asRuntimeException()); - - watcher.watchRequest.onNext(watcher.nextRequest()); - } catch (Exception e) { - Assertions.assertTrue(e.getMessage().contains("call was cancelled")); - } - } - - @Test - public void test_watch_on_recoverable_connection() throws InterruptedException { - - String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/connection"; - String child = "/dubbo/com.alibaba.dubbo.demo.DemoService/connection/demoService1"; - - final CountDownLatch notNotified = new CountDownLatch(1); - final CountDownLatch notTwiceNotified = new CountDownLatch(2); - final Holder notified = new Holder(); - ChildListener childListener = (parent, children) -> { - notTwiceNotified.countDown(); - switch (notified.increaseAndGet()) { - case 1: { - notNotified.countDown(); - Assertions.assertEquals(1, children.size()); - Assertions.assertEquals(child.substring(child.lastIndexOf("/") + 1), children.get(0)); - break; - } - case 2: { - Assertions.assertEquals(0, children.size()); - Assertions.assertEquals(path, parent); - break; - } - default: - Assertions.fail("two many callback invoked."); - } - }; - - client.addChildListener(path, childListener); - client.createEphemeral(child); - - // make sure first time callback successfully - Assertions.assertTrue(notNotified.await(15, TimeUnit.SECONDS)); - - // connection error causes client to release all resources including current watcher - JEtcdClient.EtcdWatcher watcher = client.getChildListener(path, childListener); - watcher.onError(Status.UNAVAILABLE.withDescription("temporary connection issue").asRuntimeException()); - - // trigger delete after unavailable - client.delete(child); - Assertions.assertTrue(notTwiceNotified.await(15, TimeUnit.SECONDS)); - - client.removeChildListener(path, childListener); - } - - @Test - public void test_watch_after_client_closed() throws InterruptedException { - - String path = "/dubbo/com.alibaba.dubbo.demo.DemoService/providers"; - client.close(); - - try { - client.addChildListener(path, (parent, children) -> { - Assertions.assertEquals(path, parent); - }); - } catch (ClosedClientException e) { - Assertions.assertEquals("watch client has been closed, path '" + path + "'", e.getMessage()); - } - } - - @BeforeEach - public void setUp() { - // timeout in 15 seconds. - URL url = URL.valueOf("etcd3://127.0.0.1:2379/com.alibaba.dubbo.registry.RegistryService") - .addParameter(SESSION_TIMEOUT_KEY, 15000); - - client = new JEtcdClient(url); - } - - @AfterEach - public void tearDown() { - client.close(); - } - - static class Holder { - - volatile int value; - - synchronized int getAndIncrease() { - return value++; - } - - synchronized int increaseAndGet() { - return ++value; - } - } - - private ManagedChannel getChannel(Client client) { - try { - // hack, use reflection to get the shared channel. - Field connectionField = client.getClass().getDeclaredField("connectionManager"); - connectionField.setAccessible(true); - Object connection = connectionField.get(client); - Method channelMethod = connection.getClass().getDeclaredMethod("getChannel"); - channelMethod.setAccessible(true); - ManagedChannel channel = (ManagedChannel) channelMethod.invoke(connection); - return channel; - } catch (Exception e) { - return null; - } - } -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java deleted file mode 100644 index 337b6decea..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/JEtcdClientWrapperTest.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * 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. - */ - -/* - * 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.apache.dubbo.remoting.etcd.jetcd; - -import org.apache.dubbo.common.URL; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.locks.LockSupport; - -import static org.apache.dubbo.remoting.etcd.Constants.SESSION_TIMEOUT_KEY; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.spy; - -@Disabled -public class JEtcdClientWrapperTest { - - JEtcdClientWrapper clientWrapper; - - @Test - public void test_path_exists() { - String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; - clientWrapper.createPersistent(path); - Assertions.assertTrue(clientWrapper.checkExists(path)); - Assertions.assertFalse(clientWrapper.checkExists(path + "/noneexits")); - clientWrapper.delete(path); - } - - @Test - public void test_create_emerphal_path() { - String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; - clientWrapper.createEphemeral(path); - Assertions.assertTrue(clientWrapper.checkExists(path)); - clientWrapper.delete(path); - } - - @Test - public void test_grant_lease_then_revoke() { - long lease = clientWrapper.createLease(1); - clientWrapper.revokeLease(lease); - - long newLease = clientWrapper.createLease(1); - LockSupport.parkNanos(this, TimeUnit.SECONDS.toNanos(2)); - // test timeout of lease - clientWrapper.revokeLease(newLease); - } - - @Test - public void test_create_emerphal_path_then_timeout() { - String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; - - URL url = URL.valueOf("etcd3://127.0.0.1:2379/org.apache.dubbo.registry.RegistryService") - .addParameter(SESSION_TIMEOUT_KEY, 1000); - - JEtcdClientWrapper saved = clientWrapper; - - try { - clientWrapper = spy(new JEtcdClientWrapper(url)); - clientWrapper.start(); - - doAnswer(new Answer() { - int timeout; - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - LockSupport.parkNanos(this, TimeUnit.SECONDS.toNanos(2)); - if (timeout++ > 0) { - throw new TimeoutException(); - } - return null; - } - }).when(clientWrapper).keepAlive(anyLong()); - - try { - clientWrapper.createEphemeral(path); - } catch (IllegalStateException ex) { - Assertions.assertEquals("failed to create ephereral by path '" + path + "'", ex.getMessage()); - } - - } finally { - clientWrapper.doClose(); - clientWrapper = saved; - } - } - - @Test - public void test_get_emerphal_children_path() { - String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; - String[] children = { - "/dubbo/org.apache.dubbo.demo.DemoService/providers/service1" - , "/dubbo/org.apache.dubbo.demo.DemoService/providers/service2" - , "/dubbo/org.apache.dubbo.demo.DemoService/providers/service3" - , "/dubbo/org.apache.dubbo.demo.DemoService/providers/service4" - , "/dubbo/org.apache.dubbo.demo.DemoService/providers/service5/exclude" - }; - - Arrays.stream(children).forEach((child) -> { - Assertions.assertFalse(clientWrapper.checkExists(child)); - clientWrapper.createEphemeral(child); - }); - - List extected = clientWrapper.getChildren(path); - - Assertions.assertEquals(4, extected.size()); - extected.stream().forEach((child) -> { - boolean found = false; - for (int i = 0; i < children.length; ++i) { - if (child.equals(children[i])) { - found = true; - break; - } - } - Assertions.assertTrue(found); - clientWrapper.delete(child); - }); - } - - @Test - public void test_connect_cluster() { - URL url = URL.valueOf("etcd3://127.0.0.1:22379/org.apache.dubbo.registry.RegistryService?backup=127.0.0.1:2379,127.0.0.1:32379"); - JEtcdClientWrapper clientWrapper = new JEtcdClientWrapper(url); - try { - clientWrapper.start(); - String path = "/dubbo/org.apache.dubbo.demo.DemoService/providers"; - clientWrapper.createEphemeral(path); - Assertions.assertTrue(clientWrapper.checkExists(path)); - Assertions.assertFalse(clientWrapper.checkExists(path + "/noneexits")); - clientWrapper.delete(path); - } finally { - clientWrapper.doClose(); - } - } - - @BeforeEach - public void setUp() { - URL url = URL.valueOf("etcd3://127.0.0.1:2379/org.apache.dubbo.registry.RegistryService"); - clientWrapper = new JEtcdClientWrapper(url); - clientWrapper.start(); - } - - @AfterEach - public void tearDown() { - clientWrapper.doClose(); - } -} diff --git a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/LeaseTest.java b/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/LeaseTest.java deleted file mode 100644 index 2b378ef9e5..0000000000 --- a/dubbo-remoting/dubbo-remoting-etcd3/src/test/java/org/apache/dubbo/remoting/etcd/jetcd/LeaseTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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. - */ - -/* - * 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.apache.dubbo.remoting.etcd.jetcd; - -import com.google.common.base.Charsets; -import io.etcd.jetcd.ByteSequence; -import io.etcd.jetcd.Client; -import io.etcd.jetcd.CloseableClient; -import io.etcd.jetcd.KV; -import io.etcd.jetcd.Lease; -import io.etcd.jetcd.Observers; -import io.etcd.jetcd.launcher.EtcdCluster; -import io.etcd.jetcd.launcher.EtcdClusterFactory; -import io.etcd.jetcd.lease.LeaseKeepAliveResponse; -import io.etcd.jetcd.options.PutOption; -import io.grpc.stub.StreamObserver; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author cvictory ON 2019-08-16 - */ -public class LeaseTest { - - private static EtcdCluster cluster; - - private KV kvClient; - private Client client; - private Lease leaseClient; - - private static final ByteSequence KEY = ByteSequence.from("foo", Charsets.UTF_8); - private static final ByteSequence KEY_2 = ByteSequence.from("foo2", Charsets.UTF_8); - private static final ByteSequence VALUE = ByteSequence.from("bar", Charsets.UTF_8); - - @BeforeAll - public static void beforeClass() { - cluster = EtcdClusterFactory.buildCluster("etcd-lease", 3, false); - cluster.start(); - } - - @AfterAll - public static void afterClass() { - cluster.close(); - } - - @BeforeEach - public void setUp() { - client = Client.builder().endpoints(cluster.getClientEndpoints()).build(); - kvClient = client.getKVClient(); - leaseClient = client.getLeaseClient(); - } - - @AfterEach - public void tearDown() { - if (client != null) { - client.close(); - } - - } - - @Test - public void testGrant() throws Exception { - long leaseID = leaseClient.grant(5).get().getID(); - - kvClient.put(KEY, VALUE, PutOption.newBuilder().withLeaseId(leaseID).build()).get(); - assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(1); - - Thread.sleep(6000); - assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(0); - } - - @Test - public void testRevoke() throws Exception { - long leaseID = leaseClient.grant(5).get().getID(); - kvClient.put(KEY, VALUE, PutOption.newBuilder().withLeaseId(leaseID).build()).get(); - assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(1); - leaseClient.revoke(leaseID).get(); - assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(0); - } - - @Test - public void testKeepAliveOnce() throws ExecutionException, InterruptedException { - long leaseID = leaseClient.grant(2).get().getID(); - kvClient.put(KEY, VALUE, PutOption.newBuilder().withLeaseId(leaseID).build()).get(); - assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(1); - LeaseKeepAliveResponse rp = leaseClient.keepAliveOnce(leaseID).get(); - assertThat(rp.getTTL()).isGreaterThan(0); - } - - @Test - public void testKeepAlive() throws ExecutionException, InterruptedException { - long leaseID = leaseClient.grant(2).get().getID(); - kvClient.put(KEY, VALUE, PutOption.newBuilder().withLeaseId(leaseID).build()).get(); - assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(1); - - CountDownLatch latch = new CountDownLatch(1); - AtomicReference responseRef = new AtomicReference<>(); - StreamObserver observer = Observers.observer(response -> { - responseRef.set(response); - latch.countDown(); - }); - - try (CloseableClient c = leaseClient.keepAlive(leaseID, observer)) { - latch.await(5, TimeUnit.SECONDS); - LeaseKeepAliveResponse response = responseRef.get(); - assertThat(response.getTTL()).isGreaterThan(0); - } - - Thread.sleep(3000); - assertThat(kvClient.get(KEY).get().getCount()).isEqualTo(0); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml b/dubbo-remoting/dubbo-remoting-grizzly/pom.xml deleted file mode 100644 index 1d5a7f1017..0000000000 --- a/dubbo-remoting/dubbo-remoting-grizzly/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-grizzly - jar - ${project.artifactId} - The grizzly remoting module of dubbo project - - false - - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.glassfish.grizzly - grizzly-core - - - \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyChannel.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyChannel.java deleted file mode 100644 index 02caca61c9..0000000000 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyChannel.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.grizzly; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.transport.AbstractChannel; - -import org.glassfish.grizzly.Connection; -import org.glassfish.grizzly.Grizzly; -import org.glassfish.grizzly.GrizzlyFuture; -import org.glassfish.grizzly.attributes.Attribute; - -import java.net.InetSocketAddress; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; -import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; - -/** - * GrizzlyChannel - * - * - */ -final class GrizzlyChannel extends AbstractChannel { - - private static final Logger logger = LoggerFactory.getLogger(GrizzlyChannel.class); - - private static final String CHANNEL_KEY = GrizzlyChannel.class.getName() + ".CHANNEL"; - - private static final Attribute ATTRIBUTE = Grizzly.DEFAULT_ATTRIBUTE_BUILDER.createAttribute(CHANNEL_KEY); - - private final Connection connection; - - /** - * @param connection - * @param url - * @param handler - */ - private GrizzlyChannel(Connection connection, URL url, ChannelHandler handler) { - super(url, handler); - if (connection == null) { - throw new IllegalArgumentException("grizzly connection == null"); - } - this.connection = connection; - } - - static GrizzlyChannel getOrAddChannel(Connection connection, URL url, ChannelHandler handler) { - if (connection == null) { - return null; - } - GrizzlyChannel ret = ATTRIBUTE.get(connection); - if (ret == null) { - ret = new GrizzlyChannel(connection, url, handler); - if (connection.isOpen()) { - ATTRIBUTE.set(connection, ret); - } - } - return ret; - } - - static void removeChannelIfDisconnected(Connection connection) { - if (connection != null && !connection.isOpen()) { - ATTRIBUTE.remove(connection); - } - } - - @Override - public InetSocketAddress getRemoteAddress() { - return (InetSocketAddress) connection.getPeerAddress(); - } - - @Override - public boolean isConnected() { - return connection.isOpen(); - } - - @Override - public InetSocketAddress getLocalAddress() { - return (InetSocketAddress) connection.getLocalAddress(); - } - - @Override - @SuppressWarnings("rawtypes") - public void send(Object message, boolean sent) throws RemotingException { - super.send(message, sent); - - int timeout = 0; - try { - GrizzlyFuture future = connection.write(message); - if (sent) { - timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); - future.get(timeout, TimeUnit.MILLISECONDS); - } - } catch (TimeoutException e) { - throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() - + "in timeout(" + timeout + "ms) limit", e); - } catch (Throwable e) { - throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e); - } - } - - @Override - public void close() { - try { - super.close(); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - try { - removeChannelIfDisconnected(connection); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - try { - if (logger.isInfoEnabled()) { - logger.info("Close grizzly channel " + connection); - } - connection.close(); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - } - - @Override - public boolean hasAttribute(String key) { - return getAttribute(key) == null; - } - - @Override - public Object getAttribute(String key) { - return Grizzly.DEFAULT_ATTRIBUTE_BUILDER.createAttribute(key).get(connection); - } - - @Override - public void setAttribute(String key, Object value) { - Grizzly.DEFAULT_ATTRIBUTE_BUILDER.createAttribute(key).set(connection, value); - } - - @Override - public void removeAttribute(String key) { - Grizzly.DEFAULT_ATTRIBUTE_BUILDER.createAttribute(key).remove(connection); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((connection == null) ? 0 : connection.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - GrizzlyChannel other = (GrizzlyChannel) obj; - if (connection == null) { - if (other.connection != null) { - return false; - } - } else if (!connection.equals(other.connection)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "GrizzlyChannel [connection=" + connection + "]"; - } - -} diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyClient.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyClient.java deleted file mode 100644 index e4a0e345d8..0000000000 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyClient.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.grizzly; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.transport.AbstractClient; - -import org.glassfish.grizzly.Connection; -import org.glassfish.grizzly.filterchain.FilterChainBuilder; -import org.glassfish.grizzly.filterchain.TransportFilter; -import org.glassfish.grizzly.nio.transport.TCPNIOTransport; -import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder; -import org.glassfish.grizzly.strategies.SameThreadIOStrategy; -import org.glassfish.grizzly.threadpool.ThreadPoolConfig; - -import java.util.concurrent.TimeUnit; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; -import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; - -/** - * GrizzlyClient - * - * - */ -public class GrizzlyClient extends AbstractClient { - - private static final Logger logger = LoggerFactory.getLogger(GrizzlyClient.class); - - private TCPNIOTransport transport; - - private volatile Connection connection; // volatile, please copy reference to use - - public GrizzlyClient(URL url, ChannelHandler handler) throws RemotingException { - super(url, handler); - } - - @Override - protected void doOpen() throws Throwable { - FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless(); - filterChainBuilder.add(new TransportFilter()); - filterChainBuilder.add(new GrizzlyCodecAdapter(getCodec(), getUrl(), this)); - filterChainBuilder.add(new GrizzlyHandler(getUrl(), this)); - TCPNIOTransportBuilder builder = TCPNIOTransportBuilder.newInstance(); - ThreadPoolConfig config = builder.getWorkerThreadPoolConfig(); - config.setPoolName(CLIENT_THREAD_POOL_NAME) - .setQueueLimit(-1) - .setCorePoolSize(0) - .setMaxPoolSize(Integer.MAX_VALUE) - .setKeepAliveTime(60L, TimeUnit.SECONDS); - builder.setTcpNoDelay(true).setKeepAlive(true) - .setConnectionTimeout(getConnectTimeout()) - .setIOStrategy(SameThreadIOStrategy.getInstance()); - transport = builder.build(); - transport.setProcessor(filterChainBuilder.build()); - transport.start(); - } - - - @Override - protected void doConnect() throws Throwable { - connection = transport.connect(getConnectAddress()) - .get(getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT), TimeUnit.MILLISECONDS); - } - - @Override - protected void doDisConnect() throws Throwable { - try { - GrizzlyChannel.removeChannelIfDisconnected(connection); - } catch (Throwable t) { - logger.warn(t.getMessage()); - } - } - - @Override - protected void doClose() throws Throwable { - try { - transport.stop(); - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - } - } - - @Override - protected Channel getChannel() { - Connection c = connection; - if (c == null || !c.isOpen()) { - return null; - } - return GrizzlyChannel.getOrAddChannel(c, getUrl(), this); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java deleted file mode 100644 index 39e6990c19..0000000000 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyCodecAdapter.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.grizzly; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.Codec2; -import org.apache.dubbo.remoting.buffer.ChannelBuffer; -import org.apache.dubbo.remoting.buffer.ChannelBuffers; -import org.apache.dubbo.remoting.buffer.DynamicChannelBuffer; - -import org.glassfish.grizzly.Buffer; -import org.glassfish.grizzly.Connection; -import org.glassfish.grizzly.filterchain.BaseFilter; -import org.glassfish.grizzly.filterchain.FilterChainContext; -import org.glassfish.grizzly.filterchain.NextAction; - -import java.io.IOException; - -import static org.apache.dubbo.remoting.Constants.BUFFER_KEY; -import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE; -import static org.apache.dubbo.remoting.Constants.MAX_BUFFER_SIZE; -import static org.apache.dubbo.remoting.Constants.MIN_BUFFER_SIZE; - -/** - * GrizzlyCodecAdapter - */ -public class GrizzlyCodecAdapter extends BaseFilter { - - private final Codec2 codec; - - private final URL url; - - private final ChannelHandler handler; - - private final int bufferSize; - - private ChannelBuffer previousData = ChannelBuffers.EMPTY_BUFFER; - - public GrizzlyCodecAdapter(Codec2 codec, URL url, ChannelHandler handler) { - this.codec = codec; - this.url = url; - this.handler = handler; - int b = url.getPositiveParameter(BUFFER_KEY, DEFAULT_BUFFER_SIZE); - this.bufferSize = b >= MIN_BUFFER_SIZE && b <= MAX_BUFFER_SIZE ? b : DEFAULT_BUFFER_SIZE; - } - - @Override - public NextAction handleWrite(FilterChainContext context) throws IOException { - Connection connection = context.getConnection(); - GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); - try { - ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer(1024); // Do not need to close - - Object msg = context.getMessage(); - codec.encode(channel, channelBuffer, msg); - - GrizzlyChannel.removeChannelIfDisconnected(connection); - Buffer buffer = connection.getTransport().getMemoryManager().allocate(channelBuffer.readableBytes()); - buffer.put(channelBuffer.toByteBuffer()); - buffer.flip(); - buffer.allowBufferDispose(true); - context.setMessage(buffer); - } finally { - GrizzlyChannel.removeChannelIfDisconnected(connection); - } - return context.getInvokeAction(); - } - - @Override - public NextAction handleRead(FilterChainContext context) throws IOException { - Object message = context.getMessage(); - Connection connection = context.getConnection(); - Channel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); - try { - if (message instanceof Buffer) { // receive a new packet - Buffer grizzlyBuffer = (Buffer) message; // buffer - - ChannelBuffer frame; - - if (previousData.readable()) { - if (previousData instanceof DynamicChannelBuffer) { - previousData.writeBytes(grizzlyBuffer.toByteBuffer()); - frame = previousData; - } else { - int size = previousData.readableBytes() + grizzlyBuffer.remaining(); - frame = ChannelBuffers.dynamicBuffer(size > bufferSize ? size : bufferSize); - frame.writeBytes(previousData, previousData.readableBytes()); - frame.writeBytes(grizzlyBuffer.toByteBuffer()); - } - } else { - frame = ChannelBuffers.wrappedBuffer(grizzlyBuffer.toByteBuffer()); - } - - Object msg; - int savedReadIndex; - - do { - savedReadIndex = frame.readerIndex(); - try { - msg = codec.decode(channel, frame); - } catch (Exception e) { - previousData = ChannelBuffers.EMPTY_BUFFER; - throw new IOException(e.getMessage(), e); - } - if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) { - frame.readerIndex(savedReadIndex); - return context.getStopAction(); - } else { - if (savedReadIndex == frame.readerIndex()) { - previousData = ChannelBuffers.EMPTY_BUFFER; - throw new IOException("Decode without read data."); - } - if (msg != null) { - context.setMessage(msg); - return context.getInvokeAction(); - } else { - return context.getInvokeAction(); - } - } - } while (frame.readable()); - } else { // Other events are passed down directly - return context.getInvokeAction(); - } - } finally { - GrizzlyChannel.removeChannelIfDisconnected(connection); - } - } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyHandler.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyHandler.java deleted file mode 100644 index 4ae6d8247b..0000000000 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyHandler.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.grizzly; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; - -import org.glassfish.grizzly.Connection; -import org.glassfish.grizzly.filterchain.BaseFilter; -import org.glassfish.grizzly.filterchain.FilterChainContext; -import org.glassfish.grizzly.filterchain.NextAction; - -import java.io.IOException; - -/** - * GrizzlyHandler - */ -public class GrizzlyHandler extends BaseFilter { - - private static final Logger logger = LoggerFactory.getLogger(GrizzlyHandler.class); - - private final URL url; - - private final ChannelHandler handler; - - public GrizzlyHandler(URL url, ChannelHandler handler) { - this.url = url; - this.handler = handler; - } - - @Override - public NextAction handleConnect(FilterChainContext ctx) throws IOException { - Connection connection = ctx.getConnection(); - GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); - try { - handler.connected(channel); - } catch (RemotingException e) { - throw new IOException(StringUtils.toString(e)); - } finally { - GrizzlyChannel.removeChannelIfDisconnected(connection); - } - return ctx.getInvokeAction(); - } - - @Override - public NextAction handleClose(FilterChainContext ctx) throws IOException { - Connection connection = ctx.getConnection(); - GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); - try { - handler.disconnected(channel); - } catch (RemotingException e) { - throw new IOException(StringUtils.toString(e)); - } finally { - GrizzlyChannel.removeChannelIfDisconnected(connection); - } - return ctx.getInvokeAction(); - } - - @Override - public NextAction handleRead(FilterChainContext ctx) throws IOException { - Connection connection = ctx.getConnection(); - GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); - try { - handler.received(channel, ctx.getMessage()); - } catch (RemotingException e) { - throw new IOException(StringUtils.toString(e)); - } finally { - GrizzlyChannel.removeChannelIfDisconnected(connection); - } - return ctx.getInvokeAction(); - } - - @Override - public NextAction handleWrite(FilterChainContext ctx) throws IOException { - Connection connection = ctx.getConnection(); - GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); - try { - handler.sent(channel, ctx.getMessage()); - } catch (RemotingException e) { - throw new IOException(StringUtils.toString(e)); - } finally { - GrizzlyChannel.removeChannelIfDisconnected(connection); - } - return ctx.getInvokeAction(); - } - - @Override - public void exceptionOccurred(FilterChainContext ctx, Throwable error) { - Connection connection = ctx.getConnection(); - GrizzlyChannel channel = GrizzlyChannel.getOrAddChannel(connection, url, handler); - try { - handler.caught(channel, error); - } catch (RemotingException e) { - logger.error("RemotingException on channel " + channel, e); - } finally { - GrizzlyChannel.removeChannelIfDisconnected(connection); - } - } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyServer.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyServer.java deleted file mode 100644 index 38608603a5..0000000000 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyServer.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.grizzly; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.transport.AbstractServer; - -import org.glassfish.grizzly.filterchain.FilterChainBuilder; -import org.glassfish.grizzly.filterchain.TransportFilter; -import org.glassfish.grizzly.nio.transport.TCPNIOTransport; -import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder; -import org.glassfish.grizzly.strategies.SameThreadIOStrategy; -import org.glassfish.grizzly.threadpool.ThreadPoolConfig; - -import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADPOOL; -import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; - -/** - * GrizzlyServer - */ -public class GrizzlyServer extends AbstractServer { - - private static final Logger logger = LoggerFactory.getLogger(GrizzlyServer.class); - - private final Map channels = new ConcurrentHashMap(); // - - private TCPNIOTransport transport; - - public GrizzlyServer(URL url, ChannelHandler handler) throws RemotingException { - super(url, handler); - } - - @Override - protected void doOpen() throws Throwable { - FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless(); - filterChainBuilder.add(new TransportFilter()); - - filterChainBuilder.add(new GrizzlyCodecAdapter(getCodec(), getUrl(), this)); - filterChainBuilder.add(new GrizzlyHandler(getUrl(), this)); - TCPNIOTransportBuilder builder = TCPNIOTransportBuilder.newInstance(); - ThreadPoolConfig config = builder.getWorkerThreadPoolConfig(); - config.setPoolName(SERVER_THREAD_POOL_NAME).setQueueLimit(-1); - String threadpool = getUrl().getParameter(THREADPOOL_KEY, DEFAULT_THREADPOOL); - if (DEFAULT_THREADPOOL.equals(threadpool)) { - int threads = getUrl().getPositiveParameter(THREADS_KEY, DEFAULT_THREADS); - config.setCorePoolSize(threads).setMaxPoolSize(threads) - .setKeepAliveTime(0L, TimeUnit.SECONDS); - } else if ("cached".equals(threadpool)) { - int threads = getUrl().getPositiveParameter(THREADS_KEY, Integer.MAX_VALUE); - config.setCorePoolSize(0).setMaxPoolSize(threads) - .setKeepAliveTime(60L, TimeUnit.SECONDS); - } else { - throw new IllegalArgumentException("Unsupported threadpool type " + threadpool); - } - builder.setKeepAlive(true).setReuseAddress(false) - .setIOStrategy(SameThreadIOStrategy.getInstance()); - transport = builder.build(); - transport.setProcessor(filterChainBuilder.build()); - transport.bind(getBindAddress()); - transport.start(); - } - - @Override - protected void doClose() throws Throwable { - try { - transport.stop(); - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - } - } - - @Override - public boolean isBound() { - return !transport.isStopped(); - } - - @Override - public Collection getChannels() { - return channels.values(); - } - - @Override - public Channel getChannel(InetSocketAddress remoteAddress) { - return channels.get(NetUtils.toAddressString(remoteAddress)); - } - - @Override - public void connected(Channel ch) throws RemotingException { - channels.put(NetUtils.toAddressString(ch.getRemoteAddress()), ch); - super.connected(ch); - } - - @Override - public void disconnected(Channel ch) throws RemotingException { - channels.remove(NetUtils.toAddressString(ch.getRemoteAddress())); - super.disconnected(ch); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporter.java b/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporter.java deleted file mode 100644 index 55892b6eef..0000000000 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporter.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.grizzly; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.Client; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.RemotingServer; -import org.apache.dubbo.remoting.Transporter; - -/** - * GrizzlyTransporter - */ -public class GrizzlyTransporter implements Transporter { - - public static final String NAME = "grizzly"; - - @Override - public RemotingServer bind(URL url, ChannelHandler handler) throws RemotingException { - return new GrizzlyServer(url, handler); - } - - @Override - public Client connect(URL url, ChannelHandler handler) throws RemotingException { - return new GrizzlyClient(url, handler); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter b/dubbo-remoting/dubbo-remoting-grizzly/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter deleted file mode 100644 index 8e78c7f894..0000000000 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter +++ /dev/null @@ -1 +0,0 @@ -grizzly=org.apache.dubbo.remoting.transport.grizzly.GrizzlyTransporter \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-grizzly/src/test/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java b/dubbo-remoting/dubbo-remoting-grizzly/src/test/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java deleted file mode 100644 index 8244529031..0000000000 --- a/dubbo-remoting/dubbo-remoting-grizzly/src/test/java/org/apache/dubbo/remoting/transport/grizzly/GrizzlyTransporterTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.grizzly; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.RemotingServer; -import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; - -import org.junit.jupiter.api.Test; - -import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; - -public class GrizzlyTransporterTest { - @Test - public void shouldAbleToBindGrizzly() throws Exception { - int port = NetUtils.getAvailablePort(); - URL url = new URL("http", "localhost", port, - new String[]{BIND_PORT_KEY, String.valueOf(port)}); - - RemotingServer server = new GrizzlyTransporter().bind(url, new ChannelHandlerAdapter()); - - assertThat(server.isBound(), is(true)); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/pom.xml b/dubbo-remoting/dubbo-remoting-http/pom.xml deleted file mode 100644 index 4c3cc99d48..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-http - jar - ${project.artifactId} - The http remoting module of dubbo project - - false - - - - org.apache.dubbo - dubbo-common - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.eclipse.jetty - jetty-server - - - org.eclipse.jetty - jetty-servlet - - - org.apache.tomcat.embed - tomcat-embed-core - - - org.apache.httpcomponents - fluent-hc - 4.5.5 - test - - - \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java deleted file mode 100644 index 5e5bec4192..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpBinder.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.Adaptive; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.remoting.Constants; - -/** - * HttpBinder - */ -@SPI("jetty") -public interface HttpBinder { - - /** - * bind the server. - * - * @param url server url. - * @return server. - */ - @Adaptive({Constants.SERVER_KEY}) - HttpServer bind(URL url, HttpHandler handler); - -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java deleted file mode 100644 index c8cd21781b..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpHandler.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * http invocation handler. - */ -public interface HttpHandler { - - /** - * invoke. - * - * @param request request. - * @param response response. - * @throws IOException - * @throws ServletException - */ - void handle(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException; - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java deleted file mode 100644 index 643fda4694..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/HttpServer.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http; - -import org.apache.dubbo.common.Resetable; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingServer; - -import java.net.InetSocketAddress; - -public interface HttpServer extends Resetable, RemotingServer { - - /** - * get http handler. - * - * @return http handler. - */ - HttpHandler getHttpHandler(); - - /** - * get url. - * - * @return url - */ - URL getUrl(); - - /** - * get local address. - * - * @return local address. - */ - InetSocketAddress getLocalAddress(); - - /** - * close the channel. - */ - void close(); - - /** - * Graceful close the channel. - */ - void close(int timeout); - - /** - * is bound. - * - * @return bound - */ - boolean isBound(); - - /** - * is closed. - * - * @return closed - */ - boolean isClosed(); - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java deleted file mode 100644 index 4b2cd70b06..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinder.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.jetty; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.http.HttpBinder; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -/** - * JettyHttpTransporter - */ -public class JettyHttpBinder implements HttpBinder { - - @Override - public HttpServer bind(URL url, HttpHandler handler) { - return new JettyHttpServer(url, handler); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java deleted file mode 100644 index e3c6719eeb..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/jetty/JettyHttpServer.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.jetty; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.servlet.DispatcherServlet; -import org.apache.dubbo.remoting.http.servlet.ServletManager; -import org.apache.dubbo.remoting.http.support.AbstractHttpServer; - -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.StdErrLog; -import org.eclipse.jetty.util.thread.QueuedThreadPool; - -import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; - -public class JettyHttpServer extends AbstractHttpServer { - - private static final Logger logger = LoggerFactory.getLogger(JettyHttpServer.class); - - private Server server; - - private URL url; - - public JettyHttpServer(URL url, final HttpHandler handler) { - super(url, handler); - this.url = url; - // TODO we should leave this setting to slf4j - // we must disable the debug logging for production use - Log.setLog(new StdErrLog()); - Log.getLog().setDebugEnabled(false); - - DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), handler); - - int threads = url.getParameter(THREADS_KEY, DEFAULT_THREADS); - QueuedThreadPool threadPool = new QueuedThreadPool(); - threadPool.setDaemon(true); - threadPool.setMaxThreads(threads); - threadPool.setMinThreads(threads); - - server = new Server(threadPool); - - ServerConnector connector = new ServerConnector(server); - - String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost()); - if (!url.isAnyHost() && NetUtils.isValidLocalHost(bindIp)) { - connector.setHost(bindIp); - } - connector.setPort(url.getParameter(Constants.BIND_PORT_KEY, url.getPort())); - - server.addConnector(connector); - - ServletHandler servletHandler = new ServletHandler(); - ServletHolder servletHolder = servletHandler.addServletWithMapping(DispatcherServlet.class, "/*"); - servletHolder.setInitOrder(2); - - // dubbo's original impl can't support the use of ServletContext - // server.addHandler(servletHandler); - // TODO Context.SESSIONS is the best option here? (In jetty 9.x, it becomes ServletContextHandler.SESSIONS) - ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); - context.setServletHandler(servletHandler); - ServletManager.getInstance().addServletContext(url.getParameter(Constants.BIND_PORT_KEY, url.getPort()), context.getServletContext()); - - try { - server.start(); - } catch (Exception e) { - throw new IllegalStateException("Failed to start jetty server on " + url.getParameter(Constants.BIND_IP_KEY) + ":" + url.getParameter(Constants.BIND_PORT_KEY) + ", cause: " - + e.getMessage(), e); - } - } - - @Override - public void close() { - super.close(); - - // - ServletManager.getInstance().removeServletContext(url.getParameter(Constants.BIND_PORT_KEY, url.getPort())); - - if (server != null) { - try { - server.stop(); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - } - } - -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java deleted file mode 100644 index 8c2e6f267b..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/BootstrapListener.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.servlet; - -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - -/** - * This class must be defined before something like spring's ContextLoaderListener in web.xml - * - */ -public class BootstrapListener implements ServletContextListener { - - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - ServletManager.getInstance().addServletContext(ServletManager.EXTERNAL_SERVER_PORT, servletContextEvent.getServletContext()); - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - ServletManager.getInstance().removeServletContext(ServletManager.EXTERNAL_SERVER_PORT); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java deleted file mode 100644 index 6cc0c1e7f8..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/DispatcherServlet.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.servlet; - -import org.apache.dubbo.remoting.http.HttpHandler; - -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.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Service dispatcher Servlet. - */ -public class DispatcherServlet extends HttpServlet { - - private static final long serialVersionUID = 5766349180380479888L; - private static final Map HANDLERS = new ConcurrentHashMap(); - private static DispatcherServlet INSTANCE; - - public DispatcherServlet() { - DispatcherServlet.INSTANCE = this; - } - - public static void addHttpHandler(int port, HttpHandler processor) { - HANDLERS.put(port, processor); - } - - public static void removeHttpHandler(int port) { - HANDLERS.remove(port); - } - - public static DispatcherServlet getInstance() { - return INSTANCE; - } - - @Override - protected void service(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - HttpHandler handler = HANDLERS.get(request.getLocalPort()); - if (handler == null) {// service not found. - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Service not found."); - } else { - handler.handle(request, response); - } - } - -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java deleted file mode 100644 index 447ea4e6ed..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpBinder.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.servlet; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.http.HttpBinder; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -/** - * ServletHttpTransporter - */ -public class ServletHttpBinder implements HttpBinder { - - @Override - public HttpServer bind(URL url, HttpHandler handler) { - return new ServletHttpServer(url, handler); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java deleted file mode 100644 index 0f8ad7d609..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletHttpServer.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.servlet; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.support.AbstractHttpServer; - -public class ServletHttpServer extends AbstractHttpServer { - - public ServletHttpServer(URL url, HttpHandler handler) { - super(url, handler); - DispatcherServlet.addHttpHandler(url.getParameter(Constants.BIND_PORT_KEY, 8080), handler); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java deleted file mode 100644 index 243c5541df..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/servlet/ServletManager.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.servlet; - -import javax.servlet.ServletContext; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * TODO this may not be a pretty elegant solution, - * - */ -public class ServletManager { - - public static final int EXTERNAL_SERVER_PORT = -1234; - - private static final ServletManager INSTANCE = new ServletManager(); - - private final Map contextMap = new ConcurrentHashMap(); - - public static ServletManager getInstance() { - return INSTANCE; - } - - public void addServletContext(int port, ServletContext servletContext) { - contextMap.put(port, servletContext); - } - - public void removeServletContext(int port) { - contextMap.remove(port); - } - - public ServletContext getServletContext(int port) { - return contextMap.get(port); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java deleted file mode 100644 index 2d87274db0..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/support/AbstractHttpServer.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.support; - -import org.apache.dubbo.common.Parameters; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -import java.net.InetSocketAddress; -import java.util.Collection; - -/** - * AbstractHttpServer - */ -public abstract class AbstractHttpServer implements HttpServer { - - private final URL url; - - private final HttpHandler handler; - - private volatile boolean closed; - - public AbstractHttpServer(URL url, HttpHandler handler) { - if (url == null) { - throw new IllegalArgumentException("url == null"); - } - if (handler == null) { - throw new IllegalArgumentException("handler == null"); - } - this.url = url; - this.handler = handler; - } - - @Override - public HttpHandler getHttpHandler() { - return handler; - } - - @Override - public URL getUrl() { - return url; - } - - @Override - public void reset(URL url) { - } - - @Override - public boolean isBound() { - return true; - } - - @Override - public InetSocketAddress getLocalAddress() { - return url.toInetSocketAddress(); - } - - @Override - public void close() { - closed = true; - } - - @Override - public void close(int timeout) { - close(); - } - - @Override - public boolean isClosed() { - return closed; - } - - /** - * Following methods are extended from RemotingServer, useless for http servers - */ - - @Override - public boolean canHandleIdle() { - return false; - } - - @Override - public Collection getChannels() { - return null; - } - - @Override - public Channel getChannel(InetSocketAddress remoteAddress) { - return null; - } - - @Override - public void reset(Parameters parameters) { - - } - - @Override - public ChannelHandler getChannelHandler() { - return null; - } - - @Override - public void send(Object message) throws RemotingException { - - } - - @Override - public void send(Object message, boolean sent) throws RemotingException { - - } - - @Override - public void startClose() { - - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java deleted file mode 100755 index 4e4a74bb7e..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinder.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.tomcat; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.http.HttpBinder; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -public class TomcatHttpBinder implements HttpBinder { - - @Override - public HttpServer bind(URL url, HttpHandler handler) { - return new TomcatHttpServer(url, handler); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java b/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java deleted file mode 100755 index 07115901f1..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpServer.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.tomcat; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.servlet.DispatcherServlet; -import org.apache.dubbo.remoting.http.servlet.ServletManager; -import org.apache.dubbo.remoting.http.support.AbstractHttpServer; - -import org.apache.catalina.Context; -import org.apache.catalina.LifecycleException; -import org.apache.catalina.connector.Connector; -import org.apache.catalina.startup.Tomcat; - -import java.io.File; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREADS; -import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY; -import static org.apache.dubbo.remoting.Constants.ACCEPTS_KEY; - -public class TomcatHttpServer extends AbstractHttpServer { - - private static final Logger logger = LoggerFactory.getLogger(TomcatHttpServer.class); - - private final Tomcat tomcat; - - private final URL url; - - public TomcatHttpServer(URL url, final HttpHandler handler) { - super(url, handler); - - this.url = url; - DispatcherServlet.addHttpHandler(url.getPort(), handler); - String baseDir = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath(); - tomcat = new Tomcat(); - - Connector connector = tomcat.getConnector(); - connector.setPort(url.getPort()); - connector.setProperty("maxThreads", String.valueOf(url.getParameter(THREADS_KEY, DEFAULT_THREADS))); - connector.setProperty("maxConnections", String.valueOf(url.getParameter(ACCEPTS_KEY, -1))); - connector.setProperty("URIEncoding", "UTF-8"); - connector.setProperty("connectionTimeout", "60000"); - connector.setProperty("maxKeepAliveRequests", "-1"); - - tomcat.setBaseDir(baseDir); - tomcat.setPort(url.getPort()); - - Context context = tomcat.addContext("/", baseDir); - Tomcat.addServlet(context, "dispatcher", new DispatcherServlet()); - // Issue : https://github.com/apache/dubbo/issues/6418 - // addServletMapping method will be removed since Tomcat 9 - // context.addServletMapping("/*", "dispatcher"); - context.addServletMappingDecoded("/*", "dispatcher"); - ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext()); - - // tell tomcat to fail on startup failures. - System.setProperty("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true"); - - try { - tomcat.start(); - } catch (LifecycleException e) { - throw new IllegalStateException("Failed to start tomcat server at " + url.getAddress(), e); - } - } - - @Override - public void close() { - super.close(); - - ServletManager.getInstance().removeServletContext(url.getPort()); - - try { - tomcat.stop(); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder b/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder deleted file mode 100644 index d31dcb4d2e..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder +++ /dev/null @@ -1,3 +0,0 @@ -servlet=org.apache.dubbo.remoting.http.servlet.ServletHttpBinder -jetty=org.apache.dubbo.remoting.http.jetty.JettyHttpBinder -tomcat=org.apache.dubbo.remoting.http.tomcat.TomcatHttpBinder \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java deleted file mode 100644 index d26d4f5623..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/jetty/JettyHttpBinderTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.jetty; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; -import org.apache.http.client.fluent.Request; -import org.junit.jupiter.api.Test; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; - -public class JettyHttpBinderTest { - @Test - public void shouldAbleHandleRequestForJettyBinder() throws Exception { - int port = NetUtils.getAvailablePort(); - URL url = new URL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); - HttpServer httpServer = new JettyHttpServer(url, new HttpHandler() { - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.getWriter().write("Jetty"); - } - }); - - String response = Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); - - assertThat(response, is("Jetty")); - - httpServer.close(); - } -} diff --git a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java b/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java deleted file mode 100644 index f31b6ce23c..0000000000 --- a/dubbo-remoting/dubbo-remoting-http/src/test/java/org/apache/dubbo/remoting/http/tomcat/TomcatHttpBinderTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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.apache.dubbo.remoting.http.tomcat; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.HttpServer; - -import org.apache.http.client.fluent.Request; -import org.junit.jupiter.api.Test; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; - -public class TomcatHttpBinderTest { - @Test - public void shouldAbleHandleRequestForTomcatBinder() throws Exception { - int port = NetUtils.getAvailablePort(); - URL url = new URL("http", "localhost", port, - new String[]{Constants.BIND_PORT_KEY, String.valueOf(port)}); - - HttpServer httpServer = new TomcatHttpBinder().bind(url, new HttpHandler() { - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.getWriter().write("Tomcat"); - } - }); - - String response = Request.Get(url.toJavaURL().toURI()).execute().returnContent().asString(); - - assertThat(response, is("Tomcat")); - - httpServer.close(); - } -} diff --git a/dubbo-remoting/dubbo-remoting-mina/pom.xml b/dubbo-remoting/dubbo-remoting-mina/pom.xml deleted file mode 100644 index 76725e6a12..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-mina - jar - ${project.artifactId} - The mina remoting module of dubbo project - - false - - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.apache.mina - mina-core - - - org.slf4j - slf4j-api - - - org.apache.dubbo - dubbo-serialization-hessian2 - ${project.parent.version} - test - - - \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaChannel.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaChannel.java deleted file mode 100644 index 7229cb1607..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaChannel.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.mina; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.transport.AbstractChannel; - -import org.apache.mina.common.IoSession; -import org.apache.mina.common.WriteFuture; - -import java.net.InetSocketAddress; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; -import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; - -/** - * MinaChannel - */ -final class MinaChannel extends AbstractChannel { - - private static final Logger logger = LoggerFactory.getLogger(MinaChannel.class); - - private static final String CHANNEL_KEY = MinaChannel.class.getName() + ".CHANNEL"; - - private final IoSession session; - - private MinaChannel(IoSession session, URL url, ChannelHandler handler) { - super(url, handler); - if (session == null) { - throw new IllegalArgumentException("mina session == null"); - } - this.session = session; - } - - static MinaChannel getOrAddChannel(IoSession session, URL url, ChannelHandler handler) { - if (session == null) { - return null; - } - MinaChannel ret = (MinaChannel) session.getAttribute(CHANNEL_KEY); - if (ret == null) { - ret = new MinaChannel(session, url, handler); - if (session.isConnected()) { - MinaChannel old = (MinaChannel) session.setAttribute(CHANNEL_KEY, ret); - if (old != null) { - session.setAttribute(CHANNEL_KEY, old); - ret = old; - } - } - } - return ret; - } - - static void removeChannelIfDisconnected(IoSession session) { - if (session != null && !session.isConnected()) { - session.removeAttribute(CHANNEL_KEY); - } - } - - @Override - public InetSocketAddress getLocalAddress() { - return (InetSocketAddress) session.getLocalAddress(); - } - - @Override - public InetSocketAddress getRemoteAddress() { - return (InetSocketAddress) session.getRemoteAddress(); - } - - @Override - public boolean isConnected() { - return session.isConnected(); - } - - @Override - public void send(Object message, boolean sent) throws RemotingException { - super.send(message, sent); - - boolean success = true; - int timeout = 0; - try { - WriteFuture future = session.write(message); - if (sent) { - timeout = getUrl().getPositiveParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); - success = future.join(timeout); - } - } catch (Throwable e) { - throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e); - } - - if (!success) { - throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() - + "in timeout(" + timeout + "ms) limit"); - } - } - - @Override - public void close() { - try { - super.close(); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - try { - removeChannelIfDisconnected(session); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - try { - if (logger.isInfoEnabled()) { - logger.info("CLose mina channel " + session); - } - session.close(); - } catch (Exception e) { - logger.warn(e.getMessage(), e); - } - } - - @Override - public boolean hasAttribute(String key) { - return session.containsAttribute(key); - } - - @Override - public Object getAttribute(String key) { - return session.getAttribute(key); - } - - @Override - public void setAttribute(String key, Object value) { - session.setAttribute(key, value); - } - - @Override - public void removeAttribute(String key) { - session.removeAttribute(key); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((session == null) ? 0 : session.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - MinaChannel other = (MinaChannel) obj; - if (session == null) { - if (other.session != null) { - return false; - } - } else if (!session.equals(other.session)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "MinaChannel [session=" + session + "]"; - } - -} diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java deleted file mode 100644 index ad047a0f82..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaClient.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.mina; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.Version; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.transport.AbstractClient; - -import org.apache.mina.common.ConnectFuture; -import org.apache.mina.common.IoFuture; -import org.apache.mina.common.IoFutureListener; -import org.apache.mina.common.IoSession; -import org.apache.mina.common.ThreadModel; -import org.apache.mina.filter.codec.ProtocolCodecFilter; -import org.apache.mina.transport.socket.nio.SocketConnector; -import org.apache.mina.transport.socket.nio.SocketConnectorConfig; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Mina client. - */ -public class MinaClient extends AbstractClient { - - private static final Logger logger = LoggerFactory.getLogger(MinaClient.class); - - private static final Map CONNECTORS = new ConcurrentHashMap(); - - private String connectorKey; - - private SocketConnector connector; - - private volatile IoSession session; // volatile, please copy reference to use - - public MinaClient(final URL url, final ChannelHandler handler) throws RemotingException { - super(url, wrapChannelHandler(url, handler)); - } - - @Override - protected void doOpen() throws Throwable { - connectorKey = getUrl().toFullString(); - SocketConnector c = CONNECTORS.get(connectorKey); - if (c != null) { - connector = c; - } else { - // set thread pool. - connector = new SocketConnector(Constants.DEFAULT_IO_THREADS, - Executors.newCachedThreadPool(new NamedThreadFactory("MinaClientWorker", true))); - // config - SocketConnectorConfig cfg = (SocketConnectorConfig) connector.getDefaultConfig(); - cfg.setThreadModel(ThreadModel.MANUAL); - cfg.getSessionConfig().setTcpNoDelay(true); - cfg.getSessionConfig().setKeepAlive(true); - int timeout = getConnectTimeout(); - cfg.setConnectTimeout(timeout < 1000 ? 1 : timeout / 1000); - // set codec. - connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaCodecAdapter(getCodec(), getUrl(), this))); - CONNECTORS.put(connectorKey, connector); - } - } - - @Override - protected void doConnect() throws Throwable { - ConnectFuture future = connector.connect(getConnectAddress(), new MinaHandler(getUrl(), this)); - long start = System.currentTimeMillis(); - final AtomicReference exception = new AtomicReference(); - final CountDownLatch finish = new CountDownLatch(1); // resolve future.awaitUninterruptibly() dead lock - future.addListener(new IoFutureListener() { - @Override - public void operationComplete(IoFuture future) { - try { - if (future.isReady()) { - IoSession newSession = future.getSession(); - try { - // Close old channel - IoSession oldSession = MinaClient.this.session; // copy reference - if (oldSession != null) { - try { - if (logger.isInfoEnabled()) { - logger.info("Close old mina channel " + oldSession + " on create new mina channel " + newSession); - } - oldSession.close(); - } finally { - MinaChannel.removeChannelIfDisconnected(oldSession); - } - } - } finally { - if (MinaClient.this.isClosed()) { - try { - if (logger.isInfoEnabled()) { - logger.info("Close new mina channel " + newSession + ", because the client closed."); - } - newSession.close(); - } finally { - MinaClient.this.session = null; - MinaChannel.removeChannelIfDisconnected(newSession); - } - } else { - MinaClient.this.session = newSession; - } - } - } - } catch (Exception e) { - exception.set(e); - } finally { - finish.countDown(); - } - } - }); - try { - finish.await(getConnectTimeout(), TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress() + " client-side timeout " - + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) - + "ms) from netty client " + NetUtils.getLocalHost() + " using dubbo version " - + Version.getVersion() + ", cause: " + e.getMessage(), e); - } - Throwable e = exception.get(); - if (e != null) { - throw e; - } - } - - @Override - protected void doDisConnect() throws Throwable { - try { - MinaChannel.removeChannelIfDisconnected(session); - } catch (Throwable t) { - logger.warn(t.getMessage()); - } - } - - @Override - protected void doClose() throws Throwable { - //release mina resources. - } - - @Override - protected Channel getChannel() { - IoSession s = session; - if (s == null || !s.isConnected()) { - return null; - } - return MinaChannel.getOrAddChannel(s, getUrl(), this); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java deleted file mode 100644 index 7ce9253666..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaCodecAdapter.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.mina; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.Codec2; -import org.apache.dubbo.remoting.buffer.ChannelBuffer; -import org.apache.dubbo.remoting.buffer.ChannelBuffers; -import org.apache.dubbo.remoting.buffer.DynamicChannelBuffer; - -import org.apache.mina.common.ByteBuffer; -import org.apache.mina.common.IoSession; -import org.apache.mina.filter.codec.ProtocolCodecFactory; -import org.apache.mina.filter.codec.ProtocolDecoder; -import org.apache.mina.filter.codec.ProtocolDecoderOutput; -import org.apache.mina.filter.codec.ProtocolEncoder; -import org.apache.mina.filter.codec.ProtocolEncoderOutput; - -import static org.apache.dubbo.remoting.Constants.BUFFER_KEY; -import static org.apache.dubbo.remoting.Constants.DEFAULT_BUFFER_SIZE; -import static org.apache.dubbo.remoting.Constants.MAX_BUFFER_SIZE; -import static org.apache.dubbo.remoting.Constants.MIN_BUFFER_SIZE; - -/** - * MinaCodecAdapter. - */ -final class MinaCodecAdapter implements ProtocolCodecFactory { - - private final ProtocolEncoder encoder = new InternalEncoder(); - - private final ProtocolDecoder decoder = new InternalDecoder(); - - private final Codec2 codec; - - private final URL url; - - private final ChannelHandler handler; - - private final int bufferSize; - - public MinaCodecAdapter(Codec2 codec, URL url, ChannelHandler handler) { - this.codec = codec; - this.url = url; - this.handler = handler; - int b = url.getPositiveParameter(BUFFER_KEY, DEFAULT_BUFFER_SIZE); - this.bufferSize = b >= MIN_BUFFER_SIZE && b <= MAX_BUFFER_SIZE ? b : DEFAULT_BUFFER_SIZE; - } - - @Override - public ProtocolEncoder getEncoder() { - return encoder; - } - - @Override - public ProtocolDecoder getDecoder() { - return decoder; - } - - private class InternalEncoder implements ProtocolEncoder { - - @Override - public void dispose(IoSession session) throws Exception { - } - - @Override - public void encode(IoSession session, Object msg, ProtocolEncoderOutput out) throws Exception { - ChannelBuffer buffer = ChannelBuffers.dynamicBuffer(1024); - MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler); - try { - codec.encode(channel, buffer, msg); - } finally { - MinaChannel.removeChannelIfDisconnected(session); - } - out.write(ByteBuffer.wrap(buffer.toByteBuffer())); - out.flush(); - } - } - - private class InternalDecoder implements ProtocolDecoder { - - private ChannelBuffer buffer = ChannelBuffers.EMPTY_BUFFER; - - @Override - public void decode(IoSession session, ByteBuffer in, ProtocolDecoderOutput out) throws Exception { - int readable = in.limit(); - if (readable <= 0) { - return; - } - - ChannelBuffer frame; - - if (buffer.readable()) { - if (buffer instanceof DynamicChannelBuffer) { - buffer.writeBytes(in.buf()); - frame = buffer; - } else { - int size = buffer.readableBytes() + in.remaining(); - frame = ChannelBuffers.dynamicBuffer(size > bufferSize ? size : bufferSize); - frame.writeBytes(buffer, buffer.readableBytes()); - frame.writeBytes(in.buf()); - } - } else { - frame = ChannelBuffers.wrappedBuffer(in.buf()); - } - - Channel channel = MinaChannel.getOrAddChannel(session, url, handler); - Object msg; - int savedReadIndex; - - try { - do { - savedReadIndex = frame.readerIndex(); - try { - msg = codec.decode(channel, frame); - } catch (Exception e) { - buffer = ChannelBuffers.EMPTY_BUFFER; - throw e; - } - if (msg == Codec2.DecodeResult.NEED_MORE_INPUT) { - frame.readerIndex(savedReadIndex); - break; - } else { - if (savedReadIndex == frame.readerIndex()) { - buffer = ChannelBuffers.EMPTY_BUFFER; - throw new Exception("Decode without read data."); - } - if (msg != null) { - out.write(msg); - } - } - } while (frame.readable()); - } finally { - if (frame.readable()) { - frame.discardReadBytes(); - buffer = frame; - } else { - buffer = ChannelBuffers.EMPTY_BUFFER; - } - MinaChannel.removeChannelIfDisconnected(session); - } - } - - @Override - public void dispose(IoSession session) throws Exception { - } - - @Override - public void finishDecode(IoSession session, ProtocolDecoderOutput out) throws Exception { - } - } -} diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaHandler.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaHandler.java deleted file mode 100644 index dabfe1c835..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaHandler.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.mina; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.ChannelHandler; - -import org.apache.mina.common.IoHandlerAdapter; -import org.apache.mina.common.IoSession; - -/** - * MinaHandler - */ -public class MinaHandler extends IoHandlerAdapter { - - private final URL url; - - private final ChannelHandler handler; - - public MinaHandler(URL url, ChannelHandler handler) { - if (url == null) { - throw new IllegalArgumentException("url == null"); - } - if (handler == null) { - throw new IllegalArgumentException("handler == null"); - } - this.url = url; - this.handler = handler; - } - - @Override - public void sessionOpened(IoSession session) throws Exception { - MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler); - try { - handler.connected(channel); - } finally { - MinaChannel.removeChannelIfDisconnected(session); - } - } - - @Override - public void sessionClosed(IoSession session) throws Exception { - MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler); - try { - handler.disconnected(channel); - } finally { - MinaChannel.removeChannelIfDisconnected(session); - } - } - - @Override - public void messageReceived(IoSession session, Object message) throws Exception { - MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler); - try { - handler.received(channel, message); - } finally { - MinaChannel.removeChannelIfDisconnected(session); - } - } - - @Override - public void messageSent(IoSession session, Object message) throws Exception { - MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler); - try { - handler.sent(channel, message); - } finally { - MinaChannel.removeChannelIfDisconnected(session); - } - } - - @Override - public void exceptionCaught(IoSession session, Throwable cause) throws Exception { - MinaChannel channel = MinaChannel.getOrAddChannel(session, url, handler); - try { - handler.caught(channel, cause); - } finally { - MinaChannel.removeChannelIfDisconnected(session); - } - } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java deleted file mode 100644 index 304d9ca416..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaServer.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.mina; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.utils.ExecutorUtil; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.transport.AbstractServer; -import org.apache.dubbo.remoting.transport.dispatcher.ChannelHandlers; - -import org.apache.mina.common.IoSession; -import org.apache.mina.common.ThreadModel; -import org.apache.mina.filter.codec.ProtocolCodecFilter; -import org.apache.mina.transport.socket.nio.SocketAcceptor; -import org.apache.mina.transport.socket.nio.SocketAcceptorConfig; - -import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.Executors; - -import static org.apache.dubbo.remoting.Constants.DEFAULT_IO_THREADS; -import static org.apache.dubbo.common.constants.CommonConstants.IO_THREADS_KEY; - -/** - * MinaServer - */ -public class MinaServer extends AbstractServer { - - private static final Logger logger = LoggerFactory.getLogger(MinaServer.class); - - private SocketAcceptor acceptor; - - public MinaServer(URL url, ChannelHandler handler) throws RemotingException { - super(url, ChannelHandlers.wrap(handler, ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME))); - } - - @Override - protected void doOpen() throws Throwable { - // set thread pool. - acceptor = new SocketAcceptor(getUrl().getPositiveParameter(IO_THREADS_KEY, DEFAULT_IO_THREADS), - Executors.newCachedThreadPool(new NamedThreadFactory("MinaServerWorker", - true))); - // config - SocketAcceptorConfig cfg = acceptor.getDefaultConfig(); - cfg.setThreadModel(ThreadModel.MANUAL); - // set codec. - acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MinaCodecAdapter(getCodec(), getUrl(), this))); - - acceptor.bind(getBindAddress(), new MinaHandler(getUrl(), this)); - } - - @Override - protected void doClose() throws Throwable { - try { - if (acceptor != null) { - acceptor.unbind(getBindAddress()); - } - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - } - } - - @Override - public Collection getChannels() { - Set sessions = acceptor.getManagedSessions(getBindAddress()); - Collection channels = new HashSet(); - for (IoSession session : sessions) { - if (session.isConnected()) { - channels.add(MinaChannel.getOrAddChannel(session, getUrl(), this)); - } - } - return channels; - } - - @Override - public Channel getChannel(InetSocketAddress remoteAddress) { - Set sessions = acceptor.getManagedSessions(getBindAddress()); - for (IoSession session : sessions) { - if (session.getRemoteAddress().equals(remoteAddress)) { - return MinaChannel.getOrAddChannel(session, getUrl(), this); - } - } - return null; - } - - @Override - public boolean isBound() { - return acceptor.isManaged(getBindAddress()); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaTransporter.java b/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaTransporter.java deleted file mode 100644 index d8739f4fb4..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/java/org/apache/dubbo/remoting/transport/mina/MinaTransporter.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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.apache.dubbo.remoting.transport.mina; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.Client; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.RemotingServer; -import org.apache.dubbo.remoting.Transporter; - -public class MinaTransporter implements Transporter { - - public static final String NAME = "mina"; - - @Override - public RemotingServer bind(URL url, ChannelHandler handler) throws RemotingException { - return new MinaServer(url, handler); - } - - @Override - public Client connect(URL url, ChannelHandler handler) throws RemotingException { - return new MinaClient(url, handler); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-mina/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter b/dubbo-remoting/dubbo-remoting-mina/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter deleted file mode 100644 index 28fba104ae..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Transporter +++ /dev/null @@ -1 +0,0 @@ -mina=org.apache.dubbo.remoting.transport.mina.MinaTransporter \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientToServerTest.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientToServerTest.java deleted file mode 100644 index 25d8618249..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientToServerTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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.apache.remoting.transport.mina; - -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeChannel; -import org.apache.dubbo.remoting.exchange.ExchangeServer; -import org.apache.dubbo.remoting.exchange.support.Replier; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.CompletableFuture; - -/** - * ClientToServer - */ -public abstract class ClientToServerTest { - - protected static final String LOCALHOST = "127.0.0.1"; - - protected ExchangeServer server; - - protected ExchangeChannel client; - - protected WorldHandler handler = new WorldHandler(); - - protected abstract ExchangeServer newServer(int port, Replier receiver) throws RemotingException; - - protected abstract ExchangeChannel newClient(int port) throws RemotingException; - - @BeforeEach - protected void setUp() throws Exception { - int port = NetUtils.getAvailablePort(); - server = newServer(port, handler); - client = newClient(port); - } - - @AfterEach - protected void tearDown() { - try { - if (server != null) - server.close(); - } finally { - if (client != null) - client.close(); - } - } - - @Test - public void testFuture() throws Exception { - CompletableFuture future = client.request(new World("world")); - Hello result = (Hello) future.get(); - Assertions.assertEquals("hello,world", result.getName()); - } - -// @Test -// public void testCallback() throws Exception { -// final Object waitter = new Object(); -// client.invoke(new World("world"), new InvokeCallback() { -// public void callback(Hello result) { -// Assertions.assertEquals("hello,world", result.getName()); -// synchronized (waitter) { -// waitter.notifyAll(); -// } -// } -// public void onException(Throwable exception) { -// } -// }); -// synchronized (waitter) { -// waitter.wait(); -// } -// } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientsTest.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientsTest.java deleted file mode 100644 index b475d49b0b..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/ClientsTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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.apache.remoting.transport.mina; - -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.remoting.Transporter; -import org.apache.dubbo.remoting.transport.mina.MinaTransporter; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsString; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.fail; - -public class ClientsTest { - - @Test - public void testGetTransportEmpty() { - try { - ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(""); - fail(); - } catch (IllegalArgumentException expected) { - assertThat(expected.getMessage(), containsString("Extension name == null")); - } - } - - @Test - public void testGetTransportNull() { - Assertions.assertThrows(IllegalArgumentException.class, () -> { - String name = null; - ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(name); - }); - } - - @Test - public void testGetTransport1() { - String name = "mina"; - assertEquals(MinaTransporter.class, ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(name).getClass()); - } - - @Test - public void testGetTransportWrong() { - Assertions.assertThrows(IllegalStateException.class, () -> { - String name = "nety"; - assertNull(ExtensionLoader.getExtensionLoader(Transporter.class).getExtension(name).getClass()); - }); - } -} diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/Hello.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/Hello.java deleted file mode 100644 index 9e0f7c7483..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/Hello.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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.apache.remoting.transport.mina; - -import java.io.Serializable; - -/** - * Result - */ -public class Hello implements Serializable { - - private static final long serialVersionUID = 8563900571013747774L; - - private String name; - - public Hello() { - } - - public Hello(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/MinaClientToServerTest.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/MinaClientToServerTest.java deleted file mode 100644 index 433a4a8250..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/MinaClientToServerTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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.apache.remoting.transport.mina; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeChannel; -import org.apache.dubbo.remoting.exchange.ExchangeServer; -import org.apache.dubbo.remoting.exchange.Exchangers; -import org.apache.dubbo.remoting.exchange.support.Replier; - -/** - * MinaServerClientTest - */ -public class MinaClientToServerTest extends ClientToServerTest { - - @Override - protected ExchangeServer newServer(int port, Replier receiver) throws RemotingException { - return Exchangers.bind(URL.valueOf("exchange://localhost:" + port + "?server=mina"), receiver); - } - - @Override - protected ExchangeChannel newClient(int port) throws RemotingException { - return Exchangers.connect(URL.valueOf("exchange://localhost:" + port + "?client=mina&timeout=3000")); - } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/World.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/World.java deleted file mode 100644 index 79fc3de515..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/World.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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.apache.remoting.transport.mina; - -import java.io.Serializable; - -/** - * Data - */ -public class World implements Serializable { - - private static final long serialVersionUID = 8563900571013747774L; - - private String name; - - public World() { - } - - public World(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/WorldHandler.java b/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/WorldHandler.java deleted file mode 100644 index f74a6c1c88..0000000000 --- a/dubbo-remoting/dubbo-remoting-mina/src/test/java/org/apache/remoting/transport/mina/WorldHandler.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.apache.remoting.transport.mina; - -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeChannel; -import org.apache.dubbo.remoting.exchange.support.Replier; - -/** - * DataHandler - */ -public class WorldHandler implements Replier { - - public Class interest() { - return World.class; - } - - public Object reply(ExchangeChannel channel, World msg) throws RemotingException { - return new Hello("hello," + msg.getName()); - } - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/pom.xml b/dubbo-remoting/dubbo-remoting-p2p/pom.xml deleted file mode 100644 index ff0bbee5e2..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-remoting - ${revision} - ../pom.xml - - dubbo-remoting-p2p - jar - ${project.artifactId} - The p2p remoting module of dubbo project - - false - - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.parent.version} - test - - - \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Group.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Group.java deleted file mode 100644 index 57483889df..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Group.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; - -/** - * Group. (SPI, Prototype, ThreadSafe) - *

    - * Peer-to-peer - */ -public interface Group { - - /** - * get group url. - * - * @return group url. - */ - URL getUrl(); - - /** - * join. - * - * @param url - */ - Peer join(URL url, ChannelHandler handler) throws RemotingException; - - /** - * leave. - * - * @param url - * @throws RemotingException - */ - void leave(URL url) throws RemotingException; - - /** - * close the group. - */ - void close(); - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Networker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Networker.java deleted file mode 100644 index ff99a0abfc..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Networker.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.SPI; -import org.apache.dubbo.remoting.RemotingException; - -/** - * Networker. (SPI, Singleton, ThreadSafe) - *

    - * Peer-to-peer - */ -@SPI -public interface Networker { - - /** - * lookup group. - * - * @param url group url - * @return group. - */ - Group lookup(URL url) throws RemotingException; - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Networkers.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Networkers.java deleted file mode 100644 index 10f8138f90..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Networkers.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; - -/** - * Networkers. (API, Static, ThreadSafe) - *

    - * Peer-to-peer - */ -public class Networkers { - - public static Peer join(String group, String peer, ChannelHandler handler) throws RemotingException { - return join(URL.valueOf(group), URL.valueOf(peer), handler); - } - - public static Peer join(URL group, URL peer, ChannelHandler handler) throws RemotingException { - return lookup(group).join(peer, handler); - } - - public static Group lookup(String group) throws RemotingException { - return lookup(URL.valueOf(group)); - } - - public static Group lookup(URL group) throws RemotingException { - Networker networker = ExtensionLoader.getExtensionLoader(Networker.class).getExtension(group.getProtocol()); - return networker.lookup(group); - } -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Peer.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Peer.java deleted file mode 100644 index 9d23eacbde..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/Peer.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p; - -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.RemotingServer; - -/** - * Peer. (SPI, Prototype, ThreadSafe) - *

    - * Peer-to-peer - */ -public interface Peer extends RemotingServer { - - /** - * leave. - * - * @throws RemotingException - */ - void leave() throws RemotingException; - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeGroup.java deleted file mode 100644 index db6ef8c120..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeGroup.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.exchange; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.p2p.Group; - -/** - * Group - */ -public interface ExchangeGroup extends Group { - - /** - * join. - * - * @param url - */ - ExchangePeer join(URL url, ExchangeHandler handler) throws RemotingException; - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeNetworker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeNetworker.java deleted file mode 100644 index ba3ca8257c..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeNetworker.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.exchange; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingException; - -/** - * Networker - */ -public interface ExchangeNetworker { - - /** - * lookup group. - * - * @param url group url - * @return group. - */ - ExchangeGroup lookup(URL url) throws RemotingException; - -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeNetworkers.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeNetworkers.java deleted file mode 100644 index c720d9e43f..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangeNetworkers.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.exchange; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeHandler; - -/** - * Networkers - */ -public class ExchangeNetworkers { - - public static ExchangePeer join(String group, String peer, ExchangeHandler handler) throws RemotingException { - return join(URL.valueOf(group), URL.valueOf(peer), handler); - } - - public static ExchangePeer join(URL group, URL peer, ExchangeHandler handler) throws RemotingException { - return lookup(group).join(peer, handler); - } - - public static ExchangeGroup lookup(String group) throws RemotingException { - return lookup(URL.valueOf(group)); - } - - public static ExchangeGroup lookup(URL group) throws RemotingException { - ExchangeNetworker networker = ExtensionLoader.getExtensionLoader(ExchangeNetworker.class).getExtension(group.getProtocol()); - return networker.lookup(group); - } -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangePeer.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangePeer.java deleted file mode 100644 index 998e54de40..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/ExchangePeer.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.exchange; - -import org.apache.dubbo.remoting.exchange.ExchangeServer; -import org.apache.dubbo.remoting.p2p.Peer; - -/** - * Peer - */ -public interface ExchangePeer extends Peer, ExchangeServer { -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/AbstractExchangeGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/AbstractExchangeGroup.java deleted file mode 100644 index 55f1a9268b..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/AbstractExchangeGroup.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.exchange.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.Client; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.RemotingServer; -import org.apache.dubbo.remoting.exchange.ExchangeClient; -import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.exchange.ExchangeServer; -import org.apache.dubbo.remoting.exchange.Exchangers; -import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerDispatcher; -import org.apache.dubbo.remoting.p2p.Peer; -import org.apache.dubbo.remoting.p2p.exchange.ExchangeGroup; -import org.apache.dubbo.remoting.p2p.exchange.ExchangePeer; - -import java.util.ArrayList; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * AbstractGroup - */ -public abstract class AbstractExchangeGroup implements ExchangeGroup { - - // log output - protected static final Logger logger = LoggerFactory.getLogger(AbstractExchangeGroup.class); - - protected final URL url; - - protected final Map servers = new ConcurrentHashMap(); - - protected final Map clients = new ConcurrentHashMap(); - - protected final ExchangeHandlerDispatcher dispatcher = new ExchangeHandlerDispatcher(); - - public AbstractExchangeGroup(URL url) { - if (url == null) { - throw new IllegalArgumentException("url == null"); - } - this.url = url; - } - - @Override - public URL getUrl() { - return url; - } - - @Override - public void close() { - for (URL url : new ArrayList(servers.keySet())) { - try { - leave(url); - } catch (Throwable t) { - logger.error(t.getMessage(), t); - } - } - for (URL url : new ArrayList(clients.keySet())) { - try { - disconnect(url); - } catch (Throwable t) { - logger.error(t.getMessage(), t); - } - } - } - - @Override - public Peer join(URL url, ChannelHandler handler) throws RemotingException { - return join(url, (ExchangeHandler) handler); - } - - @Override - public ExchangePeer join(URL url, ExchangeHandler handler) throws RemotingException { - ExchangeServer server = servers.get(url); - if (server == null) { // TODO exist concurrent gap - server = Exchangers.bind(url, handler); - servers.put(url, server); - dispatcher.addChannelHandler(handler); - } - return new ExchangeServerPeer(server, clients, this); - } - - @Override - public void leave(URL url) throws RemotingException { - RemotingServer server = servers.remove(url); - if (server != null) { - server.close(); - } - } - - protected Client connect(URL url) throws RemotingException { - if (servers.containsKey(url)) { - return null; - } - ExchangeClient client = clients.get(url); - if (client == null) { // TODO exist concurrent gap - client = Exchangers.connect(url, dispatcher); - clients.put(url, client); - } - return client; - } - - protected void disconnect(URL url) throws RemotingException { - Client client = clients.remove(url); - if (client != null) { - client.close(); - } - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java deleted file mode 100644 index 82038410de..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/ExchangeServerPeer.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.exchange.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.Client; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeChannel; -import org.apache.dubbo.remoting.exchange.ExchangeClient; -import org.apache.dubbo.remoting.exchange.ExchangeServer; -import org.apache.dubbo.remoting.exchange.support.ExchangeServerDelegate; -import org.apache.dubbo.remoting.p2p.exchange.ExchangeGroup; -import org.apache.dubbo.remoting.p2p.exchange.ExchangePeer; - -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; - -/** - * ServerPeer - */ -public class ExchangeServerPeer extends ExchangeServerDelegate implements ExchangePeer { - - private static final Logger logger = LoggerFactory.getLogger(ExchangeServerPeer.class); - - private final Map clients; - - private final ExchangeGroup group; - - public ExchangeServerPeer(ExchangeServer server, Map clients, ExchangeGroup group) { - super(server); - this.clients = clients; - this.group = group; - } - - @Override - public void leave() throws RemotingException { - group.leave(getUrl()); - } - - @Override - public void close() { - try { - leave(); - } catch (RemotingException e) { - logger.error(e.getMessage(), e); - } - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - @Override - public Collection getChannels() { - return (Collection) getExchangeChannels(); - } - - @Override - public Channel getChannel(InetSocketAddress remoteAddress) { - return getExchangeChannel(remoteAddress); - } - - @Override - public Collection getExchangeChannels() { - Collection channels = super.getExchangeChannels(); - if (clients.size() > 0) { - channels = channels == null ? new ArrayList() : new ArrayList(channels); - channels.addAll(clients.values()); - } - return channels; - } - - @Override - public ExchangeChannel getExchangeChannel(InetSocketAddress remoteAddress) { - String host = remoteAddress.getAddress() != null ? remoteAddress.getAddress().getHostAddress() : remoteAddress.getHostName(); - int port = remoteAddress.getPort(); - ExchangeChannel channel = super.getExchangeChannel(remoteAddress); - if (channel == null) { - for (Map.Entry entry : clients.entrySet()) { - URL url = entry.getKey(); - if (url.getIp().equals(host) && url.getPort() == port) { - return entry.getValue(); - } - } - } - return channel; - } - - @Override - public void send(Object message) throws RemotingException { - send(message, getUrl().getParameter(Constants.SENT_KEY, false)); - } - - @Override - public void send(Object message, boolean sent) throws RemotingException { - Throwable last = null; - try { - super.send(message, sent); - } catch (Throwable t) { - last = t; - } - for (Client client : clients.values()) { - try { - client.send(message, sent); - } catch (Throwable t) { - last = t; - } - } - if (last != null) { - if (last instanceof RemotingException) { - throw (RemotingException) last; - } else if (last instanceof RuntimeException) { - throw (RuntimeException) last; - } else { - throw new RuntimeException(last.getMessage(), last); - } - } - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/FileExchangeGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/FileExchangeGroup.java deleted file mode 100644 index 554b0e3dc2..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/FileExchangeGroup.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.exchange.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.ExecutorUtil; -import org.apache.dubbo.common.utils.IOUtils; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.p2p.exchange.ExchangePeer; - -import java.io.File; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -/** - * FileGroup - */ -public class FileExchangeGroup extends AbstractExchangeGroup { - - private final File file; - // scheduled executor service - private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3, new NamedThreadFactory("FileGroupModifiedChecker", true)); - // Reconnect the timer to check whether the connection is available at a time, and when unavailable, an infinite reconnection - private final ScheduledFuture checkModifiedFuture; - private volatile long last; - - public FileExchangeGroup(URL url) { - super(url); - String path = url.getHost() + "/" + url.getPath(); - file = new File(path); - if (!file.exists()) { - throw new IllegalStateException("The group file not exists. file: " + path); - } - checkModifiedFuture = scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - // check the file change - try { - check(); - } catch (Throwable t) { // Defensive fault tolerance - logger.error("Unexpected error occur at reconnect, cause: " + t.getMessage(), t); - } - } - }, 2000, 2000, TimeUnit.MILLISECONDS); - } - - @Override - public void close() { - super.close(); - try { - ExecutorUtil.cancelScheduledFuture(checkModifiedFuture); - } catch (Throwable t) { - logger.error(t.getMessage(), t); - } - } - - private void check() throws RemotingException { - long modified = file.lastModified(); - if (modified > last) { - last = modified; - changed(); - } - } - - private void changed() throws RemotingException { - try { - String[] lines = IOUtils.readLines(file); - for (String line : lines) { - connect(URL.valueOf(line)); - } - } catch (IOException e) { - throw new RemotingException(new InetSocketAddress(NetUtils.getLocalHost(), 0), getUrl().toInetSocketAddress(), e.getMessage(), e); - } - } - - public ExchangePeer joinExchange(URL url, ExchangeHandler handler) throws RemotingException { - ExchangePeer peer = super.join(url, handler); - try { - String full = url.toFullString(); - String[] lines = IOUtils.readLines(file); - for (String line : lines) { - if (full.equals(line)) { - return peer; - } - } - IOUtils.appendLines(file, new String[]{full}); - } catch (IOException e) { - throw new RemotingException(new InetSocketAddress(NetUtils.getLocalHost(), 0), getUrl().toInetSocketAddress(), e.getMessage(), e); - } - return peer; - } - - @Override - public void leave(URL url) throws RemotingException { - super.leave(url); - try { - String full = url.toFullString(); - String[] lines = IOUtils.readLines(file); - List saves = new ArrayList(); - for (String line : lines) { - if (full.equals(line)) { - return; - } - saves.add(line); - } - IOUtils.appendLines(file, saves.toArray(new String[0])); - } catch (IOException e) { - throw new RemotingException(new InetSocketAddress(NetUtils.getLocalHost(), 0), getUrl().toInetSocketAddress(), e.getMessage(), e); - } - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/FileExchangeNetworker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/FileExchangeNetworker.java deleted file mode 100644 index 6f66afcb84..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/FileExchangeNetworker.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.exchange.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.p2p.exchange.ExchangeGroup; -import org.apache.dubbo.remoting.p2p.exchange.ExchangeNetworker; - -/** - * FileNetworker - */ -public class FileExchangeNetworker implements ExchangeNetworker { - - @Override - public ExchangeGroup lookup(URL url) throws RemotingException { - return new FileExchangeGroup(url); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeGroup.java deleted file mode 100644 index e808086774..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeGroup.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.exchange.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.p2p.exchange.ExchangePeer; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.MulticastSocket; - -/** - * MulticastGroup - */ -public class MulticastExchangeGroup extends AbstractExchangeGroup { - - private static final String JOIN = "join"; - - private static final String LEAVE = "leave"; - - private InetAddress mutilcastAddress; - - private MulticastSocket mutilcastSocket; - - public MulticastExchangeGroup(URL url) { - super(url); - if (!NetUtils.isMulticastAddress(url.getHost())) { - throw new IllegalArgumentException("Invalid multicast address " + url.getHost() + ", scope: 224.0.0.0 - 239.255.255.255"); - } - try { - mutilcastAddress = InetAddress.getByName(url.getHost()); - mutilcastSocket = new MulticastSocket(url.getPort()); - mutilcastSocket.setLoopbackMode(false); - mutilcastSocket.joinGroup(mutilcastAddress); - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - byte[] buf = new byte[1024]; - DatagramPacket recv = new DatagramPacket(buf, buf.length); - while (true) { - try { - mutilcastSocket.receive(recv); - MulticastExchangeGroup.this.receive(new String(recv.getData()).trim(), (InetSocketAddress) recv.getSocketAddress()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - } - } - }, "MulticastGroupReceiver"); - thread.setDaemon(true); - thread.start(); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private void send(String msg) throws RemotingException { - DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), mutilcastAddress, mutilcastSocket.getLocalPort()); - try { - mutilcastSocket.send(hi); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private void receive(String msg, InetSocketAddress remoteAddress) throws RemotingException { - if (msg.startsWith(JOIN)) { - String url = msg.substring(JOIN.length()).trim(); - connect(URL.valueOf(url)); - } else if (msg.startsWith(LEAVE)) { - String url = msg.substring(LEAVE.length()).trim(); - disconnect(URL.valueOf(url)); - } - } - - @Override - public ExchangePeer join(URL url, ExchangeHandler handler) throws RemotingException { - ExchangePeer peer = super.join(url, handler); - send(JOIN + " " + url.toFullString()); - return peer; - } - - @Override - public void leave(URL url) throws RemotingException { - super.leave(url); - send(LEAVE + " " + url.toFullString()); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworker.java deleted file mode 100644 index cd46082286..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworker.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.exchange.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.p2p.exchange.ExchangeGroup; -import org.apache.dubbo.remoting.p2p.exchange.ExchangeNetworker; - -/** - * MulticastNetworker - */ -public class MulticastExchangeNetworker implements ExchangeNetworker { - - @Override - public ExchangeGroup lookup(URL url) throws RemotingException { - return new MulticastExchangeGroup(url); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/AbstractGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/AbstractGroup.java deleted file mode 100644 index 0ea76f9473..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/AbstractGroup.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.Client; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.RemotingServer; -import org.apache.dubbo.remoting.Transporters; -import org.apache.dubbo.remoting.p2p.Group; -import org.apache.dubbo.remoting.p2p.Peer; -import org.apache.dubbo.remoting.transport.ChannelHandlerDispatcher; - -import java.util.ArrayList; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * AbstractGroup - */ -public abstract class AbstractGroup implements Group { - - // log output - protected static final Logger logger = LoggerFactory.getLogger(AbstractGroup.class); - - protected final URL url; - - protected final Map servers = new ConcurrentHashMap(); - - protected final Map clients = new ConcurrentHashMap(); - - protected final ChannelHandlerDispatcher dispatcher = new ChannelHandlerDispatcher(); - - public AbstractGroup(URL url) { - if (url == null) { - throw new IllegalArgumentException("url == null"); - } - this.url = url; - } - - @Override - public URL getUrl() { - return url; - } - - @Override - public void close() { - for (URL url : new ArrayList(servers.keySet())) { - try { - leave(url); - } catch (Throwable t) { - logger.error(t.getMessage(), t); - } - } - for (URL url : new ArrayList(clients.keySet())) { - try { - disconnect(url); - } catch (Throwable t) { - logger.error(t.getMessage(), t); - } - } - } - - @Override - public Peer join(URL url, ChannelHandler handler) throws RemotingException { - RemotingServer server = servers.get(url); - if (server == null) { // TODO exist concurrent gap - server = Transporters.bind(url, handler); - servers.put(url, server); - dispatcher.addChannelHandler(handler); - } - return new ServerPeer(server, clients, this); - } - - @Override - public void leave(URL url) throws RemotingException { - RemotingServer server = servers.remove(url); - if (server != null) { - server.close(); - } - } - - protected Client connect(URL url) throws RemotingException { - if (servers.containsKey(url)) { - return null; - } - Client client = clients.get(url); - if (client == null) { // TODO exist concurrent gap - client = Transporters.connect(url, dispatcher); - clients.put(url, client); - } - return client; - } - - protected void disconnect(URL url) throws RemotingException { - Client client = clients.remove(url); - if (client != null) { - client.close(); - } - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/FileGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/FileGroup.java deleted file mode 100644 index 68562c1525..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/FileGroup.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.ExecutorUtil; -import org.apache.dubbo.common.utils.IOUtils; -import org.apache.dubbo.common.utils.NamedThreadFactory; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.p2p.Peer; - -import java.io.File; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -/** - * FileGroup - */ -public class FileGroup extends AbstractGroup { - - private final File file; - // Scheduled executor service - private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3, new NamedThreadFactory("FileGroupModifiedChecker", true)); - // Reconnect the timer to check whether the connection is available at a time, and when unavailable, an infinite reconnection - private final ScheduledFuture checkModifiedFuture; - private volatile long last; - - public FileGroup(URL url) { - super(url); - String path = url.getAbsolutePath(); - file = new File(path); - checkModifiedFuture = scheduledExecutorService.scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { - // Check the file change - try { - check(); - } catch (Throwable t) { // Defensive fault tolerance - logger.error("Unexpected error occur at reconnect, cause: " + t.getMessage(), t); - } - } - }, 2000, 2000, TimeUnit.MILLISECONDS); - } - - @Override - public void close() { - super.close(); - try { - ExecutorUtil.cancelScheduledFuture(checkModifiedFuture); - } catch (Throwable t) { - logger.error(t.getMessage(), t); - } - } - - private void check() throws RemotingException { - long modified = file.lastModified(); - if (modified > last) { - last = modified; - changed(); - } - } - - private void changed() throws RemotingException { - try { - String[] lines = IOUtils.readLines(file); - for (String line : lines) { - connect(URL.valueOf(line)); - } - } catch (IOException e) { - throw new RemotingException(new InetSocketAddress(NetUtils.getLocalHost(), 0), getUrl().toInetSocketAddress(), e.getMessage(), e); - } - } - - @Override - public Peer join(URL url, ChannelHandler handler) throws RemotingException { - Peer peer = super.join(url, handler); - try { - String full = url.toFullString(); - String[] lines = IOUtils.readLines(file); - for (String line : lines) { - if (full.equals(line)) { - return peer; - } - } - IOUtils.appendLines(file, new String[]{full}); - } catch (IOException e) { - throw new RemotingException(new InetSocketAddress(NetUtils.getLocalHost(), 0), getUrl().toInetSocketAddress(), e.getMessage(), e); - } - return peer; - } - - @Override - public void leave(URL url) throws RemotingException { - super.leave(url); - try { - String full = url.toFullString(); - String[] lines = IOUtils.readLines(file); - List saves = new ArrayList(); - for (String line : lines) { - if (full.equals(line)) { - return; - } - saves.add(line); - } - IOUtils.appendLines(file, saves.toArray(new String[0])); - } catch (IOException e) { - throw new RemotingException(new InetSocketAddress(NetUtils.getLocalHost(), 0), getUrl().toInetSocketAddress(), e.getMessage(), e); - } - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/FileNetworker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/FileNetworker.java deleted file mode 100644 index 90569d4643..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/FileNetworker.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.p2p.Group; -import org.apache.dubbo.remoting.p2p.Networker; - -/** - * FileNetworker - */ -public class FileNetworker implements Networker { - - @Override - public Group lookup(URL url) throws RemotingException { - return new FileGroup(url); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/MulticastGroup.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/MulticastGroup.java deleted file mode 100644 index e070d10614..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/MulticastGroup.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.p2p.Peer; - -import java.io.IOException; -import java.net.DatagramPacket; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.MulticastSocket; - -/** - * MulticastGroup - */ -public class MulticastGroup extends AbstractGroup { - - private static final String JOIN = "join"; - - private static final String LEAVE = "leave"; - - private InetAddress mutilcastAddress; - - private MulticastSocket mutilcastSocket; - - public MulticastGroup(URL url) { - super(url); - if (!NetUtils.isMulticastAddress(url.getHost())) { - throw new IllegalArgumentException("Invalid multicast address " + url.getHost() + ", scope: 224.0.0.0 - 239.255.255.255"); - } - try { - mutilcastAddress = InetAddress.getByName(url.getHost()); - mutilcastSocket = new MulticastSocket(url.getPort()); - mutilcastSocket.setLoopbackMode(false); - mutilcastSocket.joinGroup(mutilcastAddress); - Thread thread = new Thread(new Runnable() { - @Override - public void run() { - byte[] buf = new byte[1024]; - DatagramPacket recv = new DatagramPacket(buf, buf.length); - while (true) { - try { - mutilcastSocket.receive(recv); - MulticastGroup.this.receive(new String(recv.getData()).trim(), (InetSocketAddress) recv.getSocketAddress()); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - } - } - }, "MulticastGroupReceiver"); - thread.setDaemon(true); - thread.start(); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private void send(String msg) throws RemotingException { - DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), mutilcastAddress, mutilcastSocket.getLocalPort()); - try { - mutilcastSocket.send(hi); - } catch (IOException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - private void receive(String msg, InetSocketAddress remoteAddress) throws RemotingException { - if (msg.startsWith(JOIN)) { - String url = msg.substring(JOIN.length()).trim(); - connect(URL.valueOf(url)); - } else if (msg.startsWith(LEAVE)) { - String url = msg.substring(LEAVE.length()).trim(); - disconnect(URL.valueOf(url)); - } - } - - @Override - public Peer join(URL url, ChannelHandler handler) throws RemotingException { - Peer peer = super.join(url, handler); - send(JOIN + " " + url.toFullString()); - return peer; - } - - @Override - public void leave(URL url) throws RemotingException { - super.leave(url); - send(LEAVE + " " + url.toFullString()); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/MulticastNetworker.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/MulticastNetworker.java deleted file mode 100644 index 09c8de2b54..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/MulticastNetworker.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.p2p.Group; -import org.apache.dubbo.remoting.p2p.Networker; - -/** - * MulticastNetworker - */ -public class MulticastNetworker implements Networker { - - @Override - public Group lookup(URL url) throws RemotingException { - return new MulticastGroup(url); - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java b/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java deleted file mode 100644 index 3d1090737c..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/java/org/apache/dubbo/remoting/p2p/support/ServerPeer.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.Client; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.RemotingServer; -import org.apache.dubbo.remoting.p2p.Group; -import org.apache.dubbo.remoting.p2p.Peer; -import org.apache.dubbo.remoting.transport.ServerDelegate; - -import java.net.InetSocketAddress; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; - -/** - * ServerPeer - */ -public class ServerPeer extends ServerDelegate implements Peer { - - private static final Logger logger = LoggerFactory.getLogger(ServerPeer.class); - - private final Map clients; - - private final Group group; - - public ServerPeer(RemotingServer server, Map clients, Group group) { - super(server); - this.clients = clients; - this.group = group; - } - - @Override - public void leave() throws RemotingException { - group.leave(getUrl()); - } - - @Override - public void close() { - try { - leave(); - } catch (RemotingException e) { - logger.error(e.getMessage(), e); - } - } - - @Override - public Collection getChannels() { - Collection channels = super.getChannels(); - if (clients.size() > 0) { - channels = channels == null ? new ArrayList() : new ArrayList(channels); - channels.addAll(clients.values()); - } - return channels; - } - - @Override - public Channel getChannel(InetSocketAddress remoteAddress) { - String host = remoteAddress.getAddress() != null ? remoteAddress.getAddress().getHostAddress() : remoteAddress.getHostName(); - int port = remoteAddress.getPort(); - Channel channel = super.getChannel(remoteAddress); - if (channel == null) { - for (Map.Entry entry : clients.entrySet()) { - URL url = entry.getKey(); - if (url.getIp().equals(host) && url.getPort() == port) { - return entry.getValue(); - } - } - } - return channel; - } - - @Override - public void send(Object message) throws RemotingException { - send(message, getUrl().getParameter(Constants.SENT_KEY, false)); - } - - @Override - public void send(Object message, boolean sent) throws RemotingException { - Throwable last = null; - try { - super.send(message, sent); - } catch (Throwable t) { - last = t; - } - for (Client client : clients.values()) { - try { - client.send(message, sent); - } catch (Throwable t) { - last = t; - } - } - if (last != null) { - if (last instanceof RemotingException) { - throw (RemotingException) last; - } else if (last instanceof RuntimeException) { - throw (RuntimeException) last; - } else { - throw new RuntimeException(last.getMessage(), last); - } - } - } - -} diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.p2p.Networker b/dubbo-remoting/dubbo-remoting-p2p/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.p2p.Networker deleted file mode 100644 index 08140a367c..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.p2p.Networker +++ /dev/null @@ -1,2 +0,0 @@ -multicast=org.apache.dubbo.remoting.p2p.support.MulticastNetworker -file=org.apache.dubbo.remoting.p2p.support.FileNetworker \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworkerTest.java b/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworkerTest.java deleted file mode 100644 index d102c992c4..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/exchange/support/MulticastExchangeNetworkerTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.exchange.support; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.nullValue; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.exchange.ExchangeChannel; -import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import org.apache.dubbo.remoting.p2p.Group; -import org.apache.dubbo.remoting.p2p.Networkers; -import org.apache.dubbo.remoting.p2p.Peer; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.mock; - -public class MulticastExchangeNetworkerTest { - @Test - public void testJoin() throws RemotingException, InterruptedException { - final String groupURL = "multicast://224.5.6.7:1234"; - - MulticastExchangeNetworker multicastExchangeNetworker = new MulticastExchangeNetworker(); - - final CountDownLatch countDownLatch = new CountDownLatch(1); - Peer peer1 = multicastExchangeNetworker.lookup(URL.valueOf(groupURL)) - .join(URL.valueOf("dubbo://0.0.0.0:" + NetUtils.getAvailablePort()), new ExchangeHandlerAdapter() { - @Override - public CompletableFuture reply(ExchangeChannel channel, Object msg) throws RemotingException { - countDownLatch.countDown(); - return super.reply(channel, msg); - } - }); - Peer peer2 = multicastExchangeNetworker.lookup(URL.valueOf(groupURL)) - .join(URL.valueOf("dubbo://0.0.0.0:" + NetUtils.getAvailablePort()), mock(ExchangeHandler.class)); - - while (true) { - for (Channel channel : peer1.getChannels()) { - channel.send("hello multicast exchange network!"); - } - TimeUnit.MILLISECONDS.sleep(50); - - long count = countDownLatch.getCount(); - if (count > 0) { - break; - } - } - - Group lookup = Networkers.lookup(groupURL); - assertThat(lookup, not(nullValue())); - - assertThat(peer1, instanceOf(ExchangeServerPeer.class)); - - peer1.close(); - peer2.close(); - } -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/FileNetworkerTest.java b/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/FileNetworkerTest.java deleted file mode 100644 index a442173c45..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/FileNetworkerTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.p2p.Group; -import org.apache.dubbo.remoting.p2p.Peer; -import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; - -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -import java.nio.file.Path; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import static org.mockito.Mockito.mock; - -public class FileNetworkerTest { - - @BeforeEach - public void setUp(@TempDir Path folder) throws Exception { - folder.toFile().createNewFile(); - } - - @AfterEach - public void tearDown(@TempDir Path folder) { - folder.getFileName().toAbsolutePath().toFile().delete(); - } - - @Test - public void testJoin(@TempDir Path folder) throws RemotingException, InterruptedException { - final String groupURL = "file:///" + folder.getFileName().toAbsolutePath(); - - FileNetworker networker = new FileNetworker(); - Group group = networker.lookup(URL.valueOf(groupURL)); - - final CountDownLatch countDownLatch = new CountDownLatch(1); - Peer peer1 = group.join(URL.valueOf("dubbo://0.0.0.0:" + NetUtils.getAvailablePort()), new ChannelHandlerAdapter() { - @Override - public void received(Channel channel, Object message) { - countDownLatch.countDown(); - } - }); - Peer peer2 = group.join(URL.valueOf("dubbo://0.0.0.0:" + NetUtils.getAvailablePort()), - mock(ChannelHandlerAdapter.class)); - - while (true) { - long count = countDownLatch.getCount(); - if (count > 0) { - break; - } - for (Channel channel : peer1.getChannels()) { - channel.send(0, false); - channel.send("hello world!"); - } - TimeUnit.MILLISECONDS.sleep(50); - } - - - peer2.close(); - peer1.close(); - } -} \ No newline at end of file diff --git a/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/MulticastNetworkerTest.java b/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/MulticastNetworkerTest.java deleted file mode 100644 index 2229f0480a..0000000000 --- a/dubbo-remoting/dubbo-remoting-p2p/src/test/java/org/apache/dubbo/remoting/p2p/support/MulticastNetworkerTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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.apache.dubbo.remoting.p2p.support; - -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.p2p.Group; -import org.apache.dubbo.remoting.p2p.Networkers; -import org.apache.dubbo.remoting.p2p.Peer; -import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.mock; - -public class MulticastNetworkerTest { - - @Test - public void testJoin() throws RemotingException, InterruptedException { - final String groupURL = "multicast://224.5.6.7:1234"; - final String peerURL = "dubbo://0.0.0.0:" + NetUtils.getAvailablePort(); - - final CountDownLatch countDownLatch = new CountDownLatch(1); - Peer peer1 = Networkers.join(groupURL, peerURL, new ChannelHandlerAdapter() { - @Override - public void received(Channel channel, Object message) { - countDownLatch.countDown(); - } - }); - Peer peer2 = Networkers.join(groupURL, "dubbo://0.0.0.0:" + NetUtils.getAvailablePort(), - mock(ChannelHandlerAdapter.class)); - - while (true) { - long count = countDownLatch.getCount(); - if (count > 0) { - break; - } - for (Channel channel : peer1.getChannels()) { - channel.send("hello world!"); - } - TimeUnit.MILLISECONDS.sleep(50); - } - - Group lookup = Networkers.lookup(groupURL); - assertThat(lookup, not(nullValue())); - - peer2.close(); - peer1.close(); - } -} \ No newline at end of file diff --git a/dubbo-remoting/pom.xml b/dubbo-remoting/pom.xml index 19970adfd8..5c37a6debb 100644 --- a/dubbo-remoting/pom.xml +++ b/dubbo-remoting/pom.xml @@ -33,12 +33,7 @@ dubbo-remoting-api dubbo-remoting-netty - dubbo-remoting-mina - dubbo-remoting-grizzly - dubbo-remoting-p2p - dubbo-remoting-http dubbo-remoting-zookeeper dubbo-remoting-netty4 - dubbo-remoting-etcd3 \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/pom.xml b/dubbo-rpc/dubbo-rpc-hessian/pom.xml deleted file mode 100644 index 5a0a8383e3..0000000000 --- a/dubbo-rpc/dubbo-rpc-hessian/pom.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-hessian - jar - ${project.artifactId} - The hessian rpc module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-http - ${project.parent.version} - - - com.caucho - hessian - - - org.apache.httpcomponents - httpclient - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.parent.version} - test - - - org.springframework - spring-test - test - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/Constants.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/Constants.java deleted file mode 100644 index 7b5eb6c4c2..0000000000 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/Constants.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.hessian; - -/** - * - */ -public interface Constants { - - String HESSIAN2_REQUEST_KEY = "hessian2.request"; - - boolean DEFAULT_HESSIAN2_REQUEST = false; - - String HESSIAN_OVERLOAD_METHOD_KEY = "hessian.overload.method"; - - boolean DEFAULT_HESSIAN_OVERLOAD_METHOD = false; - - String DEFAULT_HTTP_CLIENT = "jdk"; - -} diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java deleted file mode 100644 index ed8b4d58c2..0000000000 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/DubboHessianURLConnectionFactory.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.hessian; - -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.RpcContext; - -import com.caucho.hessian.client.HessianConnection; -import com.caucho.hessian.client.HessianURLConnectionFactory; - -import java.io.IOException; -import java.net.URL; - -public class DubboHessianURLConnectionFactory extends HessianURLConnectionFactory { - - @Override - public HessianConnection open(URL url) throws IOException { - HessianConnection connection = super.open(url); - RpcContext context = RpcContext.getContext(); - for (String key : context.getObjectAttachments().keySet()) { - connection.addHeader(Constants.DEFAULT_EXCHANGER + key, context.getAttachment(key)); - } - - return connection; - } -} diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java deleted file mode 100644 index 648e0f25e4..0000000000 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocol.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.hessian; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingServer; -import org.apache.dubbo.remoting.http.HttpBinder; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.rpc.ProtocolServer; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; -import org.apache.dubbo.rpc.service.GenericService; -import org.apache.dubbo.rpc.support.ProtocolUtils; - -import com.caucho.hessian.HessianException; -import com.caucho.hessian.client.HessianConnectionException; -import com.caucho.hessian.client.HessianConnectionFactory; -import com.caucho.hessian.client.HessianProxyFactory; -import com.caucho.hessian.io.HessianMethodSerializationException; -import com.caucho.hessian.server.HessianSkeleton; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; -import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.remoting.Constants.CLIENT_KEY; -import static org.apache.dubbo.remoting.Constants.DEFAULT_EXCHANGER; -import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; -import static org.apache.dubbo.rpc.protocol.hessian.Constants.DEFAULT_HESSIAN2_REQUEST; -import static org.apache.dubbo.rpc.protocol.hessian.Constants.DEFAULT_HESSIAN_OVERLOAD_METHOD; -import static org.apache.dubbo.rpc.protocol.hessian.Constants.DEFAULT_HTTP_CLIENT; -import static org.apache.dubbo.rpc.protocol.hessian.Constants.HESSIAN2_REQUEST_KEY; -import static org.apache.dubbo.rpc.protocol.hessian.Constants.HESSIAN_OVERLOAD_METHOD_KEY; - -/** - * http rpc support. - */ -public class HessianProtocol extends AbstractProxyProtocol { - - private final Map skeletonMap = new ConcurrentHashMap(); - - private HttpBinder httpBinder; - - public HessianProtocol() { - super(HessianException.class); - } - - public void setHttpBinder(HttpBinder httpBinder) { - this.httpBinder = httpBinder; - } - - @Override - public int getDefaultPort() { - return 80; - } - - @Override - protected Runnable doExport(T impl, Class type, URL url) throws RpcException { - String addr = getAddr(url); - ProtocolServer protocolServer = serverMap.get(addr); - if (protocolServer == null) { - RemotingServer remotingServer = httpBinder.bind(url, new HessianHandler()); - serverMap.put(addr, new ProxyProtocolServer(remotingServer)); - } - final String path = url.getAbsolutePath(); - final HessianSkeleton skeleton = new HessianSkeleton(impl, type); - skeletonMap.put(path, skeleton); - - final String genericPath = path + "/" + GENERIC_KEY; - skeletonMap.put(genericPath, new HessianSkeleton(impl, GenericService.class)); - - return new Runnable() { - @Override - public void run() { - skeletonMap.remove(path); - skeletonMap.remove(genericPath); - } - }; - } - - @Override - @SuppressWarnings("unchecked") - protected T doRefer(Class serviceType, URL url) throws RpcException { - String generic = url.getParameter(GENERIC_KEY); - boolean isGeneric = ProtocolUtils.isGeneric(generic) || serviceType.equals(GenericService.class); - if (isGeneric) { - RpcContext.getContext().setAttachment(GENERIC_KEY, generic); - url = url.setPath(url.getPath() + "/" + GENERIC_KEY); - } - - HessianProxyFactory hessianProxyFactory = new HessianProxyFactory(); - boolean isHessian2Request = url.getParameter(HESSIAN2_REQUEST_KEY, DEFAULT_HESSIAN2_REQUEST); - hessianProxyFactory.setHessian2Request(isHessian2Request); - boolean isOverloadEnabled = url.getParameter(HESSIAN_OVERLOAD_METHOD_KEY, DEFAULT_HESSIAN_OVERLOAD_METHOD); - hessianProxyFactory.setOverloadEnabled(isOverloadEnabled); - String client = url.getParameter(CLIENT_KEY, DEFAULT_HTTP_CLIENT); - if ("httpclient".equals(client)) { - HessianConnectionFactory factory = new HttpClientConnectionFactory(); - factory.setHessianProxyFactory(hessianProxyFactory); - hessianProxyFactory.setConnectionFactory(factory); - } else if (client != null && client.length() > 0 && !DEFAULT_HTTP_CLIENT.equals(client)) { - throw new IllegalStateException("Unsupported http protocol client=\"" + client + "\"!"); - } else { - HessianConnectionFactory factory = new DubboHessianURLConnectionFactory(); - factory.setHessianProxyFactory(hessianProxyFactory); - hessianProxyFactory.setConnectionFactory(factory); - } - int timeout = url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); - hessianProxyFactory.setConnectTimeout(timeout); - hessianProxyFactory.setReadTimeout(timeout); - return (T) hessianProxyFactory.create(serviceType, url.setProtocol("http").toJavaURL(), Thread.currentThread().getContextClassLoader()); - } - - @Override - protected int getErrorCode(Throwable e) { - if (e instanceof HessianConnectionException) { - if (e.getCause() != null) { - Class cls = e.getCause().getClass(); - if (SocketTimeoutException.class.equals(cls)) { - return RpcException.TIMEOUT_EXCEPTION; - } - } - return RpcException.NETWORK_EXCEPTION; - } else if (e instanceof HessianMethodSerializationException) { - return RpcException.SERIALIZATION_EXCEPTION; - } - return super.getErrorCode(e); - } - - @Override - public void destroy() { - super.destroy(); - for (String key : new ArrayList(serverMap.keySet())) { - ProtocolServer protocolServer = serverMap.remove(key); - if (protocolServer != null) { - try { - if (logger.isInfoEnabled()) { - logger.info("Close hessian server " + protocolServer.getUrl()); - } - protocolServer.close(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } - } - } - - private class HessianHandler implements HttpHandler { - - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException { - String uri = request.getRequestURI(); - HessianSkeleton skeleton = skeletonMap.get(uri); - if (!"POST".equalsIgnoreCase(request.getMethod())) { - response.setStatus(500); - } else { - RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); - - Enumeration enumeration = request.getHeaderNames(); - while (enumeration.hasMoreElements()) { - String key = enumeration.nextElement(); - if (key.startsWith(DEFAULT_EXCHANGER)) { - RpcContext.getContext().setAttachment(key.substring(DEFAULT_EXCHANGER.length()), - request.getHeader(key)); - } - } - - try { - skeleton.invoke(request.getInputStream(), response.getOutputStream()); - } catch (Throwable e) { - throw new ServletException(e); - } - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnection.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnection.java deleted file mode 100644 index 2c339260ff..0000000000 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnection.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.hessian; - -import com.caucho.hessian.client.HessianConnection; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ByteArrayEntity; -import org.apache.http.message.BasicHeader; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; - -/** - * HttpClientConnection - */ -public class HttpClientConnection implements HessianConnection { - - private final HttpClient httpClient; - - private final ByteArrayOutputStream output; - - private final HttpPost request; - - private volatile HttpResponse response; - - public HttpClientConnection(HttpClient httpClient, URL url) { - this.httpClient = httpClient; - this.output = new ByteArrayOutputStream(); - this.request = new HttpPost(url.toString()); - } - - @Override - public void addHeader(String key, String value) { - request.addHeader(new BasicHeader(key, value)); - } - - @Override - public OutputStream getOutputStream() throws IOException { - return output; - } - - @Override - public void sendRequest() throws IOException { - request.setEntity(new ByteArrayEntity(output.toByteArray())); - this.response = httpClient.execute(request); - } - - @Override - public int getStatusCode() { - return response == null || response.getStatusLine() == null ? 0 : response.getStatusLine().getStatusCode(); - } - - @Override - public String getStatusMessage() { - return response == null || response.getStatusLine() == null ? null : response.getStatusLine().getReasonPhrase(); - } - - @Override - public String getContentEncoding() { - return (response == null || response.getEntity() == null || response.getEntity().getContentEncoding() == null) ? null : response.getEntity().getContentEncoding().getValue(); - } - - @Override - public InputStream getInputStream() throws IOException { - return response == null || response.getEntity() == null ? null : response.getEntity().getContent(); - } - - @Override - public void close() throws IOException { - HttpPost request = this.request; - if (request != null) { - request.abort(); - } - } - - @Override - public void destroy() throws IOException { - } - -} diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java b/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java deleted file mode 100644 index 13c30fb9e8..0000000000 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/java/org/apache/dubbo/rpc/protocol/hessian/HttpClientConnectionFactory.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.hessian; - -import org.apache.dubbo.rpc.RpcContext; - -import com.caucho.hessian.client.HessianConnection; -import com.caucho.hessian.client.HessianConnectionFactory; -import com.caucho.hessian.client.HessianProxyFactory; -import org.apache.http.client.HttpClient; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.HttpClientBuilder; - -import java.net.URL; - -import static org.apache.dubbo.remoting.Constants.DEFAULT_EXCHANGER; - -/** - * HttpClientConnectionFactory - * TODO, Consider using connection pool - */ -public class HttpClientConnectionFactory implements HessianConnectionFactory { - - private HttpClient httpClient; - - @Override - public void setHessianProxyFactory(HessianProxyFactory factory) { - RequestConfig requestConfig = RequestConfig.custom() - .setConnectionRequestTimeout((int) factory.getConnectTimeout()) - .setSocketTimeout((int) factory.getReadTimeout()) - .build(); - httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); - } - - @Override - public HessianConnection open(URL url) { - HttpClientConnection httpClientConnection = new HttpClientConnection(httpClient, url); - RpcContext context = RpcContext.getContext(); - for (String key : context.getObjectAttachments().keySet()) { - httpClientConnection.addHeader(DEFAULT_EXCHANGER + key, context.getAttachment(key)); - } - return httpClientConnection; - } -} diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-hessian/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol deleted file mode 100644 index cecd14777e..0000000000 --- a/dubbo-rpc/dubbo-rpc-hessian/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -hessian=org.apache.dubbo.rpc.protocol.hessian.HessianProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocolTest.java b/dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocolTest.java deleted file mode 100644 index a9bf02e0ef..0000000000 --- a/dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianProtocolTest.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.hessian; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; -import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; -import org.apache.dubbo.common.serialize.nativejava.NativeJavaSerialization; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.hessian.HessianServiceImpl.MyException; - -import org.apache.dubbo.rpc.service.GenericService; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import static org.junit.jupiter.api.Assertions.fail; - -/** - * HessianProtocolTest - */ -public class HessianProtocolTest { - - @Test - public void testHessianProtocol() { - HessianServiceImpl server = new HessianServiceImpl(); - Assertions.assertFalse(server.isCalled()); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + HessianService.class.getName() + "?version=1.0.0&hessian.overload.method=true"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); - Invoker invoker = protocol.refer(HessianService.class, url); - HessianService client = proxyFactory.getProxy(invoker); - String result = client.sayHello("haha"); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - public void testGenericInvoke() { - HessianServiceImpl server = new HessianServiceImpl(); - Assertions.assertFalse(server.isCalled()); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + HessianService.class.getName() + "?version=1.0.0"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); - Invoker invoker = protocol.refer(GenericService.class, url); - GenericService client = proxyFactory.getProxy(invoker, true); - String result = (String) client.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"haha"}); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - public void testGenericInvokeWithNativeJava() throws IOException, ClassNotFoundException { - HessianServiceImpl server = new HessianServiceImpl(); - Assertions.assertFalse(server.isCalled()); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + HessianService.class.getName() + "?version=1.0.0&generic=nativejava"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); - Invoker invoker = protocol.refer(GenericService.class, url); - GenericService client = proxyFactory.getProxy(invoker); - - Serialization serialization = new NativeJavaSerialization(); - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - - ObjectOutput objectOutput = serialization.serialize(url, byteArrayOutputStream); - objectOutput.writeObject("haha"); - objectOutput.flushBuffer(); - - Object result = client.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{byteArrayOutputStream.toByteArray()}); - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream((byte[]) result); - ObjectInput objectInput = serialization.deserialize(url, byteArrayInputStream); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", objectInput.readObject()); - invoker.destroy(); - exporter.unexport(); - } - - @Test - public void testGenericInvokeWithRpcContext() { - RpcContext.getContext().setAttachment("myContext", "123"); - - HessianServiceImpl server = new HessianServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + HessianService.class.getName() + "?version=1.0.0"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); - Invoker invoker = protocol.refer(GenericService.class, url); - GenericService client = proxyFactory.getProxy(invoker, true); - String result = (String) client.$invoke("context", new String[]{"java.lang.String"}, new Object[]{"haha"}); - Assertions.assertEquals("Hello, haha context, 123", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - public void testGenericInvokeWithBean() { - HessianServiceImpl server = new HessianServiceImpl(); - Assertions.assertFalse(server.isCalled()); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + HessianService.class.getName() + "?version=1.0.0&generic=bean"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); - Invoker invoker = protocol.refer(GenericService.class, url); - GenericService client = proxyFactory.getProxy(invoker); - - JavaBeanDescriptor javaBeanDescriptor = JavaBeanSerializeUtil.serialize("haha"); - - Object result = client.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{javaBeanDescriptor}); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) result)); - invoker.destroy(); - exporter.unexport(); - } - - @Test - public void testOverload() { - HessianServiceImpl server = new HessianServiceImpl(); - Assertions.assertFalse(server.isCalled()); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + HessianService.class.getName() + "?version=1.0.0&hessian.overload.method=true&hessian2.request=false"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); - Invoker invoker = protocol.refer(HessianService.class, url); - HessianService client = proxyFactory.getProxy(invoker); - String result = client.sayHello("haha"); - Assertions.assertEquals("Hello, haha", result); - result = client.sayHello("haha", 1); - Assertions.assertEquals("Hello, haha. ", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - public void testHttpClient() { - HessianServiceImpl server = new HessianServiceImpl(); - Assertions.assertFalse(server.isCalled()); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + HessianService.class.getName() + "?version=1.0.0&client=httpclient&hessian.overload.method=true"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); - Invoker invoker = protocol.refer(HessianService.class, url); - HessianService client = proxyFactory.getProxy(invoker); - String result = client.sayHello("haha"); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - public void testTimeOut() { - HessianServiceImpl server = new HessianServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + HessianService.class.getName() + "?version=1.0.0&timeout=10"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); - Invoker invoker = protocol.refer(HessianService.class, url); - HessianService client = proxyFactory.getProxy(invoker); - try { - client.timeOut(6000); - fail(); - } catch (RpcException expected) { - Assertions.assertTrue(expected.isTimeout()); - } finally { - invoker.destroy(); - exporter.unexport(); - } - - } - - @Test - public void testCustomException() { - HessianServiceImpl server = new HessianServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + HessianService.class.getName() + "?version=1.0.0"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); - Invoker invoker = protocol.refer(HessianService.class, url); - HessianService client = proxyFactory.getProxy(invoker); - try { - client.customException(); - fail(); - } catch (MyException expected) { - - } - invoker.destroy(); - exporter.unexport(); - } - - - @Test - public void testRemoteApplicationName() { - HessianServiceImpl server = new HessianServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("hessian://127.0.0.1:" + port + "/" + HessianService.class.getName() + "?version=1.0.0&hessian.overload.method=true").addParameter("application", "consumer"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HessianService.class, url)); - Invoker invoker = protocol.refer(HessianService.class, url); - HessianService client = proxyFactory.getProxy(invoker); - String result = client.getRemoteApplicationName(); - Assertions.assertEquals("consumer", result); - invoker.destroy(); - exporter.unexport(); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianService.java b/dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianService.java deleted file mode 100644 index 7de8333ebc..0000000000 --- a/dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianService.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.hessian; - - -/** - * HessianService - */ -public interface HessianService { - - String sayHello(String name); - - String sayHello(String name, int times); - - void timeOut(int millis); - - String customException(); - - String context(String name); - - String getRemoteApplicationName(); - -} diff --git a/dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianServiceImpl.java b/dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianServiceImpl.java deleted file mode 100644 index 0440a4cfdb..0000000000 --- a/dubbo-rpc/dubbo-rpc-hessian/src/test/java/org/apache/dubbo/rpc/protocol/hessian/HessianServiceImpl.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.hessian; - -import org.apache.dubbo.rpc.RpcContext; - -/** - * HessianServiceImpl - */ -public class HessianServiceImpl implements HessianService { - - private boolean called; - - public String sayHello(String name) { - called = true; - return "Hello, " + name; - } - - public String sayHello(String name, int times) { - called = true; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < times; i++) { - sb.append("Hello, " + name + ". "); - } - return sb.toString(); - } - - public boolean isCalled() { - return called; - } - - public void timeOut(int millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - public String customException() { - throw new MyException("custom exception"); - } - - public String context(String name) { - return "Hello, " + name + " context, " + RpcContext.getContext().getAttachment("myContext"); - } - - static class MyException extends RuntimeException { - - private static final long serialVersionUID = -3051041116483629056L; - - public MyException(String message) { - super(message); - } - } - - @Override - public String getRemoteApplicationName() { - return RpcContext.getContext().getRemoteApplicationName(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-http/pom.xml b/dubbo-rpc/dubbo-rpc-http/pom.xml deleted file mode 100644 index c6a4338a0d..0000000000 --- a/dubbo-rpc/dubbo-rpc-http/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - - dubbo-rpc - org.apache.dubbo - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-rpc-http - - The JSON-RPC module of dubbo project - - - false - - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-http - ${project.parent.version} - - - org.springframework - spring-context - - - com.github.briandilley.jsonrpc4j - jsonrpc4j - - - javax.portlet - portlet-api - - - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java deleted file mode 100644 index 53d8ab0840..0000000000 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocol.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.http; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingServer; -import org.apache.dubbo.remoting.http.HttpBinder; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.rpc.ProtocolServer; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; - -import com.googlecode.jsonrpc4j.HttpException; -import com.googlecode.jsonrpc4j.JsonRpcClientException; -import com.googlecode.jsonrpc4j.JsonRpcServer; -import com.googlecode.jsonrpc4j.spring.JsonProxyFactoryBean; -import org.apache.dubbo.rpc.service.GenericService; -import org.apache.dubbo.rpc.support.ProtocolUtils; -import org.springframework.remoting.RemoteAccessException; -import org.springframework.remoting.support.RemoteInvocation; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.ArrayList; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; - -public class HttpProtocol extends AbstractProxyProtocol { - public static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER = "Access-Control-Allow-Origin"; - public static final String ACCESS_CONTROL_ALLOW_METHODS_HEADER = "Access-Control-Allow-Methods"; - public static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER = "Access-Control-Allow-Headers"; - - private final Map skeletonMap = new ConcurrentHashMap<>(); - - private HttpBinder httpBinder; - - public HttpProtocol() { - super(HttpException.class, JsonRpcClientException.class); - } - - public void setHttpBinder(HttpBinder httpBinder) { - this.httpBinder = httpBinder; - } - - @Override - public int getDefaultPort() { - return 80; - } - - private class InternalHandler implements HttpHandler { - - private boolean cors; - - public InternalHandler(boolean cors) { - this.cors = cors; - } - - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) - throws ServletException { - String uri = request.getRequestURI(); - JsonRpcServer skeleton = skeletonMap.get(uri); - if (cors) { - response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); - response.setHeader(ACCESS_CONTROL_ALLOW_METHODS_HEADER, "POST"); - response.setHeader(ACCESS_CONTROL_ALLOW_HEADERS_HEADER, "*"); - } - if (request.getMethod().equalsIgnoreCase("OPTIONS")) { - response.setStatus(200); - } else if (request.getMethod().equalsIgnoreCase("POST")) { - - RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); - try { - skeleton.handle(request.getInputStream(), response.getOutputStream()); - } catch (Throwable e) { - throw new ServletException(e); - } - } else { - response.setStatus(500); - } - } - - } - - @Override - protected Runnable doExport(final T impl, Class type, URL url) throws RpcException { - String addr = getAddr(url); - ProtocolServer protocolServer = serverMap.get(addr); - if (protocolServer == null) { - RemotingServer remotingServer = httpBinder.bind(url, new InternalHandler(url.getParameter("cors", false))); - serverMap.put(addr, new ProxyProtocolServer(remotingServer)); - } - final String path = url.getAbsolutePath(); - final String genericPath = path + "/" + GENERIC_KEY; - JsonRpcServer skeleton = new JsonRpcServer(impl, type); - JsonRpcServer genericServer = new JsonRpcServer(impl, GenericService.class); - skeletonMap.put(path, skeleton); - skeletonMap.put(genericPath, genericServer); - return () -> { - skeletonMap.remove(path); - skeletonMap.remove(genericPath); - }; - } - - @SuppressWarnings("unchecked") - @Override - protected T doRefer(final Class serviceType, URL url) throws RpcException { - final String generic = url.getParameter(GENERIC_KEY); - final boolean isGeneric = ProtocolUtils.isGeneric(generic) || serviceType.equals(GenericService.class); - JsonProxyFactoryBean jsonProxyFactoryBean = new JsonProxyFactoryBean(); - JsonRpcProxyFactoryBean jsonRpcProxyFactoryBean = new JsonRpcProxyFactoryBean(jsonProxyFactoryBean); - jsonRpcProxyFactoryBean.setRemoteInvocationFactory((methodInvocation) -> { - RemoteInvocation invocation = new JsonRemoteInvocation(methodInvocation); - if (isGeneric) { - invocation.addAttribute(GENERIC_KEY, generic); - } - return invocation; - }); - String key = url.setProtocol("http").toIdentityString(); - if (isGeneric) { - key = key + "/" + GENERIC_KEY; - } - - jsonRpcProxyFactoryBean.setServiceUrl(key); - jsonRpcProxyFactoryBean.setServiceInterface(serviceType); - - jsonProxyFactoryBean.afterPropertiesSet(); - return (T) jsonProxyFactoryBean.getObject(); - } - - protected int getErrorCode(Throwable e) { - if (e instanceof RemoteAccessException) { - e = e.getCause(); - } - if (e != null) { - Class cls = e.getClass(); - 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; - } - - if (e instanceof HttpProtocolErrorCode) { - return ((HttpProtocolErrorCode) e).getErrorCode(); - } - } - return super.getErrorCode(e); - } - - @Override - public void destroy() { - super.destroy(); - for (String key : new ArrayList<>(serverMap.keySet())) { - ProtocolServer server = serverMap.remove(key); - if (server != null) { - try { - if (logger.isInfoEnabled()) { - logger.info("Close jsonrpc server " + server.getUrl()); - } - server.close(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } - } - } - - -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolErrorCode.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolErrorCode.java deleted file mode 100644 index 6b1610f88c..0000000000 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolErrorCode.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.http; - -/** - * Custom exception error code for http protocol. - */ -public interface HttpProtocolErrorCode { - - /** - * @return custom error code of exception - */ - int getErrorCode(); - -} diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/JsonRemoteInvocation.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/JsonRemoteInvocation.java deleted file mode 100644 index b5437f6d42..0000000000 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/JsonRemoteInvocation.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.http; - -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.rpc.RpcContext; - -import org.aopalliance.intercept.MethodInvocation; -import org.springframework.remoting.support.RemoteInvocation; - -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Map; - -import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; - -/** - * JsonRemoteInvocation - */ -public class JsonRemoteInvocation extends RemoteInvocation { - private static final long serialVersionUID = 1L; - private static final String DUBBO_ATTACHMENTS_ATTR_NAME = "dubbo.attachments"; - - public JsonRemoteInvocation(MethodInvocation methodInvocation) { - super(methodInvocation); - addAttribute(DUBBO_ATTACHMENTS_ATTR_NAME, new HashMap<>(RpcContext.getContext().getAttachments())); - } - - @Override - public Object invoke(Object targetObject) throws NoSuchMethodException, IllegalAccessException, - InvocationTargetException { - RpcContext context = RpcContext.getContext(); - context.setAttachments((Map) getAttribute(DUBBO_ATTACHMENTS_ATTR_NAME)); - - String generic = (String) getAttribute(GENERIC_KEY); - if (StringUtils.isNotEmpty(generic)) { - context.setAttachment(GENERIC_KEY, generic); - } - try { - return super.invoke(targetObject); - } finally { - context.setAttachments(null); - - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/JsonRpcProxyFactoryBean.java b/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/JsonRpcProxyFactoryBean.java deleted file mode 100644 index aff81d298d..0000000000 --- a/dubbo-rpc/dubbo-rpc-http/src/main/java/org/apache/dubbo/rpc/protocol/http/JsonRpcProxyFactoryBean.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.http; - -import com.googlecode.jsonrpc4j.spring.JsonProxyFactoryBean; -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.remoting.support.RemoteInvocationBasedAccessor; - -/** - * JsonRpcProxyFactoryBean - */ -public class JsonRpcProxyFactoryBean extends RemoteInvocationBasedAccessor - implements MethodInterceptor, - InitializingBean, - FactoryBean, - ApplicationContextAware { - private final JsonProxyFactoryBean jsonProxyFactoryBean; - - public JsonRpcProxyFactoryBean(JsonProxyFactoryBean factoryBean) { - this.jsonProxyFactoryBean = factoryBean; - } - - @Override - @SuppressWarnings("unchecked") - public void afterPropertiesSet() { - jsonProxyFactoryBean.afterPropertiesSet(); - } - - @Override - public Object invoke(MethodInvocation invocation) - throws Throwable { - - return jsonProxyFactoryBean.invoke(invocation); - } - - @Override - public Object getObject() { - return jsonProxyFactoryBean.getObject(); - } - - @Override - public Class getObjectType() { - return jsonProxyFactoryBean.getObjectType(); - } - - @Override - public boolean isSingleton() { - return jsonProxyFactoryBean.isSingleton(); - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) { - jsonProxyFactoryBean.setApplicationContext(applicationContext); - } - - @Override - public void setServiceUrl(String serviceUrl) { - jsonProxyFactoryBean.setServiceUrl(serviceUrl); - } - - @Override - public void setServiceInterface(Class serviceInterface) { - jsonProxyFactoryBean.setServiceInterface(serviceInterface); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol deleted file mode 100644 index 46f47ba0dd..0000000000 --- a/dubbo-rpc/dubbo-rpc-http/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -http=org.apache.dubbo.rpc.protocol.http.HttpProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolTest.java b/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolTest.java deleted file mode 100644 index 739f1307f9..0000000000 --- a/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpProtocolTest.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.http; - - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; - -import org.apache.dubbo.rpc.service.GenericService; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class HttpProtocolTest { - - @Test - public void testJsonrpcProtocol() { - HttpServiceImpl server = new HttpServiceImpl(); - assertFalse(server.isCalled()); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("http://127.0.0.1:" + port + "/" + HttpService.class.getName() + "?version=1.0.0"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HttpService.class, url)); - Invoker invoker = protocol.refer(HttpService.class, url); - HttpService client = proxyFactory.getProxy(invoker); - String result = client.sayHello("haha"); - assertTrue(server.isCalled()); - assertEquals("Hello, haha", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - public void testJsonrpcProtocolForServerJetty() { - HttpServiceImpl server = new HttpServiceImpl(); - assertFalse(server.isCalled()); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("http://127.0.0.1:" + port + "/" + HttpService.class.getName() + "?version=1.0.0&server=jetty"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HttpService.class, url)); - Invoker invoker = protocol.refer(HttpService.class, url); - HttpService client = proxyFactory.getProxy(invoker); - String result = client.sayHello("haha"); - assertTrue(server.isCalled()); - assertEquals("Hello, haha", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - public void testGenericInvoke() { - HttpServiceImpl server = new HttpServiceImpl(); - Assertions.assertFalse(server.isCalled()); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("http://127.0.0.1:" + port + "/" + HttpService.class.getName() + "?release=2.7.0"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, HttpService.class, url)); - Invoker invoker = protocol.refer(GenericService.class, url); - GenericService client = proxyFactory.getProxy(invoker, true); - String result = (String) client.$invoke("sayHello", new String[]{"java.lang.String"}, new Object[]{"haha"}); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", result); - invoker.destroy(); - exporter.unexport(); - } - -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpService.java b/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpService.java deleted file mode 100644 index f05994e29f..0000000000 --- a/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpService.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.http; - -public interface HttpService { - String sayHello(String name); - - void timeOut(int millis); - - String customException(); - - String getRemoteApplicationName(); -} diff --git a/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpServiceImpl.java b/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpServiceImpl.java deleted file mode 100644 index 1830aa2e9e..0000000000 --- a/dubbo-rpc/dubbo-rpc-http/src/test/java/org/apache/dubbo/rpc/protocol/http/HttpServiceImpl.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.http; - -import org.apache.dubbo.rpc.RpcContext; - -public class HttpServiceImpl implements HttpService { - private boolean called; - - public String sayHello(String name) { - called = true; - return "Hello, " + name; - } - - public boolean isCalled() { - return called; - } - - public void timeOut(int millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - public String customException() { - throw new MyException("custom exception"); - } - - static class MyException extends RuntimeException{ - - private static final long serialVersionUID = -3051041116483629056L; - - public MyException(String message) { - super(message); - } - } - - @Override - public String getRemoteApplicationName() { - return RpcContext.getContext().getRemoteApplicationName(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-memcached/pom.xml b/dubbo-rpc/dubbo-rpc-memcached/pom.xml deleted file mode 100644 index 1a055206f5..0000000000 --- a/dubbo-rpc/dubbo-rpc-memcached/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-memcached - jar - ${project.artifactId} - The memcached rpc module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - com.googlecode.xmemcached - xmemcached - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java b/dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java deleted file mode 100644 index b056a795ee..0000000000 --- a/dubbo-rpc/dubbo-rpc-memcached/src/main/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocol.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.memcached; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.constants.RemotingConstants; -import org.apache.dubbo.rpc.AsyncRpcResult; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.AbstractInvoker; -import org.apache.dubbo.rpc.protocol.AbstractProtocol; - -import net.rubyeye.xmemcached.MemcachedClient; -import net.rubyeye.xmemcached.MemcachedClientBuilder; -import net.rubyeye.xmemcached.XMemcachedClientBuilder; -import net.rubyeye.xmemcached.exception.MemcachedException; -import net.rubyeye.xmemcached.utils.AddrUtil; - -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.Map; -import java.util.concurrent.TimeoutException; - -/** - * MemcachedProtocol - */ -public class MemcachedProtocol extends AbstractProtocol { - - public static final int DEFAULT_PORT = 11211; - - @Override - public int getDefaultPort() { - return DEFAULT_PORT; - } - - @Override - public Exporter export(final Invoker invoker) throws RpcException { - throw new UnsupportedOperationException("Unsupported export memcached service. url: " + invoker.getUrl()); - } - - @Override - public Invoker protocolBindingRefer(final Class type, final URL url) throws RpcException { - try { - String address = url.getAddress(); - String backup = url.getParameter(RemotingConstants.BACKUP_KEY); - if (backup != null && backup.length() > 0) { - address += "," + backup; - } - MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(address)); - final MemcachedClient memcachedClient = builder.build(); - final int expiry = url.getParameter("expiry", 0); - final String get = url.getParameter("get", "get"); - final String set = url.getParameter("set", Map.class.equals(type) ? "put" : "set"); - final String delete = url.getParameter("delete", Map.class.equals(type) ? "remove" : "delete"); - return new AbstractInvoker(type, url) { - @Override - protected Result doInvoke(Invocation invocation) throws Throwable { - try { - Object value = null; - if (get.equals(invocation.getMethodName())) { - if (invocation.getArguments().length != 1) { - throw new IllegalArgumentException("The memcached get method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); - } - value = memcachedClient.get(String.valueOf(invocation.getArguments()[0])); - } else if (set.equals(invocation.getMethodName())) { - if (invocation.getArguments().length != 2) { - throw new IllegalArgumentException("The memcached set method arguments mismatch, must be two arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); - } - memcachedClient.set(String.valueOf(invocation.getArguments()[0]), expiry, invocation.getArguments()[1]); - } else if (delete.equals(invocation.getMethodName())) { - if (invocation.getArguments().length != 1) { - throw new IllegalArgumentException("The memcached delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); - } - memcachedClient.delete(String.valueOf(invocation.getArguments()[0])); - } else { - throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in memcached service."); - } - return AsyncRpcResult.newDefaultAsyncResult(value, invocation); - } catch (Throwable t) { - RpcException re = new RpcException("Failed to invoke memcached service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t); - if (t instanceof TimeoutException || t instanceof SocketTimeoutException) { - re.setCode(RpcException.TIMEOUT_EXCEPTION); - } else if (t instanceof MemcachedException || t instanceof IOException) { - re.setCode(RpcException.NETWORK_EXCEPTION); - } - throw re; - } - } - - @Override - public void destroy() { - super.destroy(); - try { - memcachedClient.shutdown(); - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - } - } - }; - } catch (Throwable t) { - throw new RpcException("Failed to refer memcached service. interface: " + type.getName() + ", url: " + url + ", cause: " + t.getMessage(), t); - } - } - -} diff --git a/dubbo-rpc/dubbo-rpc-memcached/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-memcached/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol deleted file mode 100644 index 5102c3fe30..0000000000 --- a/dubbo-rpc/dubbo-rpc-memcached/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -memcached=org.apache.dubbo.rpc.protocol.memcached.MemcachedProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-memcached/src/test/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocolTest.java b/dubbo-rpc/dubbo-rpc-memcached/src/test/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocolTest.java deleted file mode 100644 index 4f2a75265f..0000000000 --- a/dubbo-rpc/dubbo-rpc-memcached/src/test/java/org/apache/dubbo/rpc/protocol/memcached/MemcachedProtocolTest.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.memcached; - -public class MemcachedProtocolTest { - -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-native-thrift/pom.xml deleted file mode 100644 index 4aa998c0e7..0000000000 --- a/dubbo-rpc/dubbo-rpc-native-thrift/pom.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-native-thrift - jar - ${project.artifactId} - The thrift rpc module of dubbo project - - false - - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.thrift - libthrift - - - org.apache.dubbo - dubbo-serialization-jdk - ${revision} - test - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java deleted file mode 100644 index 8250151f27..0000000000 --- a/dubbo-rpc/dubbo-rpc-native-thrift/src/main/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocol.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.nativethrift; - - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; - -import org.apache.thrift.TException; -import org.apache.thrift.TMultiplexedProcessor; -import org.apache.thrift.TProcessor; -import org.apache.thrift.protocol.TCompactProtocol; -import org.apache.thrift.protocol.TMultiplexedProtocol; -import org.apache.thrift.protocol.TProtocol; -import org.apache.thrift.server.TServer; -import org.apache.thrift.server.TThreadedSelectorServer; -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TNonblockingServerSocket; -import org.apache.thrift.transport.TSocket; -import org.apache.thrift.transport.TTransport; - -import java.lang.reflect.Constructor; -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Map; - -import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE; - -/** - * native thrift protocol - */ -public class ThriftProtocol extends AbstractProxyProtocol { - - public static final int DEFAULT_PORT = 40880; - - public static final String NAME = "native-thrift"; - public static final String THRIFT_IFACE = "$Iface"; - public static final String THRIFT_PROCESSOR = "$Processor"; - public static final String THRIFT_CLIENT = "$Client"; - - private static final Map SERVER_MAP = new HashMap<>(); - private TMultiplexedProcessor processor = new TMultiplexedProcessor(); - - public ThriftProtocol() { - super(TException.class, RpcException.class); - } - - public ThriftProtocol(Class... exceptions) { - super(exceptions); - } - - @Override - public int getDefaultPort() { - return DEFAULT_PORT; - } - - @Override - protected Runnable doExport(T impl, Class type, URL url) throws RpcException { - return exportThreadedSelectorServer(impl, type, url); - } - - @Override - protected T doRefer(Class type, URL url) throws RpcException { - return doReferFrameAndCompact(type, url); - } - - private Runnable exportThreadedSelectorServer(T impl, Class type, URL url) throws RpcException { - - TThreadedSelectorServer.Args tArgs = null; - String typeName = type.getName(); - - if (typeName.endsWith(THRIFT_IFACE)) { - String processorClsName = typeName.substring(0, typeName.indexOf(THRIFT_IFACE)) + THRIFT_PROCESSOR; - try { - Class clazz = Class.forName(processorClsName); - Constructor constructor = clazz.getConstructor(type); - try { - TProcessor tprocessor = (TProcessor) constructor.newInstance(impl); - processor.registerProcessor(typeName, tprocessor); - - if (SERVER_MAP.get(url.getAddress()) == null) { - - /**Solve the problem of only 50 of the default number of concurrent connections*/ - TNonblockingServerSocket.NonblockingAbstractServerSocketArgs args = new TNonblockingServerSocket.NonblockingAbstractServerSocketArgs(); - /**1000 connections*/ - args.backlog(1000); - - String bindIp = url.getParameter(Constants.BIND_IP_KEY, url.getHost()); - if (url.getParameter(ANYHOST_KEY, false)) { - bindIp = ANYHOST_VALUE; - } - int bindPort = url.getParameter(Constants.BIND_PORT_KEY, url.getPort()); - args.bindAddr(new InetSocketAddress(bindIp, bindPort)); - - /**timeout: 10s */ - args.clientTimeout(10000); - - TNonblockingServerSocket transport = new TNonblockingServerSocket(args); - - tArgs = new TThreadedSelectorServer.Args(transport); - tArgs.workerThreads(200); - tArgs.selectorThreads(4); - tArgs.acceptQueueSizePerThread(256); - tArgs.processor(processor); - tArgs.transportFactory(new TFramedTransport.Factory()); - tArgs.protocolFactory(new TCompactProtocol.Factory()); - } else { - return null; // if server is starting, return and do nothing here - } - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw new RpcException("Fail to create nativethrift server(" + url + ") : " + e.getMessage(), e); - } - } catch (Exception e) { - logger.error(e.getMessage(), e); - throw new RpcException("Fail to create nativethrift server(" + url + ") : " + e.getMessage(), e); - } - } - - if (tArgs == null) { - logger.error("Fail to create nativethrift server(" + url + ") due to null args"); - throw new RpcException("Fail to create nativethrift server(" + url + ") due to null args"); - } - final TServer thriftServer = new TThreadedSelectorServer(tArgs); - SERVER_MAP.put(url.getAddress(), thriftServer); - - new Thread(() -> { - logger.info("Start Thrift ThreadedSelectorServer"); - thriftServer.serve(); - logger.info("Thrift ThreadedSelectorServer started."); - }).start(); - - return () -> { - try { - logger.info("Close Thrift NonblockingServer"); - thriftServer.stop(); - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - } - }; - } - - private T doReferFrameAndCompact(Class type, URL url) throws RpcException { - - try { - T thriftClient = null; - String typeName = type.getName(); - if (typeName.endsWith(THRIFT_IFACE)) { - String clientClsName = typeName.substring(0, typeName.indexOf(THRIFT_IFACE)) + THRIFT_CLIENT; - Class clazz = Class.forName(clientClsName); - Constructor constructor = clazz.getConstructor(TProtocol.class); - try { - TSocket tSocket = new TSocket(url.getHost(), url.getPort()); - TTransport transport = new TFramedTransport(tSocket); - TProtocol tprotocol = new TCompactProtocol(transport); - TMultiplexedProtocol protocol = new TMultiplexedProtocol(tprotocol, typeName); - thriftClient = (T) constructor.newInstance(protocol); - transport.open(); - logger.info("nativethrift 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-native-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-native-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol deleted file mode 100644 index d3b91406aa..0000000000 --- a/dubbo-rpc/dubbo-rpc-native-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -native-thrift=org.apache.dubbo.rpc.protocol.nativethrift.ThriftProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/DemoService.thrift b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/DemoService.thrift deleted file mode 100644 index 12154f8dcf..0000000000 --- a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/DemoService.thrift +++ /dev/null @@ -1,17 +0,0 @@ -namespace java org.apache.dubbo.rpc.protocol.nativethrift -namespace go demo -/*Demo service define file,can be generated to interface files*/ -/*Here test the 7 kind of data type*/ -service DemoService { - string sayHello(1:required string name); - - bool hasName( 1:required bool hasName); - - string sayHelloTimes(1:required string name, 2:required i32 times); - - void timeOut(1:required i32 millis); - - string customException(); - - string context(1:required string name); -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/UserService.thrift b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/UserService.thrift deleted file mode 100644 index c2f18e429a..0000000000 --- a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/idls/UserService.thrift +++ /dev/null @@ -1,6 +0,0 @@ -namespace java org.apache.dubbo.rpc.protocol.nativethrift -namespace go demo - -service UserService { - string find(1:required i32 id); -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoService.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoService.java deleted file mode 100644 index 97572f1c3b..0000000000 --- a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoService.java +++ /dev/null @@ -1,5141 +0,0 @@ - -/** - * Autogenerated by Thrift Compiler (0.11.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - * @generated - */ -package org.apache.dubbo.rpc.protocol.nativethrift; - -@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) -public class DemoService { - - public interface Iface { - - String sayHello(String name) throws org.apache.thrift.TException; - - boolean hasName(boolean hasName) throws org.apache.thrift.TException; - - String sayHelloTimes(String name, int times) throws org.apache.thrift.TException; - - void timeOut(int millis) throws org.apache.thrift.TException; - - String customException() throws org.apache.thrift.TException; - - String context(String name) throws org.apache.thrift.TException; - - } - - public interface AsyncIface { - - void sayHello(String name, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - void hasName(boolean hasName, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - void sayHelloTimes(String name, int times, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - void timeOut(int millis, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - void customException(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - void context(String name, 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 sayHello(String name) throws org.apache.thrift.TException - { - send_sayHello(name); - return recv_sayHello(); - } - - public void send_sayHello(String name) throws org.apache.thrift.TException - { - sayHello_args args = new sayHello_args(); - args.setName(name); - sendBase("sayHello", args); - } - - public String recv_sayHello() throws org.apache.thrift.TException - { - sayHello_result result = new sayHello_result(); - receiveBase(result, "sayHello"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "sayHello failed: unknown result"); - } - - public boolean hasName(boolean hasName) throws org.apache.thrift.TException - { - send_hasName(hasName); - return recv_hasName(); - } - - public void send_hasName(boolean hasName) throws org.apache.thrift.TException - { - hasName_args args = new hasName_args(); - args.setHasName(hasName); - sendBase("hasName", args); - } - - public boolean recv_hasName() throws org.apache.thrift.TException - { - hasName_result result = new hasName_result(); - receiveBase(result, "hasName"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "hasName failed: unknown result"); - } - - public String sayHelloTimes(String name, int times) throws org.apache.thrift.TException - { - send_sayHelloTimes(name, times); - return recv_sayHelloTimes(); - } - - public void send_sayHelloTimes(String name, int times) throws org.apache.thrift.TException - { - sayHelloTimes_args args = new sayHelloTimes_args(); - args.setName(name); - args.setTimes(times); - sendBase("sayHelloTimes", args); - } - - public String recv_sayHelloTimes() throws org.apache.thrift.TException - { - sayHelloTimes_result result = new sayHelloTimes_result(); - receiveBase(result, "sayHelloTimes"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "sayHelloTimes failed: unknown result"); - } - - public void timeOut(int millis) throws org.apache.thrift.TException - { - send_timeOut(millis); - recv_timeOut(); - } - - public void send_timeOut(int millis) throws org.apache.thrift.TException - { - timeOut_args args = new timeOut_args(); - args.setMillis(millis); - sendBase("timeOut", args); - } - - public void recv_timeOut() throws org.apache.thrift.TException - { - timeOut_result result = new timeOut_result(); - receiveBase(result, "timeOut"); - return; - } - - public String customException() throws org.apache.thrift.TException - { - send_customException(); - return recv_customException(); - } - - public void send_customException() throws org.apache.thrift.TException - { - customException_args args = new customException_args(); - sendBase("customException", args); - } - - public String recv_customException() throws org.apache.thrift.TException - { - customException_result result = new customException_result(); - receiveBase(result, "customException"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "customException failed: unknown result"); - } - - public String context(String name) throws org.apache.thrift.TException - { - send_context(name); - return recv_context(); - } - - public void send_context(String name) throws org.apache.thrift.TException - { - context_args args = new context_args(); - args.setName(name); - sendBase("context", args); - } - - public String recv_context() throws org.apache.thrift.TException - { - context_result result = new context_result(); - receiveBase(result, "context"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "context 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 sayHello(String name, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - sayHello_call method_call = new sayHello_call(name, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class sayHello_call extends org.apache.thrift.async.TAsyncMethodCall { - private String name; - public sayHello_call(String name, 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.name = name; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("sayHello", org.apache.thrift.protocol.TMessageType.CALL, 0)); - sayHello_args args = new sayHello_args(); - args.setName(name); - args.write(prot); - prot.writeMessageEnd(); - } - - public String getResult() throws org.apache.thrift.TException { - if (getState() != 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_sayHello(); - } - } - - public void hasName(boolean hasName, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - hasName_call method_call = new hasName_call(hasName, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class hasName_call extends org.apache.thrift.async.TAsyncMethodCall { - private boolean hasName; - public hasName_call(boolean hasName, 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.hasName = hasName; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("hasName", org.apache.thrift.protocol.TMessageType.CALL, 0)); - hasName_args args = new hasName_args(); - args.setHasName(hasName); - args.write(prot); - prot.writeMessageEnd(); - } - - public Boolean getResult() throws org.apache.thrift.TException { - if (getState() != 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_hasName(); - } - } - - public void sayHelloTimes(String name, int times, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - sayHelloTimes_call method_call = new sayHelloTimes_call(name, times, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class sayHelloTimes_call extends org.apache.thrift.async.TAsyncMethodCall { - private String name; - private int times; - public sayHelloTimes_call(String name, int times, 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.name = name; - this.times = times; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("sayHelloTimes", org.apache.thrift.protocol.TMessageType.CALL, 0)); - sayHelloTimes_args args = new sayHelloTimes_args(); - args.setName(name); - args.setTimes(times); - args.write(prot); - prot.writeMessageEnd(); - } - - public String getResult() throws org.apache.thrift.TException { - if (getState() != 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_sayHelloTimes(); - } - } - - public void timeOut(int millis, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - timeOut_call method_call = new timeOut_call(millis, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class timeOut_call extends org.apache.thrift.async.TAsyncMethodCall { - private int millis; - public timeOut_call(int millis, 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.millis = millis; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("timeOut", org.apache.thrift.protocol.TMessageType.CALL, 0)); - timeOut_args args = new timeOut_args(); - args.setMillis(millis); - args.write(prot); - prot.writeMessageEnd(); - } - - public Void getResult() throws org.apache.thrift.TException { - if (getState() != 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 null; - } - } - - public void customException(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - customException_call method_call = new customException_call(resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class customException_call extends org.apache.thrift.async.TAsyncMethodCall { - public customException_call(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); - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("customException", org.apache.thrift.protocol.TMessageType.CALL, 0)); - customException_args args = new customException_args(); - args.write(prot); - prot.writeMessageEnd(); - } - - public String getResult() throws org.apache.thrift.TException { - if (getState() != 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_customException(); - } - } - - public void context(String name, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - context_call method_call = new context_call(name, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class context_call extends org.apache.thrift.async.TAsyncMethodCall { - private String name; - public context_call(String name, 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.name = name; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("context", org.apache.thrift.protocol.TMessageType.CALL, 0)); - context_args args = new context_args(); - args.setName(name); - args.write(prot); - prot.writeMessageEnd(); - } - - public String getResult() throws org.apache.thrift.TException { - if (getState() != 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_context(); - } - } - - } - - public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { - private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName()); - public Processor(I iface) { - super(iface, getProcessMap(new java.util.HashMap>())); - } - - protected Processor(I iface, java.util.Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static java.util.Map> getProcessMap(java.util.Map> processMap) { - processMap.put("sayHello", new sayHello()); - processMap.put("hasName", new hasName()); - processMap.put("sayHelloTimes", new sayHelloTimes()); - processMap.put("timeOut", new timeOut()); - processMap.put("customException", new customException()); - processMap.put("context", new context()); - return processMap; - } - - public static class sayHello extends org.apache.thrift.ProcessFunction { - public sayHello() { - super("sayHello"); - } - - public sayHello_args getEmptyArgsInstance() { - return new sayHello_args(); - } - - protected boolean isOneway() { - return false; - } - - protected boolean handleRuntimeExceptions() { - return false; - } - - public sayHello_result getResult(I iface, sayHello_args args) throws org.apache.thrift.TException { - sayHello_result result = new sayHello_result(); - result.success = iface.sayHello(args.name); - return result; - } - } - - public static class hasName extends org.apache.thrift.ProcessFunction { - public hasName() { - super("hasName"); - } - - public hasName_args getEmptyArgsInstance() { - return new hasName_args(); - } - - protected boolean isOneway() { - return false; - } - - protected boolean handleRuntimeExceptions() { - return false; - } - - public hasName_result getResult(I iface, hasName_args args) throws org.apache.thrift.TException { - hasName_result result = new hasName_result(); - result.success = iface.hasName(args.hasName); - result.setSuccessIsSet(true); - return result; - } - } - - public static class sayHelloTimes extends org.apache.thrift.ProcessFunction { - public sayHelloTimes() { - super("sayHelloTimes"); - } - - public sayHelloTimes_args getEmptyArgsInstance() { - return new sayHelloTimes_args(); - } - - protected boolean isOneway() { - return false; - } - - protected boolean handleRuntimeExceptions() { - return false; - } - - public sayHelloTimes_result getResult(I iface, sayHelloTimes_args args) throws org.apache.thrift.TException { - sayHelloTimes_result result = new sayHelloTimes_result(); - result.success = iface.sayHelloTimes(args.name, args.times); - return result; - } - } - - public static class timeOut extends org.apache.thrift.ProcessFunction { - public timeOut() { - super("timeOut"); - } - - public timeOut_args getEmptyArgsInstance() { - return new timeOut_args(); - } - - protected boolean isOneway() { - return false; - } - - protected boolean handleRuntimeExceptions() { - return false; - } - - public timeOut_result getResult(I iface, timeOut_args args) throws org.apache.thrift.TException { - timeOut_result result = new timeOut_result(); - iface.timeOut(args.millis); - return result; - } - } - - public static class customException extends org.apache.thrift.ProcessFunction { - public customException() { - super("customException"); - } - - public customException_args getEmptyArgsInstance() { - return new customException_args(); - } - - protected boolean isOneway() { - return false; - } - - protected boolean handleRuntimeExceptions() { - return false; - } - - public customException_result getResult(I iface, customException_args args) throws org.apache.thrift.TException { - customException_result result = new customException_result(); - result.success = iface.customException(); - return result; - } - } - - public static class context extends org.apache.thrift.ProcessFunction { - public context() { - super("context"); - } - - public context_args getEmptyArgsInstance() { - return new context_args(); - } - - protected boolean isOneway() { - return false; - } - - protected boolean handleRuntimeExceptions() { - return false; - } - - public context_result getResult(I iface, context_args args) throws org.apache.thrift.TException { - context_result result = new context_result(); - result.success = iface.context(args.name); - return result; - } - } - - } - - public static class AsyncProcessor extends org.apache.thrift.TBaseAsyncProcessor { - private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName()); - public AsyncProcessor(I iface) { - super(iface, getProcessMap(new java.util.HashMap<>())); - } - - protected AsyncProcessor(I iface, java.util.Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static java.util.Map> getProcessMap(java.util.Map> processMap) { - processMap.put("sayHello", new sayHello()); - processMap.put("hasName", new hasName()); - processMap.put("sayHelloTimes", new sayHelloTimes()); - processMap.put("timeOut", new timeOut()); - processMap.put("customException", new customException()); - processMap.put("context", new context()); - return processMap; - } - - public static class sayHello extends org.apache.thrift.AsyncProcessFunction { - public sayHello() { - super("sayHello"); - } - - public sayHello_args getEmptyArgsInstance() { - return new sayHello_args(); - } - - public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { - final org.apache.thrift.AsyncProcessFunction fcall = this; - return new org.apache.thrift.async.AsyncMethodCallback() { - public void onComplete(String o) { - sayHello_result result = new sayHello_result(); - result.success = o; - try { - fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); - } catch (org.apache.thrift.transport.TTransportException e) { - _LOGGER.error("TTransportException writing to internal frame buffer", e); - fb.close(); - } catch (Exception e) { - _LOGGER.error("Exception writing to internal frame buffer", e); - onError(e); - } - } - public void onError(Exception e) { - byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; - org.apache.thrift.TSerializable msg; - sayHello_result result = new sayHello_result(); - if (e instanceof org.apache.thrift.transport.TTransportException) { - _LOGGER.error("TTransportException inside handler", e); - fb.close(); - return; - } else if (e instanceof org.apache.thrift.TApplicationException) { - _LOGGER.error("TApplicationException inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = (org.apache.thrift.TApplicationException)e; - } else { - _LOGGER.error("Exception inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); - } - try { - fcall.sendResponse(fb,msg,msgType,seqid); - } catch (Exception ex) { - _LOGGER.error("Exception writing to internal frame buffer", ex); - fb.close(); - } - } - }; - } - - protected boolean isOneway() { - return false; - } - - public void start(I iface, sayHello_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - iface.sayHello(args.name,resultHandler); - } - } - - public static class hasName extends org.apache.thrift.AsyncProcessFunction { - public hasName() { - super("hasName"); - } - - public hasName_args getEmptyArgsInstance() { - return new hasName_args(); - } - - public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { - final org.apache.thrift.AsyncProcessFunction fcall = this; - return new org.apache.thrift.async.AsyncMethodCallback() { - public void onComplete(Boolean o) { - hasName_result result = new hasName_result(); - result.success = o; - result.setSuccessIsSet(true); - try { - fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); - } catch (org.apache.thrift.transport.TTransportException e) { - _LOGGER.error("TTransportException writing to internal frame buffer", e); - fb.close(); - } catch (Exception e) { - _LOGGER.error("Exception writing to internal frame buffer", e); - onError(e); - } - } - public void onError(Exception e) { - byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; - org.apache.thrift.TSerializable msg; - hasName_result result = new hasName_result(); - if (e instanceof org.apache.thrift.transport.TTransportException) { - _LOGGER.error("TTransportException inside handler", e); - fb.close(); - return; - } else if (e instanceof org.apache.thrift.TApplicationException) { - _LOGGER.error("TApplicationException inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = (org.apache.thrift.TApplicationException)e; - } else { - _LOGGER.error("Exception inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); - } - try { - fcall.sendResponse(fb,msg,msgType,seqid); - } catch (Exception ex) { - _LOGGER.error("Exception writing to internal frame buffer", ex); - fb.close(); - } - } - }; - } - - protected boolean isOneway() { - return false; - } - - public void start(I iface, hasName_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - iface.hasName(args.hasName,resultHandler); - } - } - - public static class sayHelloTimes extends org.apache.thrift.AsyncProcessFunction { - public sayHelloTimes() { - super("sayHelloTimes"); - } - - public sayHelloTimes_args getEmptyArgsInstance() { - return new sayHelloTimes_args(); - } - - public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { - final org.apache.thrift.AsyncProcessFunction fcall = this; - return new org.apache.thrift.async.AsyncMethodCallback() { - public void onComplete(String o) { - sayHelloTimes_result result = new sayHelloTimes_result(); - result.success = o; - try { - fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); - } catch (org.apache.thrift.transport.TTransportException e) { - _LOGGER.error("TTransportException writing to internal frame buffer", e); - fb.close(); - } catch (Exception e) { - _LOGGER.error("Exception writing to internal frame buffer", e); - onError(e); - } - } - public void onError(Exception e) { - byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; - org.apache.thrift.TSerializable msg; - sayHelloTimes_result result = new sayHelloTimes_result(); - if (e instanceof org.apache.thrift.transport.TTransportException) { - _LOGGER.error("TTransportException inside handler", e); - fb.close(); - return; - } else if (e instanceof org.apache.thrift.TApplicationException) { - _LOGGER.error("TApplicationException inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = (org.apache.thrift.TApplicationException)e; - } else { - _LOGGER.error("Exception inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); - } - try { - fcall.sendResponse(fb,msg,msgType,seqid); - } catch (Exception ex) { - _LOGGER.error("Exception writing to internal frame buffer", ex); - fb.close(); - } - } - }; - } - - protected boolean isOneway() { - return false; - } - - public void start(I iface, sayHelloTimes_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - iface.sayHelloTimes(args.name, args.times,resultHandler); - } - } - - public static class timeOut extends org.apache.thrift.AsyncProcessFunction { - public timeOut() { - super("timeOut"); - } - - public timeOut_args getEmptyArgsInstance() { - return new timeOut_args(); - } - - public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { - final org.apache.thrift.AsyncProcessFunction fcall = this; - return new org.apache.thrift.async.AsyncMethodCallback() { - public void onComplete(Void o) { - timeOut_result result = new timeOut_result(); - try { - fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); - } catch (org.apache.thrift.transport.TTransportException e) { - _LOGGER.error("TTransportException writing to internal frame buffer", e); - fb.close(); - } catch (Exception e) { - _LOGGER.error("Exception writing to internal frame buffer", e); - onError(e); - } - } - public void onError(Exception e) { - byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; - org.apache.thrift.TSerializable msg; - timeOut_result result = new timeOut_result(); - if (e instanceof org.apache.thrift.transport.TTransportException) { - _LOGGER.error("TTransportException inside handler", e); - fb.close(); - return; - } else if (e instanceof org.apache.thrift.TApplicationException) { - _LOGGER.error("TApplicationException inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = (org.apache.thrift.TApplicationException)e; - } else { - _LOGGER.error("Exception inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); - } - try { - fcall.sendResponse(fb,msg,msgType,seqid); - } catch (Exception ex) { - _LOGGER.error("Exception writing to internal frame buffer", ex); - fb.close(); - } - } - }; - } - - protected boolean isOneway() { - return false; - } - - public void start(I iface, timeOut_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - iface.timeOut(args.millis,resultHandler); - } - } - - public static class customException extends org.apache.thrift.AsyncProcessFunction { - public customException() { - super("customException"); - } - - public customException_args getEmptyArgsInstance() { - return new customException_args(); - } - - public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { - final org.apache.thrift.AsyncProcessFunction fcall = this; - return new org.apache.thrift.async.AsyncMethodCallback() { - public void onComplete(String o) { - customException_result result = new customException_result(); - result.success = o; - try { - fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); - } catch (org.apache.thrift.transport.TTransportException e) { - _LOGGER.error("TTransportException writing to internal frame buffer", e); - fb.close(); - } catch (Exception e) { - _LOGGER.error("Exception writing to internal frame buffer", e); - onError(e); - } - } - public void onError(Exception e) { - byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; - org.apache.thrift.TSerializable msg; - customException_result result = new customException_result(); - if (e instanceof org.apache.thrift.transport.TTransportException) { - _LOGGER.error("TTransportException inside handler", e); - fb.close(); - return; - } else if (e instanceof org.apache.thrift.TApplicationException) { - _LOGGER.error("TApplicationException inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = (org.apache.thrift.TApplicationException)e; - } else { - _LOGGER.error("Exception inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); - } - try { - fcall.sendResponse(fb,msg,msgType,seqid); - } catch (Exception ex) { - _LOGGER.error("Exception writing to internal frame buffer", ex); - fb.close(); - } - } - }; - } - - protected boolean isOneway() { - return false; - } - - public void start(I iface, customException_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - iface.customException(resultHandler); - } - } - - public static class context extends org.apache.thrift.AsyncProcessFunction { - public context() { - super("context"); - } - - public context_args getEmptyArgsInstance() { - return new context_args(); - } - - public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { - final org.apache.thrift.AsyncProcessFunction fcall = this; - return new org.apache.thrift.async.AsyncMethodCallback() { - public void onComplete(String o) { - context_result result = new context_result(); - result.success = o; - try { - fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); - } catch (org.apache.thrift.transport.TTransportException e) { - _LOGGER.error("TTransportException writing to internal frame buffer", e); - fb.close(); - } catch (Exception e) { - _LOGGER.error("Exception writing to internal frame buffer", e); - onError(e); - } - } - public void onError(Exception e) { - byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; - org.apache.thrift.TSerializable msg; - context_result result = new context_result(); - if (e instanceof org.apache.thrift.transport.TTransportException) { - _LOGGER.error("TTransportException inside handler", e); - fb.close(); - return; - } else if (e instanceof org.apache.thrift.TApplicationException) { - _LOGGER.error("TApplicationException inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = (org.apache.thrift.TApplicationException)e; - } else { - _LOGGER.error("Exception inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); - } - try { - fcall.sendResponse(fb,msg,msgType,seqid); - } catch (Exception ex) { - _LOGGER.error("Exception writing to internal frame buffer", ex); - fb.close(); - } - } - }; - } - - protected boolean isOneway() { - return false; - } - - public void start(I iface, context_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - iface.context(args.name,resultHandler); - } - } - - } - - public static class sayHello_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHello_args"); - - private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new sayHello_argsStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new sayHello_argsTupleSchemeFactory(); - - public String name; // 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 { - NAME((short)1, "name"); - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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: // NAME - return NAME; - 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 java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHello_args.class, metaDataMap); - } - - public sayHello_args() { - } - - public sayHello_args( - String name) - { - this(); - this.name = name; - } - - /** - * Performs a deep copy on other. - */ - public sayHello_args(sayHello_args other) { - if (other.isSetName()) { - this.name = other.name; - } - } - - public sayHello_args deepCopy() { - return new sayHello_args(this); - } - - @Override - public void clear() { - this.name = null; - } - - public String getName() { - return this.name; - } - - public sayHello_args setName(String name) { - this.name = name; - return this; - } - - public void unsetName() { - this.name = null; - } - - /** Returns true if field name is set (has been assigned a value) and false otherwise */ - public boolean isSetName() { - return this.name != null; - } - - public void setNameIsSet(boolean value) { - if (!value) { - this.name = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case NAME: - if (value == null) { - unsetName(); - } else { - setName((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case NAME: - return getName(); - - } - 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 NAME: - return isSetName(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof sayHello_args) - return this.equals((sayHello_args)that); - return false; - } - - public boolean equals(sayHello_args that) { - if (that == null) - return false; - if (this == that) - return true; - - boolean this_present_name = true && this.isSetName(); - boolean that_present_name = true && that.isSetName(); - if (this_present_name || that_present_name) { - if (!(this_present_name && that_present_name)) - return false; - if (!this.name.equals(that.name)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287); - if (isSetName()) - hashCode = hashCode * 8191 + name.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(sayHello_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetName()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); - 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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("sayHello_args("); - boolean first = true; - - sb.append("name:"); - if (this.name == null) { - sb.append("null"); - } else { - sb.append(this.name); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (name == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'name' was not present! Struct: " + toString()); - } - // check for sub-struct validity - } - - 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); - } - } - - private static class sayHello_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public sayHello_argsStandardScheme getScheme() { - return new sayHello_argsStandardScheme(); - } - } - - private static class sayHello_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, sayHello_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 1: // NAME - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.name = iprot.readString(); - struct.setNameIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, sayHello_args struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.name != null) { - oprot.writeFieldBegin(NAME_FIELD_DESC); - oprot.writeString(struct.name); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class sayHello_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public sayHello_argsTupleScheme getScheme() { - return new sayHello_argsTupleScheme(); - } - } - - private static class sayHello_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - oprot.writeString(struct.name); - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, sayHello_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - struct.name = iprot.readString(); - struct.setNameIsSet(true); - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class sayHello_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHello_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); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new sayHello_resultStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new sayHello_resultTupleSchemeFactory(); - - 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 java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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 java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.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 = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHello_result.class, metaDataMap); - } - - public sayHello_result() { - } - - public sayHello_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public sayHello_result(sayHello_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public sayHello_result deepCopy() { - return new sayHello_result(this); - } - - @Override - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public sayHello_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 sayHello_result) - return this.equals((sayHello_result)that); - return false; - } - - public boolean equals(sayHello_result that) { - if (that == null) - return false; - if (this == that) - return true; - - 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() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); - if (isSetSuccess()) - hashCode = hashCode * 8191 + success.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(sayHello_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("sayHello_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 - // check for sub-struct validity - } - - 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); - } - } - - private static class sayHello_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public sayHello_resultStandardScheme getScheme() { - return new sayHello_resultStandardScheme(); - } - } - - private static class sayHello_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, sayHello_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 0: // SUCCESS - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, sayHello_result struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.success != null) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(struct.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class sayHello_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public sayHello_resultTupleScheme getScheme() { - return new sayHello_resultTupleScheme(); - } - } - - private static class sayHello_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, sayHello_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet optionals = new java.util.BitSet(); - if (struct.isSetSuccess()) { - optionals.set(0); - } - oprot.writeBitSet(optionals, 1); - if (struct.isSetSuccess()) { - oprot.writeString(struct.success); - } - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, sayHello_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet incoming = iprot.readBitSet(1); - if (incoming.get(0)) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class hasName_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("hasName_args"); - - private static final org.apache.thrift.protocol.TField HAS_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("hasName", org.apache.thrift.protocol.TType.BOOL, (short)1); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new hasName_argsStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new hasName_argsTupleSchemeFactory(); - - public boolean hasName; // 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 { - HAS_NAME((short)1, "hasName"); - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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: // HAS_NAME - return HAS_NAME; - 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 __HASNAME_ISSET_ID = 0; - private byte __isset_bitfield = 0; - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.HAS_NAME, new org.apache.thrift.meta_data.FieldMetaData("hasName", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL))); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(hasName_args.class, metaDataMap); - } - - public hasName_args() { - } - - public hasName_args( - boolean hasName) - { - this(); - this.hasName = hasName; - setHasNameIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public hasName_args(hasName_args other) { - __isset_bitfield = other.__isset_bitfield; - this.hasName = other.hasName; - } - - public hasName_args deepCopy() { - return new hasName_args(this); - } - - @Override - public void clear() { - setHasNameIsSet(false); - this.hasName = false; - } - - public boolean isHasName() { - return this.hasName; - } - - public hasName_args setHasName(boolean hasName) { - this.hasName = hasName; - setHasNameIsSet(true); - return this; - } - - public void unsetHasName() { - __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __HASNAME_ISSET_ID); - } - - /** Returns true if field hasName is set (has been assigned a value) and false otherwise */ - public boolean isSetHasName() { - return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __HASNAME_ISSET_ID); - } - - public void setHasNameIsSet(boolean value) { - __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __HASNAME_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case HAS_NAME: - if (value == null) { - unsetHasName(); - } else { - setHasName((Boolean)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case HAS_NAME: - return isHasName(); - - } - 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 HAS_NAME: - return isSetHasName(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof hasName_args) - return this.equals((hasName_args)that); - return false; - } - - public boolean equals(hasName_args that) { - if (that == null) - return false; - if (this == that) - return true; - - boolean this_present_hasName = true; - boolean that_present_hasName = true; - if (this_present_hasName || that_present_hasName) { - if (!(this_present_hasName && that_present_hasName)) - return false; - if (this.hasName != that.hasName) - return false; - } - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((hasName) ? 131071 : 524287); - - return hashCode; - } - - @Override - public int compareTo(hasName_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetHasName()).compareTo(other.isSetHasName()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetHasName()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.hasName, other.hasName); - 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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("hasName_args("); - boolean first = true; - - sb.append("hasName:"); - sb.append(this.hasName); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'hasName' because it's a primitive and you chose the non-beans generator. - // check for sub-struct validity - } - - 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_bitfield = 0; - 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); - } - } - - private static class hasName_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public hasName_argsStandardScheme getScheme() { - return new hasName_argsStandardScheme(); - } - } - - private static class hasName_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, hasName_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 1: // HAS_NAME - if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { - struct.hasName = iprot.readBool(); - struct.setHasNameIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!struct.isSetHasName()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'hasName' was not found in serialized data! Struct: " + toString()); - } - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, hasName_args struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(HAS_NAME_FIELD_DESC); - oprot.writeBool(struct.hasName); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class hasName_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public hasName_argsTupleScheme getScheme() { - return new hasName_argsTupleScheme(); - } - } - - private static class hasName_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, hasName_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - oprot.writeBool(struct.hasName); - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, hasName_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - struct.hasName = iprot.readBool(); - struct.setHasNameIsSet(true); - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class hasName_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("hasName_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); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new hasName_resultStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new hasName_resultTupleSchemeFactory(); - - 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 java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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 byte __isset_bitfield = 0; - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.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 = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(hasName_result.class, metaDataMap); - } - - public hasName_result() { - } - - public hasName_result( - boolean success) - { - this(); - this.success = success; - setSuccessIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public hasName_result(hasName_result other) { - __isset_bitfield = other.__isset_bitfield; - this.success = other.success; - } - - public hasName_result deepCopy() { - return new hasName_result(this); - } - - @Override - public void clear() { - setSuccessIsSet(false); - this.success = false; - } - - public boolean isSuccess() { - return this.success; - } - - public hasName_result setSuccess(boolean success) { - this.success = success; - setSuccessIsSet(true); - return this; - } - - public void unsetSuccess() { - __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID); - } - - /** Returns true if field success is set (has been assigned a value) and false otherwise */ - public boolean isSetSuccess() { - return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID); - } - - public void setSuccessIsSet(boolean value) { - __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __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 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(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof hasName_result) - return this.equals((hasName_result)that); - return false; - } - - public boolean equals(hasName_result that) { - if (that == null) - return false; - if (this == that) - return true; - - 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; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((success) ? 131071 : 524287); - - return hashCode; - } - - @Override - public int compareTo(hasName_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("hasName_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 - // check for sub-struct validity - } - - 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_bitfield = 0; - 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); - } - } - - private static class hasName_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public hasName_resultStandardScheme getScheme() { - return new hasName_resultStandardScheme(); - } - } - - private static class hasName_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, hasName_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 0: // SUCCESS - if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) { - struct.success = iprot.readBool(); - struct.setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, hasName_result struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.isSetSuccess()) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeBool(struct.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class hasName_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public hasName_resultTupleScheme getScheme() { - return new hasName_resultTupleScheme(); - } - } - - private static class hasName_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, hasName_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet optionals = new java.util.BitSet(); - if (struct.isSetSuccess()) { - optionals.set(0); - } - oprot.writeBitSet(optionals, 1); - if (struct.isSetSuccess()) { - oprot.writeBool(struct.success); - } - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, hasName_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet incoming = iprot.readBitSet(1); - if (incoming.get(0)) { - struct.success = iprot.readBool(); - struct.setSuccessIsSet(true); - } - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class sayHelloTimes_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHelloTimes_args"); - - private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1); - private static final org.apache.thrift.protocol.TField TIMES_FIELD_DESC = new org.apache.thrift.protocol.TField("times", org.apache.thrift.protocol.TType.I32, (short)2); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new sayHelloTimes_argsStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new sayHelloTimes_argsTupleSchemeFactory(); - - public String name; // required - public int times; // 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 { - NAME((short)1, "name"), - TIMES((short)2, "times"); - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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: // NAME - return NAME; - case 2: // TIMES - return TIMES; - 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 __TIMES_ISSET_ID = 0; - private byte __isset_bitfield = 0; - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - tmpMap.put(_Fields.TIMES, new org.apache.thrift.meta_data.FieldMetaData("times", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHelloTimes_args.class, metaDataMap); - } - - public sayHelloTimes_args() { - } - - public sayHelloTimes_args( - String name, - int times) - { - this(); - this.name = name; - this.times = times; - setTimesIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public sayHelloTimes_args(sayHelloTimes_args other) { - __isset_bitfield = other.__isset_bitfield; - if (other.isSetName()) { - this.name = other.name; - } - this.times = other.times; - } - - public sayHelloTimes_args deepCopy() { - return new sayHelloTimes_args(this); - } - - @Override - public void clear() { - this.name = null; - setTimesIsSet(false); - this.times = 0; - } - - public String getName() { - return this.name; - } - - public sayHelloTimes_args setName(String name) { - this.name = name; - return this; - } - - public void unsetName() { - this.name = null; - } - - /** Returns true if field name is set (has been assigned a value) and false otherwise */ - public boolean isSetName() { - return this.name != null; - } - - public void setNameIsSet(boolean value) { - if (!value) { - this.name = null; - } - } - - public int getTimes() { - return this.times; - } - - public sayHelloTimes_args setTimes(int times) { - this.times = times; - setTimesIsSet(true); - return this; - } - - public void unsetTimes() { - __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __TIMES_ISSET_ID); - } - - /** Returns true if field times is set (has been assigned a value) and false otherwise */ - public boolean isSetTimes() { - return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __TIMES_ISSET_ID); - } - - public void setTimesIsSet(boolean value) { - __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __TIMES_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case NAME: - if (value == null) { - unsetName(); - } else { - setName((String)value); - } - break; - - case TIMES: - if (value == null) { - unsetTimes(); - } else { - setTimes((Integer)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case NAME: - return getName(); - - case TIMES: - return getTimes(); - - } - 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 NAME: - return isSetName(); - case TIMES: - return isSetTimes(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof sayHelloTimes_args) - return this.equals((sayHelloTimes_args)that); - return false; - } - - public boolean equals(sayHelloTimes_args that) { - if (that == null) - return false; - if (this == that) - return true; - - boolean this_present_name = true && this.isSetName(); - boolean that_present_name = true && that.isSetName(); - if (this_present_name || that_present_name) { - if (!(this_present_name && that_present_name)) - return false; - if (!this.name.equals(that.name)) - return false; - } - - boolean this_present_times = true; - boolean that_present_times = true; - if (this_present_times || that_present_times) { - if (!(this_present_times && that_present_times)) - return false; - if (this.times != that.times) - return false; - } - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287); - if (isSetName()) - hashCode = hashCode * 8191 + name.hashCode(); - - hashCode = hashCode * 8191 + times; - - return hashCode; - } - - @Override - public int compareTo(sayHelloTimes_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetName()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); - if (lastComparison != 0) { - return lastComparison; - } - } - lastComparison = Boolean.valueOf(isSetTimes()).compareTo(other.isSetTimes()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetTimes()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.times, other.times); - 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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("sayHelloTimes_args("); - boolean first = true; - - sb.append("name:"); - if (this.name == null) { - sb.append("null"); - } else { - sb.append(this.name); - } - first = false; - if (!first) sb.append(", "); - sb.append("times:"); - sb.append(this.times); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (name == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'name' was not present! Struct: " + toString()); - } - // alas, we cannot check 'times' because it's a primitive and you chose the non-beans generator. - // check for sub-struct validity - } - - 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_bitfield = 0; - 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); - } - } - - private static class sayHelloTimes_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public sayHelloTimes_argsStandardScheme getScheme() { - return new sayHelloTimes_argsStandardScheme(); - } - } - - private static class sayHelloTimes_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, sayHelloTimes_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 1: // NAME - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.name = iprot.readString(); - struct.setNameIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - case 2: // TIMES - if (schemeField.type == org.apache.thrift.protocol.TType.I32) { - struct.times = iprot.readI32(); - struct.setTimesIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!struct.isSetTimes()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'times' was not found in serialized data! Struct: " + toString()); - } - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, sayHelloTimes_args struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.name != null) { - oprot.writeFieldBegin(NAME_FIELD_DESC); - oprot.writeString(struct.name); - oprot.writeFieldEnd(); - } - oprot.writeFieldBegin(TIMES_FIELD_DESC); - oprot.writeI32(struct.times); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class sayHelloTimes_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public sayHelloTimes_argsTupleScheme getScheme() { - return new sayHelloTimes_argsTupleScheme(); - } - } - - private static class sayHelloTimes_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, sayHelloTimes_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - oprot.writeString(struct.name); - oprot.writeI32(struct.times); - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, sayHelloTimes_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - struct.name = iprot.readString(); - struct.setNameIsSet(true); - struct.times = iprot.readI32(); - struct.setTimesIsSet(true); - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class sayHelloTimes_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("sayHelloTimes_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); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new sayHelloTimes_resultStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new sayHelloTimes_resultTupleSchemeFactory(); - - 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 java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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 java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.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 = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(sayHelloTimes_result.class, metaDataMap); - } - - public sayHelloTimes_result() { - } - - public sayHelloTimes_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public sayHelloTimes_result(sayHelloTimes_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public sayHelloTimes_result deepCopy() { - return new sayHelloTimes_result(this); - } - - @Override - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public sayHelloTimes_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 sayHelloTimes_result) - return this.equals((sayHelloTimes_result)that); - return false; - } - - public boolean equals(sayHelloTimes_result that) { - if (that == null) - return false; - if (this == that) - return true; - - 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() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); - if (isSetSuccess()) - hashCode = hashCode * 8191 + success.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(sayHelloTimes_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("sayHelloTimes_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 - // check for sub-struct validity - } - - 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); - } - } - - private static class sayHelloTimes_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public sayHelloTimes_resultStandardScheme getScheme() { - return new sayHelloTimes_resultStandardScheme(); - } - } - - private static class sayHelloTimes_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, sayHelloTimes_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 0: // SUCCESS - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, sayHelloTimes_result struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.success != null) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(struct.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class sayHelloTimes_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public sayHelloTimes_resultTupleScheme getScheme() { - return new sayHelloTimes_resultTupleScheme(); - } - } - - private static class sayHelloTimes_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, sayHelloTimes_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet optionals = new java.util.BitSet(); - if (struct.isSetSuccess()) { - optionals.set(0); - } - oprot.writeBitSet(optionals, 1); - if (struct.isSetSuccess()) { - oprot.writeString(struct.success); - } - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, sayHelloTimes_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet incoming = iprot.readBitSet(1); - if (incoming.get(0)) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class timeOut_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("timeOut_args"); - - private static final org.apache.thrift.protocol.TField MILLIS_FIELD_DESC = new org.apache.thrift.protocol.TField("millis", org.apache.thrift.protocol.TType.I32, (short)1); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new timeOut_argsStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new timeOut_argsTupleSchemeFactory(); - - public int millis; // 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 { - MILLIS((short)1, "millis"); - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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: // MILLIS - return MILLIS; - 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 __MILLIS_ISSET_ID = 0; - private byte __isset_bitfield = 0; - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.MILLIS, new org.apache.thrift.meta_data.FieldMetaData("millis", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(timeOut_args.class, metaDataMap); - } - - public timeOut_args() { - } - - public timeOut_args( - int millis) - { - this(); - this.millis = millis; - setMillisIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public timeOut_args(timeOut_args other) { - __isset_bitfield = other.__isset_bitfield; - this.millis = other.millis; - } - - public timeOut_args deepCopy() { - return new timeOut_args(this); - } - - @Override - public void clear() { - setMillisIsSet(false); - this.millis = 0; - } - - public int getMillis() { - return this.millis; - } - - public timeOut_args setMillis(int millis) { - this.millis = millis; - setMillisIsSet(true); - return this; - } - - public void unsetMillis() { - __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __MILLIS_ISSET_ID); - } - - /** Returns true if field millis is set (has been assigned a value) and false otherwise */ - public boolean isSetMillis() { - return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __MILLIS_ISSET_ID); - } - - public void setMillisIsSet(boolean value) { - __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __MILLIS_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case MILLIS: - if (value == null) { - unsetMillis(); - } else { - setMillis((Integer)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case MILLIS: - return getMillis(); - - } - 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 MILLIS: - return isSetMillis(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof timeOut_args) - return this.equals((timeOut_args)that); - return false; - } - - public boolean equals(timeOut_args that) { - if (that == null) - return false; - if (this == that) - return true; - - boolean this_present_millis = true; - boolean that_present_millis = true; - if (this_present_millis || that_present_millis) { - if (!(this_present_millis && that_present_millis)) - return false; - if (this.millis != that.millis) - return false; - } - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + millis; - - return hashCode; - } - - @Override - public int compareTo(timeOut_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetMillis()).compareTo(other.isSetMillis()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetMillis()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.millis, other.millis); - 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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("timeOut_args("); - boolean first = true; - - sb.append("millis:"); - sb.append(this.millis); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'millis' because it's a primitive and you chose the non-beans generator. - // check for sub-struct validity - } - - 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_bitfield = 0; - 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); - } - } - - private static class timeOut_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public timeOut_argsStandardScheme getScheme() { - return new timeOut_argsStandardScheme(); - } - } - - private static class timeOut_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, timeOut_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 1: // MILLIS - if (schemeField.type == org.apache.thrift.protocol.TType.I32) { - struct.millis = iprot.readI32(); - struct.setMillisIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!struct.isSetMillis()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'millis' was not found in serialized data! Struct: " + toString()); - } - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, timeOut_args struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(MILLIS_FIELD_DESC); - oprot.writeI32(struct.millis); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class timeOut_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public timeOut_argsTupleScheme getScheme() { - return new timeOut_argsTupleScheme(); - } - } - - private static class timeOut_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, timeOut_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - oprot.writeI32(struct.millis); - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, timeOut_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - struct.millis = iprot.readI32(); - struct.setMillisIsSet(true); - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class timeOut_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("timeOut_result"); - - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new timeOut_resultStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new timeOut_resultTupleSchemeFactory(); - - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ; - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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) { - 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; - } - } - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(timeOut_result.class, metaDataMap); - } - - public timeOut_result() { - } - - /** - * Performs a deep copy on other. - */ - public timeOut_result(timeOut_result other) { - } - - public timeOut_result deepCopy() { - return new timeOut_result(this); - } - - @Override - public void clear() { - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - } - 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) { - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof timeOut_result) - return this.equals((timeOut_result)that); - return false; - } - - public boolean equals(timeOut_result that) { - if (that == null) - return false; - if (this == that) - return true; - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - return hashCode; - } - - @Override - public int compareTo(timeOut_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - 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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("timeOut_result("); - boolean first = true; - - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // check for sub-struct validity - } - - 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); - } - } - - private static class timeOut_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public timeOut_resultStandardScheme getScheme() { - return new timeOut_resultStandardScheme(); - } - } - - private static class timeOut_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, timeOut_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, timeOut_result struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class timeOut_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public timeOut_resultTupleScheme getScheme() { - return new timeOut_resultTupleScheme(); - } - } - - private static class timeOut_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, timeOut_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, timeOut_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class customException_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("customException_args"); - - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new customException_argsStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new customException_argsTupleSchemeFactory(); - - - /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ - public enum _Fields implements org.apache.thrift.TFieldIdEnum { - ; - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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) { - 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; - } - } - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(customException_args.class, metaDataMap); - } - - public customException_args() { - } - - /** - * Performs a deep copy on other. - */ - public customException_args(customException_args other) { - } - - public customException_args deepCopy() { - return new customException_args(this); - } - - @Override - public void clear() { - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - } - 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) { - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof customException_args) - return this.equals((customException_args)that); - return false; - } - - public boolean equals(customException_args that) { - if (that == null) - return false; - if (this == that) - return true; - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - return hashCode; - } - - @Override - public int compareTo(customException_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - 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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("customException_args("); - boolean first = true; - - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // check for sub-struct validity - } - - 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); - } - } - - private static class customException_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public customException_argsStandardScheme getScheme() { - return new customException_argsStandardScheme(); - } - } - - private static class customException_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, customException_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, customException_args struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class customException_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public customException_argsTupleScheme getScheme() { - return new customException_argsTupleScheme(); - } - } - - private static class customException_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, customException_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, customException_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class customException_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("customException_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); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new customException_resultStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new customException_resultTupleSchemeFactory(); - - 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 java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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 java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.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 = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(customException_result.class, metaDataMap); - } - - public customException_result() { - } - - public customException_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public customException_result(customException_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public customException_result deepCopy() { - return new customException_result(this); - } - - @Override - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public customException_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 customException_result) - return this.equals((customException_result)that); - return false; - } - - public boolean equals(customException_result that) { - if (that == null) - return false; - if (this == that) - return true; - - 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() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); - if (isSetSuccess()) - hashCode = hashCode * 8191 + success.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(customException_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("customException_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 - // check for sub-struct validity - } - - 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); - } - } - - private static class customException_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public customException_resultStandardScheme getScheme() { - return new customException_resultStandardScheme(); - } - } - - private static class customException_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, customException_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 0: // SUCCESS - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, customException_result struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.success != null) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(struct.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class customException_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public customException_resultTupleScheme getScheme() { - return new customException_resultTupleScheme(); - } - } - - private static class customException_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, customException_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet optionals = new java.util.BitSet(); - if (struct.isSetSuccess()) { - optionals.set(0); - } - oprot.writeBitSet(optionals, 1); - if (struct.isSetSuccess()) { - oprot.writeString(struct.success); - } - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, customException_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet incoming = iprot.readBitSet(1); - if (incoming.get(0)) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class context_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("context_args"); - - private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new context_argsStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new context_argsTupleSchemeFactory(); - - public String name; // 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 { - NAME((short)1, "name"); - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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: // NAME - return NAME; - 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 java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(context_args.class, metaDataMap); - } - - public context_args() { - } - - public context_args( - String name) - { - this(); - this.name = name; - } - - /** - * Performs a deep copy on other. - */ - public context_args(context_args other) { - if (other.isSetName()) { - this.name = other.name; - } - } - - public context_args deepCopy() { - return new context_args(this); - } - - @Override - public void clear() { - this.name = null; - } - - public String getName() { - return this.name; - } - - public context_args setName(String name) { - this.name = name; - return this; - } - - public void unsetName() { - this.name = null; - } - - /** Returns true if field name is set (has been assigned a value) and false otherwise */ - public boolean isSetName() { - return this.name != null; - } - - public void setNameIsSet(boolean value) { - if (!value) { - this.name = null; - } - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case NAME: - if (value == null) { - unsetName(); - } else { - setName((String)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case NAME: - return getName(); - - } - 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 NAME: - return isSetName(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof context_args) - return this.equals((context_args)that); - return false; - } - - public boolean equals(context_args that) { - if (that == null) - return false; - if (this == that) - return true; - - boolean this_present_name = true && this.isSetName(); - boolean that_present_name = true && that.isSetName(); - if (this_present_name || that_present_name) { - if (!(this_present_name && that_present_name)) - return false; - if (!this.name.equals(that.name)) - return false; - } - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetName()) ? 131071 : 524287); - if (isSetName()) - hashCode = hashCode * 8191 + name.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(context_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetName()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name); - 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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("context_args("); - boolean first = true; - - sb.append("name:"); - if (this.name == null) { - sb.append("null"); - } else { - sb.append(this.name); - } - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - if (name == null) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'name' was not present! Struct: " + toString()); - } - // check for sub-struct validity - } - - 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); - } - } - - private static class context_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public context_argsStandardScheme getScheme() { - return new context_argsStandardScheme(); - } - } - - private static class context_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, context_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 1: // NAME - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.name = iprot.readString(); - struct.setNameIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, context_args struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.name != null) { - oprot.writeFieldBegin(NAME_FIELD_DESC); - oprot.writeString(struct.name); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class context_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public context_argsTupleScheme getScheme() { - return new context_argsTupleScheme(); - } - } - - private static class context_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, context_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - oprot.writeString(struct.name); - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, context_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - struct.name = iprot.readString(); - struct.setNameIsSet(true); - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class context_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("context_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); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new context_resultStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new context_resultTupleSchemeFactory(); - - 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 java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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 java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.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 = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(context_result.class, metaDataMap); - } - - public context_result() { - } - - public context_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public context_result(context_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public context_result deepCopy() { - return new context_result(this); - } - - @Override - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public context_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 context_result) - return this.equals((context_result)that); - return false; - } - - public boolean equals(context_result that) { - if (that == null) - return false; - if (this == that) - return true; - - 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() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); - if (isSetSuccess()) - hashCode = hashCode * 8191 + success.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(context_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("context_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 - // check for sub-struct validity - } - - 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); - } - } - - private static class context_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public context_resultStandardScheme getScheme() { - return new context_resultStandardScheme(); - } - } - - private static class context_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, context_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 0: // SUCCESS - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, context_result struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.success != null) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(struct.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class context_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public context_resultTupleScheme getScheme() { - return new context_resultTupleScheme(); - } - } - - private static class context_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, context_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet optionals = new java.util.BitSet(); - if (struct.isSetSuccess()) { - optionals.set(0); - } - oprot.writeBitSet(optionals, 1); - if (struct.isSetSuccess()) { - oprot.writeString(struct.success); - } - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, context_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet incoming = iprot.readBitSet(1); - if (incoming.get(0)) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - -} diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoServiceImpl.java deleted file mode 100644 index 37876742c2..0000000000 --- a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/DemoServiceImpl.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.nativethrift; - - -import org.apache.dubbo.rpc.RpcContext; -import org.apache.thrift.TException; - -public class DemoServiceImpl implements DemoService.Iface { - private boolean called; - - public String sayHello(String name) { - called = true; - return "Hello, " + name; - } - - @Override - public boolean hasName(boolean hasName) throws TException { - return hasName; - } - - @Override - public String sayHelloTimes(String name, int times) throws TException { - return null; - } - - public String sayHello(String name, int times) { - called = true; - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < times; i++) { - sb.append("Hello, " + name + ". "); - } - return sb.toString(); - } - - public boolean isCalled() { - return called; - } - - public void timeOut(int millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - public String customException() { - throw new MyException("custom exception"); - } - - public String context(String name) { - return "Hello, " + name + " context, " + RpcContext.getContext().getAttachment("myContext"); - } - - static class MyException extends RuntimeException { - - private static final long serialVersionUID = -3051041116483629056L; - - public MyException(String message) { - super(message); - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocolTest.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocolTest.java deleted file mode 100644 index 4663370135..0000000000 --- a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/ThriftProtocolTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.nativethrift; - - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.thrift.TException; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - - -/** - * ThriftProtocolTest - */ -public class ThriftProtocolTest { - - @Test - public void testThriftProtocol() throws TException { - DemoServiceImpl server = new DemoServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf(org.apache.dubbo.rpc.protocol.nativethrift.ThriftProtocol.NAME + "://127.0.0.1:" + port + "/" + DemoService.Iface.class.getName() + "?version=1.0.0&nativethrift.overload.method=true"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, DemoService.Iface.class, url)); - Invoker invoker = protocol.refer(DemoService.Iface.class, url); - DemoService.Iface client = proxyFactory.getProxy(invoker); - String result = client.sayHello("haha"); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - public void testThriftProtocolMultipleServices() throws TException { - - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - - DemoServiceImpl server1 = new DemoServiceImpl(); - int port = NetUtils.getAvailablePort(); - URL url1 = URL.valueOf(org.apache.dubbo.rpc.protocol.nativethrift.ThriftProtocol.NAME + "://127.0.0.1:" + port + "/" + DemoService.Iface.class.getName() + "?version=1.0.0&nativethrift.overload.method=true"); - Exporter exporter1 = protocol.export(proxyFactory.getInvoker(server1, DemoService.Iface.class, url1)); - Invoker invoker1 = protocol.refer(DemoService.Iface.class, url1); - DemoService.Iface client1 = proxyFactory.getProxy(invoker1); - String result1 = client1.sayHello("haha"); - Assertions.assertTrue(server1.isCalled()); - Assertions.assertEquals("Hello, haha", result1); - - UserServiceImpl server2 = new UserServiceImpl(); - URL url2 = URL.valueOf(org.apache.dubbo.rpc.protocol.nativethrift.ThriftProtocol.NAME + "://127.0.0.1:" + NetUtils.getAvailablePort() + "/" + UserService.Iface.class.getName() + "?version=1.0.0&nativethrift.overload.method=true"); - Exporter exporter2 = protocol.export(proxyFactory.getInvoker(server2, UserService.Iface.class, url2)); - Invoker invoker2 = protocol.refer(UserService.Iface.class, url2); - UserService.Iface client2 = proxyFactory.getProxy(invoker2); - String result2 = client2.find(2); - Assertions.assertEquals("KK2", result2); - - invoker1.destroy(); - exporter1.unexport(); - invoker2.destroy(); - exporter2.unexport(); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserService.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserService.java deleted file mode 100644 index d26b460874..0000000000 --- a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserService.java +++ /dev/null @@ -1,952 +0,0 @@ -/** - * Autogenerated by Thrift Compiler (0.11.0) - * - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - * @generated - */ -package org.apache.dubbo.rpc.protocol.nativethrift; - -@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"}) -public class UserService { - - public interface Iface { - - String find(int id) throws org.apache.thrift.TException; - - } - - public interface AsyncIface { - - void find(int id, 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 find(int id) throws org.apache.thrift.TException - { - send_find(id); - return recv_find(); - } - - public void send_find(int id) throws org.apache.thrift.TException - { - find_args args = new find_args(); - args.setId(id); - sendBase("find", args); - } - - public String recv_find() throws org.apache.thrift.TException - { - find_result result = new find_result(); - receiveBase(result, "find"); - if (result.isSetSuccess()) { - return result.success; - } - throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "find 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 find(int id, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - checkReady(); - find_call method_call = new find_call(id, resultHandler, this, ___protocolFactory, ___transport); - this.___currentMethod = method_call; - ___manager.call(method_call); - } - - public static class find_call extends org.apache.thrift.async.TAsyncMethodCall { - private int id; - public find_call(int id, 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.id = id; - } - - public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException { - prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("find", org.apache.thrift.protocol.TMessageType.CALL, 0)); - find_args args = new find_args(); - args.setId(id); - args.write(prot); - prot.writeMessageEnd(); - } - - public String getResult() throws org.apache.thrift.TException { - if (getState() != 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_find(); - } - } - - } - - public static class Processor extends org.apache.thrift.TBaseProcessor implements org.apache.thrift.TProcessor { - private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName()); - public Processor(I iface) { - super(iface, getProcessMap(new java.util.HashMap>())); - } - - protected Processor(I iface, java.util.Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static java.util.Map> getProcessMap(java.util.Map> processMap) { - processMap.put("find", new find()); - return processMap; - } - - public static class find extends org.apache.thrift.ProcessFunction { - public find() { - super("find"); - } - - public find_args getEmptyArgsInstance() { - return new find_args(); - } - - protected boolean isOneway() { - return false; - } - - protected boolean handleRuntimeExceptions() { - return false; - } - - public find_result getResult(I iface, find_args args) throws org.apache.thrift.TException { - find_result result = new find_result(); - result.success = iface.find(args.id); - return result; - } - } - - } - - public static class AsyncProcessor extends org.apache.thrift.TBaseAsyncProcessor { - private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(AsyncProcessor.class.getName()); - public AsyncProcessor(I iface) { - super(iface, getProcessMap(new java.util.HashMap>())); - } - - protected AsyncProcessor(I iface, java.util.Map> processMap) { - super(iface, getProcessMap(processMap)); - } - - private static java.util.Map> getProcessMap(java.util.Map> processMap) { - processMap.put("find", new find()); - return processMap; - } - - public static class find extends org.apache.thrift.AsyncProcessFunction { - public find() { - super("find"); - } - - public find_args getEmptyArgsInstance() { - return new find_args(); - } - - public org.apache.thrift.async.AsyncMethodCallback getResultHandler(final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) { - final org.apache.thrift.AsyncProcessFunction fcall = this; - return new org.apache.thrift.async.AsyncMethodCallback() { - public void onComplete(String o) { - find_result result = new find_result(); - result.success = o; - try { - fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid); - } catch (org.apache.thrift.transport.TTransportException e) { - _LOGGER.error("TTransportException writing to internal frame buffer", e); - fb.close(); - } catch (Exception e) { - _LOGGER.error("Exception writing to internal frame buffer", e); - onError(e); - } - } - public void onError(Exception e) { - byte msgType = org.apache.thrift.protocol.TMessageType.REPLY; - org.apache.thrift.TSerializable msg; - find_result result = new find_result(); - if (e instanceof org.apache.thrift.transport.TTransportException) { - _LOGGER.error("TTransportException inside handler", e); - fb.close(); - return; - } else if (e instanceof org.apache.thrift.TApplicationException) { - _LOGGER.error("TApplicationException inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = (org.apache.thrift.TApplicationException)e; - } else { - _LOGGER.error("Exception inside handler", e); - msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION; - msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage()); - } - try { - fcall.sendResponse(fb,msg,msgType,seqid); - } catch (Exception ex) { - _LOGGER.error("Exception writing to internal frame buffer", ex); - fb.close(); - } - } - }; - } - - protected boolean isOneway() { - return false; - } - - public void start(I iface, find_args args, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException { - iface.find(args.id,resultHandler); - } - } - - } - - public static class find_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("find_args"); - - private static final org.apache.thrift.protocol.TField ID_FIELD_DESC = new org.apache.thrift.protocol.TField("id", org.apache.thrift.protocol.TType.I32, (short)1); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new find_argsStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new find_argsTupleSchemeFactory(); - - public int id; // 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 { - ID((short)1, "id"); - - private static final java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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: // ID - return ID; - 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 __ID_ISSET_ID = 0; - private byte __isset_bitfield = 0; - public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); - tmpMap.put(_Fields.ID, new org.apache.thrift.meta_data.FieldMetaData("id", org.apache.thrift.TFieldRequirementType.REQUIRED, - new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32))); - metaDataMap = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(find_args.class, metaDataMap); - } - - public find_args() { - } - - public find_args( - int id) - { - this(); - this.id = id; - setIdIsSet(true); - } - - /** - * Performs a deep copy on other. - */ - public find_args(find_args other) { - __isset_bitfield = other.__isset_bitfield; - this.id = other.id; - } - - public find_args deepCopy() { - return new find_args(this); - } - - @Override - public void clear() { - setIdIsSet(false); - this.id = 0; - } - - public int getId() { - return this.id; - } - - public find_args setId(int id) { - this.id = id; - setIdIsSet(true); - return this; - } - - public void unsetId() { - __isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __ID_ISSET_ID); - } - - /** Returns true if field id is set (has been assigned a value) and false otherwise */ - public boolean isSetId() { - return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __ID_ISSET_ID); - } - - public void setIdIsSet(boolean value) { - __isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __ID_ISSET_ID, value); - } - - public void setFieldValue(_Fields field, Object value) { - switch (field) { - case ID: - if (value == null) { - unsetId(); - } else { - setId((Integer)value); - } - break; - - } - } - - public Object getFieldValue(_Fields field) { - switch (field) { - case ID: - return getId(); - - } - 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 ID: - return isSetId(); - } - throw new IllegalStateException(); - } - - @Override - public boolean equals(Object that) { - if (that == null) - return false; - if (that instanceof find_args) - return this.equals((find_args)that); - return false; - } - - public boolean equals(find_args that) { - if (that == null) - return false; - if (this == that) - return true; - - boolean this_present_id = true; - boolean that_present_id = true; - if (this_present_id || that_present_id) { - if (!(this_present_id && that_present_id)) - return false; - if (this.id != that.id) - return false; - } - - return true; - } - - @Override - public int hashCode() { - int hashCode = 1; - - hashCode = hashCode * 8191 + id; - - return hashCode; - } - - @Override - public int compareTo(find_args other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetId()).compareTo(other.isSetId()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetId()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.id, other.id); - 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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("find_args("); - boolean first = true; - - sb.append("id:"); - sb.append(this.id); - first = false; - sb.append(")"); - return sb.toString(); - } - - public void validate() throws org.apache.thrift.TException { - // check for required fields - // alas, we cannot check 'id' because it's a primitive and you chose the non-beans generator. - // check for sub-struct validity - } - - 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_bitfield = 0; - 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); - } - } - - private static class find_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public find_argsStandardScheme getScheme() { - return new find_argsStandardScheme(); - } - } - - private static class find_argsStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, find_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 1: // ID - if (schemeField.type == org.apache.thrift.protocol.TType.I32) { - struct.id = iprot.readI32(); - struct.setIdIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - if (!struct.isSetId()) { - throw new org.apache.thrift.protocol.TProtocolException("Required field 'id' was not found in serialized data! Struct: " + toString()); - } - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, find_args struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - oprot.writeFieldBegin(ID_FIELD_DESC); - oprot.writeI32(struct.id); - oprot.writeFieldEnd(); - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class find_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public find_argsTupleScheme getScheme() { - return new find_argsTupleScheme(); - } - } - - private static class find_argsTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, find_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - oprot.writeI32(struct.id); - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, find_args struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - struct.id = iprot.readI32(); - struct.setIdIsSet(true); - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - - public static class find_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable, Comparable { - private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("find_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); - - private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new find_resultStandardSchemeFactory(); - private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new find_resultTupleSchemeFactory(); - - 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 java.util.Map byName = new java.util.HashMap(); - - static { - for (_Fields field : java.util.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 java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - static { - java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.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 = java.util.Collections.unmodifiableMap(tmpMap); - org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(find_result.class, metaDataMap); - } - - public find_result() { - } - - public find_result( - String success) - { - this(); - this.success = success; - } - - /** - * Performs a deep copy on other. - */ - public find_result(find_result other) { - if (other.isSetSuccess()) { - this.success = other.success; - } - } - - public find_result deepCopy() { - return new find_result(this); - } - - @Override - public void clear() { - this.success = null; - } - - public String getSuccess() { - return this.success; - } - - public find_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 find_result) - return this.equals((find_result)that); - return false; - } - - public boolean equals(find_result that) { - if (that == null) - return false; - if (this == that) - return true; - - 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() { - int hashCode = 1; - - hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287); - if (isSetSuccess()) - hashCode = hashCode * 8191 + success.hashCode(); - - return hashCode; - } - - @Override - public int compareTo(find_result other) { - if (!getClass().equals(other.getClass())) { - return getClass().getName().compareTo(other.getClass().getName()); - } - - int lastComparison = 0; - - lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess()); - if (lastComparison != 0) { - return lastComparison; - } - if (isSetSuccess()) { - lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.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 { - scheme(iprot).read(iprot, this); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { - scheme(oprot).write(oprot, this); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder("find_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 - // check for sub-struct validity - } - - 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); - } - } - - private static class find_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public find_resultStandardScheme getScheme() { - return new find_resultStandardScheme(); - } - } - - private static class find_resultStandardScheme extends org.apache.thrift.scheme.StandardScheme { - - public void read(org.apache.thrift.protocol.TProtocol iprot, find_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TField schemeField; - iprot.readStructBegin(); - while (true) - { - schemeField = iprot.readFieldBegin(); - if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { - break; - } - switch (schemeField.id) { - case 0: // SUCCESS - if (schemeField.type == org.apache.thrift.protocol.TType.STRING) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } else { - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - break; - default: - org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); - } - iprot.readFieldEnd(); - } - iprot.readStructEnd(); - - // check for required fields of primitive type, which can't be checked in the validate method - struct.validate(); - } - - public void write(org.apache.thrift.protocol.TProtocol oprot, find_result struct) throws org.apache.thrift.TException { - struct.validate(); - - oprot.writeStructBegin(STRUCT_DESC); - if (struct.success != null) { - oprot.writeFieldBegin(SUCCESS_FIELD_DESC); - oprot.writeString(struct.success); - oprot.writeFieldEnd(); - } - oprot.writeFieldStop(); - oprot.writeStructEnd(); - } - - } - - private static class find_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory { - public find_resultTupleScheme getScheme() { - return new find_resultTupleScheme(); - } - } - - private static class find_resultTupleScheme extends org.apache.thrift.scheme.TupleScheme { - - @Override - public void write(org.apache.thrift.protocol.TProtocol prot, find_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet optionals = new java.util.BitSet(); - if (struct.isSetSuccess()) { - optionals.set(0); - } - oprot.writeBitSet(optionals, 1); - if (struct.isSetSuccess()) { - oprot.writeString(struct.success); - } - } - - @Override - public void read(org.apache.thrift.protocol.TProtocol prot, find_result struct) throws org.apache.thrift.TException { - org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot; - java.util.BitSet incoming = iprot.readBitSet(1); - if (incoming.get(0)) { - struct.success = iprot.readString(); - struct.setSuccessIsSet(true); - } - } - } - - private static S scheme(org.apache.thrift.protocol.TProtocol proto) { - return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme(); - } - } - -} diff --git a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserServiceImpl.java b/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserServiceImpl.java deleted file mode 100644 index 3cd3c76cfb..0000000000 --- a/dubbo-rpc/dubbo-rpc-native-thrift/src/test/java/org/apache/dubbo/rpc/protocol/nativethrift/UserServiceImpl.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.nativethrift; - -public class UserServiceImpl implements UserService.Iface { - - public String find(int id) throws org.apache.thrift.TException{ - return "KK"+id; - } -} diff --git a/dubbo-rpc/dubbo-rpc-redis/pom.xml b/dubbo-rpc/dubbo-rpc-redis/pom.xml deleted file mode 100644 index 9daff2322d..0000000000 --- a/dubbo-rpc/dubbo-rpc-redis/pom.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-redis - jar - ${project.artifactId} - The redis rpc module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - redis.clients - jedis - - - com.github.kstyrc - embedded-redis - test - - - org.apache.dubbo - dubbo-serialization-jdk - ${project.parent.version} - test - - - org.apache.commons - commons-lang3 - test - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java b/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java deleted file mode 100644 index b5081887c2..0000000000 --- a/dubbo-rpc/dubbo-rpc-redis/src/main/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocol.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.redis; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.AsyncRpcResult; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.AbstractInvoker; -import org.apache.dubbo.rpc.protocol.AbstractProtocol; - -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.exceptions.JedisDataException; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.Map; -import java.util.concurrent.TimeoutException; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; -import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; - - -/** - * RedisProtocol - */ -public class RedisProtocol extends AbstractProtocol { - - public static final int DEFAULT_PORT = 6379; - - @Override - public int getDefaultPort() { - return DEFAULT_PORT; - } - - @Override - public Exporter export(final Invoker invoker) throws RpcException { - throw new UnsupportedOperationException("Unsupported export redis service. url: " + invoker.getUrl()); - } - - private Serialization getSerialization(URL url) { - return ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(url.getParameter(Constants.SERIALIZATION_KEY, "java")); - } - - @Override - protected Invoker protocolBindingRefer(final Class type, final URL url) throws RpcException { - try { - GenericObjectPoolConfig config = new GenericObjectPoolConfig(); - config.setTestOnBorrow(url.getParameter("test.on.borrow", true)); - config.setTestOnReturn(url.getParameter("test.on.return", false)); - config.setTestWhileIdle(url.getParameter("test.while.idle", false)); - if (url.getParameter("max.idle", 0) > 0) { - config.setMaxIdle(url.getParameter("max.idle", 0)); - } - if (url.getParameter("min.idle", 0) > 0) { - config.setMinIdle(url.getParameter("min.idle", 0)); - } - if (url.getParameter("max.active", 0) > 0) { - config.setMaxTotal(url.getParameter("max.active", 0)); - } - if (url.getParameter("max.total", 0) > 0) { - config.setMaxTotal(url.getParameter("max.total", 0)); - } - if (url.getParameter("max.wait", 0) > 0) { - config.setMaxWaitMillis(url.getParameter("max.wait", 0)); - } - if (url.getParameter("num.tests.per.eviction.run", 0) > 0) { - config.setNumTestsPerEvictionRun(url.getParameter("num.tests.per.eviction.run", 0)); - } - if (url.getParameter("time.between.eviction.runs.millis", 0) > 0) { - config.setTimeBetweenEvictionRunsMillis(url.getParameter("time.between.eviction.runs.millis", 0)); - } - if (url.getParameter("min.evictable.idle.time.millis", 0) > 0) { - config.setMinEvictableIdleTimeMillis(url.getParameter("min.evictable.idle.time.millis", 0)); - } - final JedisPool jedisPool = new JedisPool(config, url.getHost(), url.getPort(DEFAULT_PORT), - url.getParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT), - StringUtils.isBlank(url.getPassword()) ? null : url.getPassword(), - url.getParameter("db.index", 0)); - final int expiry = url.getParameter("expiry", 0); - final String get = url.getParameter("get", "get"); - final String set = url.getParameter("set", Map.class.equals(type) ? "put" : "set"); - final String delete = url.getParameter("delete", Map.class.equals(type) ? "remove" : "delete"); - return new AbstractInvoker(type, url) { - @Override - protected Result doInvoke(Invocation invocation) throws Throwable { - Jedis jedis = null; - try { - jedis = jedisPool.getResource(); - - if (get.equals(invocation.getMethodName())) { - if (invocation.getArguments().length != 1) { - throw new IllegalArgumentException("The redis get method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); - } - byte[] value = jedis.get(String.valueOf(invocation.getArguments()[0]).getBytes()); - if (value == null) { - return AsyncRpcResult.newDefaultAsyncResult(invocation); - } - ObjectInput oin = getSerialization(url).deserialize(url, new ByteArrayInputStream(value)); - return AsyncRpcResult.newDefaultAsyncResult(oin.readObject(), invocation); - } else if (set.equals(invocation.getMethodName())) { - if (invocation.getArguments().length != 2) { - throw new IllegalArgumentException("The redis set method arguments mismatch, must be two arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); - } - byte[] key = String.valueOf(invocation.getArguments()[0]).getBytes(); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - ObjectOutput value = getSerialization(url).serialize(url, output); - value.writeObject(invocation.getArguments()[1]); - jedis.set(key, output.toByteArray()); - if (expiry > 1000) { - jedis.expire(key, expiry / 1000); - } - return AsyncRpcResult.newDefaultAsyncResult(invocation); - } else if (delete.equals(invocation.getMethodName())) { - if (invocation.getArguments().length != 1) { - throw new IllegalArgumentException("The redis delete method arguments mismatch, must only one arguments. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url); - } - jedis.del(String.valueOf(invocation.getArguments()[0]).getBytes()); - return AsyncRpcResult.newDefaultAsyncResult(invocation); - } else { - throw new UnsupportedOperationException("Unsupported method " + invocation.getMethodName() + " in redis service."); - } - } catch (Throwable t) { - RpcException re = new RpcException("Failed to invoke redis service method. interface: " + type.getName() + ", method: " + invocation.getMethodName() + ", url: " + url + ", cause: " + t.getMessage(), t); - if (t instanceof TimeoutException || t instanceof SocketTimeoutException) { - re.setCode(RpcException.TIMEOUT_EXCEPTION); - } else if (t instanceof JedisConnectionException || t instanceof IOException) { - re.setCode(RpcException.NETWORK_EXCEPTION); - } else if (t instanceof JedisDataException) { - re.setCode(RpcException.SERIALIZATION_EXCEPTION); - } - throw re; - } finally { - if (jedis != null) { - try { - jedis.close(); - } catch (Throwable t) { - logger.warn("returnResource error: " + t.getMessage(), t); - } - } - } - } - - @Override - public void destroy() { - super.destroy(); - try { - jedisPool.destroy(); - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - } - } - }; - } catch (Throwable t) { - throw new RpcException("Failed to refer redis service. interface: " + type.getName() + ", url: " + url + ", cause: " + t.getMessage(), t); - } - } - -} diff --git a/dubbo-rpc/dubbo-rpc-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol deleted file mode 100644 index e715493701..0000000000 --- a/dubbo-rpc/dubbo-rpc-redis/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -redis=org.apache.dubbo.rpc.protocol.redis.RedisProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/IDemoService.java b/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/IDemoService.java deleted file mode 100644 index 0f0b22480f..0000000000 --- a/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/IDemoService.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.redis; - -public interface IDemoService { - void set(String key, String value); - - String get(String key); - - void delete(String key); - - String unsupported(String wrong); - - String set(String key, String value, String extraArg); -} diff --git a/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java b/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java deleted file mode 100644 index 2c2f182976..0000000000 --- a/dubbo-rpc/dubbo-rpc-redis/src/test/java/org/apache/dubbo/rpc/protocol/redis/RedisProtocolTest.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.redis; - -import org.apache.commons.lang3.SystemUtils; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.Serialization; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.dubbo.rpc.RpcException; - -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInfo; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.exceptions.JedisDataException; -import redis.embedded.RedisServer; -import redis.embedded.RedisServerBuilder; - -import java.io.ByteArrayInputStream; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; - -public class RedisProtocolTest { - private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - private RedisServer redisServer; - private URL registryUrl; - - @BeforeEach - public void setUp(TestInfo testInfo) { - int redisPort = NetUtils.getAvailablePort(); - String methodName = testInfo.getTestMethod().get().getName(); - if ("testAuthRedis".equals(methodName) || ("testWrongAuthRedis".equals(methodName))) { - String password = "123456"; - RedisServerBuilder builder = RedisServer.builder().port(redisPort).setting("requirepass " + password); - if (SystemUtils.IS_OS_WINDOWS) { - // set maxheap to fix Windows error 0x70 while starting redis - builder.setting("maxheap 128mb"); - } - redisServer = builder.build(); - this.registryUrl = URL.valueOf("redis://username:" + password + "@localhost:" + redisPort + "?db.index=0"); - } else { - RedisServerBuilder builder = RedisServer.builder().port(redisPort); - if (SystemUtils.IS_OS_WINDOWS) { - // set maxheap to fix Windows error 0x70 while starting redis - builder.setting("maxheap 128mb"); - } - redisServer = builder.build(); - this.registryUrl = URL.valueOf("redis://localhost:" + redisPort); - } - this.redisServer.start(); - } - - @AfterEach - public void tearDown() { - this.redisServer.stop(); - } - @Test - public void testReferClass() { - Invoker refer = protocol.refer(IDemoService.class, registryUrl); - - Class serviceClass = refer.getInterface(); - assertThat(serviceClass.getName(), is("org.apache.dubbo.rpc.protocol.redis.IDemoService")); - } - - @Test - public void testInvocation() { - Invoker refer = protocol.refer(IDemoService.class, - registryUrl - .addParameter("max.idle", 10) - .addParameter("max.active", 20)); - IDemoService demoService = this.proxy.getProxy(refer); - - String value = demoService.get("key"); - assertThat(value, is(nullValue())); - - demoService.set("key", "newValue"); - value = demoService.get("key"); - assertThat(value, is("newValue")); - - demoService.delete("key"); - value = demoService.get("key"); - assertThat(value, is(nullValue())); - - refer.destroy(); - } - - @Test - public void testUnsupportedMethod() { - Assertions.assertThrows(RpcException.class, () -> { - Invoker refer = protocol.refer(IDemoService.class, registryUrl); - IDemoService demoService = this.proxy.getProxy(refer); - - demoService.unsupported(null); - }); - } - - @Test - public void testWrongParameters() { - Assertions.assertThrows(RpcException.class, () -> { - Invoker refer = protocol.refer(IDemoService.class, registryUrl); - IDemoService demoService = this.proxy.getProxy(refer); - - demoService.set("key", "value", "wrongValue"); - }); - } - - @Test - public void testWrongRedis() { - Assertions.assertThrows(RpcException.class, () -> { - Invoker refer = protocol.refer(IDemoService.class, URL.valueOf("redis://localhost:1")); - IDemoService demoService = this.proxy.getProxy(refer); - - demoService.get("key"); - }); - } - - @Test - public void testExport() { - Assertions.assertThrows(UnsupportedOperationException.class, () -> protocol.export(protocol.refer(IDemoService.class, registryUrl))); - } - - @Test - public void testAuthRedis() { - // default db.index=0 - Invoker refer = protocol.refer(IDemoService.class, - registryUrl - .addParameter("max.idle", 10) - .addParameter("max.active", 20)); - IDemoService demoService = this.proxy.getProxy(refer); - - String value = demoService.get("key"); - assertThat(value, is(nullValue())); - - demoService.set("key", "newValue"); - value = demoService.get("key"); - assertThat(value, is("newValue")); - - demoService.delete("key"); - value = demoService.get("key"); - assertThat(value, is(nullValue())); - - refer.destroy(); - - //change db.index=1 - String password = "123456"; - int database = 1; - this.registryUrl = this.registryUrl.setPassword(password).addParameter("db.index", database); - refer = protocol.refer(IDemoService.class, - registryUrl - .addParameter("max.idle", 10) - .addParameter("max.active", 20)); - demoService = this.proxy.getProxy(refer); - - demoService.set("key", "newValue"); - value = demoService.get("key"); - assertThat(value, is("newValue")); - - // jedis gets the result comparison - JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), "localhost", registryUrl.getPort(), 2000, password, database, (String) null); - try (Jedis jedis = pool.getResource()) { - byte[] valueByte = jedis.get("key".getBytes()); - Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(this.registryUrl.getParameter(Constants.SERIALIZATION_KEY, "java")); - ObjectInput oin = serialization.deserialize(this.registryUrl, new ByteArrayInputStream(valueByte)); - String actual = (String) oin.readObject(); - assertThat(value, is(actual)); - } catch (Exception e) { - Assertions.fail("jedis gets the result comparison is error!"); - } finally { - pool.destroy(); - } - - demoService.delete("key"); - value = demoService.get("key"); - assertThat(value, is(nullValue())); - - refer.destroy(); - } - - @Test - public void testWrongAuthRedis() { - String password = "1234567"; - this.registryUrl = this.registryUrl.setPassword(password); - Invoker refer = protocol.refer(IDemoService.class, - registryUrl - .addParameter("max.idle", 10) - .addParameter("max.active", 20)); - IDemoService demoService = this.proxy.getProxy(refer); - - try { - String value = demoService.get("key"); - assertThat(value, is(nullValue())); - } catch (RpcException e) { - if (e.getCause() instanceof JedisConnectionException && e.getCause().getCause() instanceof JedisDataException) { - Assertions.assertEquals("ERR invalid password", e.getCause().getCause().getMessage()); - } else { - Assertions.fail("no invalid password exception!"); - } - } - - refer.destroy(); - } -} diff --git a/dubbo-rpc/dubbo-rpc-redis/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization b/dubbo-rpc/dubbo-rpc-redis/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization deleted file mode 100644 index 495c475e55..0000000000 --- a/dubbo-rpc/dubbo-rpc-redis/src/test/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization +++ /dev/null @@ -1 +0,0 @@ -java=org.apache.dubbo.common.serialize.java.JavaSerialization \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rmi/pom.xml b/dubbo-rpc/dubbo-rpc-rmi/pom.xml deleted file mode 100644 index 1c7d3273f3..0000000000 --- a/dubbo-rpc/dubbo-rpc-rmi/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-rmi - jar - ${project.artifactId} - The rmi rpc module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.springframework - spring-context - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java deleted file mode 100644 index 22a07b03d4..0000000000 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/com/alibaba/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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 com.alibaba.dubbo.rpc.protocol.rmi; - -import org.aopalliance.intercept.MethodInvocation; - -/** - * This class is deprecated, please use {@link org.apache.dubbo.rpc.protocol.rmi.RmiRemoteInvocation}. - * - * @author chickenlj - * @deprecated - */ -@Deprecated -public class RmiRemoteInvocation extends org.apache.dubbo.rpc.protocol.rmi.RmiRemoteInvocation { - private static final long serialVersionUID = 1L; - - /** - * executed on consumer side - * - * @param methodInvocation - */ - public RmiRemoteInvocation(MethodInvocation methodInvocation) { - super(methodInvocation); - } -} diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java deleted file mode 100644 index 325064f25e..0000000000 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocol.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.rmi; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; -import org.apache.dubbo.rpc.service.GenericService; -import org.apache.dubbo.rpc.support.ProtocolUtils; - -import org.springframework.remoting.RemoteAccessException; -import org.springframework.remoting.rmi.RmiProxyFactoryBean; -import org.springframework.remoting.rmi.RmiServiceExporter; -import org.springframework.remoting.support.RemoteInvocation; - -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.rmi.RemoteException; - -import static org.apache.dubbo.common.Version.isRelease263OrHigher; -import static org.apache.dubbo.common.Version.isRelease270OrHigher; -import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; -import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; - -/** - * RmiProtocol. - */ -public class RmiProtocol extends AbstractProxyProtocol { - - public static final int DEFAULT_PORT = 1099; - - public RmiProtocol() { - super(RemoteAccessException.class, RemoteException.class); - } - - @Override - public int getDefaultPort() { - return DEFAULT_PORT; - } - - @Override - protected Runnable doExport(final T impl, Class type, URL url) throws RpcException { - RmiServiceExporter rmiServiceExporter = createExporter(impl, type, url, false); - RmiServiceExporter genericServiceExporter = createExporter(impl, GenericService.class, url, true); - return new Runnable() { - @Override - public void run() { - try { - rmiServiceExporter.destroy(); - genericServiceExporter.destroy(); - } catch (Throwable e) { - logger.warn(e.getMessage(), e); - } - } - }; - } - - @Override - @SuppressWarnings("unchecked") - protected T doRefer(final Class serviceType, final URL url) throws RpcException { - final RmiProxyFactoryBean rmiProxyFactoryBean = new RmiProxyFactoryBean(); - final String generic = url.getParameter(GENERIC_KEY); - final boolean isGeneric = ProtocolUtils.isGeneric(generic) || serviceType.equals(GenericService.class); - /* - RMI needs extra parameter since it uses customized remote invocation object - - The customized RemoteInvocation was firstly introduced in v2.6.3; The package was renamed to 'org.apache.*' since v2.7.0 - Considering the above two conditions, we need to check before sending customized RemoteInvocation: - 1. if the provider version is v2.7.0 or higher, send 'org.apache.dubbo.rpc.protocol.rmi.RmiRemoteInvocation'. - 2. if the provider version is v2.6.3 or higher, send 'com.alibaba.dubbo.rpc.protocol.rmi.RmiRemoteInvocation'. - 3. if the provider version is lower than v2.6.3, does not use customized RemoteInvocation. - */ - if (isRelease270OrHigher(url.getParameter(RELEASE_KEY))) { - rmiProxyFactoryBean.setRemoteInvocationFactory(methodInvocation -> { - RemoteInvocation invocation = new RmiRemoteInvocation(methodInvocation); - if (isGeneric) { - invocation.addAttribute(GENERIC_KEY, generic); - } - return invocation; - }); - } else if (isRelease263OrHigher(url.getParameter(DUBBO_VERSION_KEY))) { - rmiProxyFactoryBean.setRemoteInvocationFactory(methodInvocation -> { - RemoteInvocation invocation = new com.alibaba.dubbo.rpc.protocol.rmi.RmiRemoteInvocation(methodInvocation); - if (isGeneric) { - invocation.addAttribute(GENERIC_KEY, generic); - } - return invocation; - }); - } - String serviceUrl = url.toIdentityString(); - if (isGeneric) { - serviceUrl = serviceUrl + "/" + GENERIC_KEY; - } - rmiProxyFactoryBean.setServiceUrl(serviceUrl); - rmiProxyFactoryBean.setServiceInterface(serviceType); - rmiProxyFactoryBean.setCacheStub(true); - rmiProxyFactoryBean.setLookupStubOnStartup(true); - rmiProxyFactoryBean.setRefreshStubOnConnectFailure(true); - rmiProxyFactoryBean.afterPropertiesSet(); - return (T) rmiProxyFactoryBean.getObject(); - } - - @Override - protected int getErrorCode(Throwable e) { - if (e instanceof RemoteAccessException) { - e = e.getCause(); - } - if (e != null && e.getCause() != null) { - Class cls = e.getCause().getClass(); - 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 super.getErrorCode(e); - } - - private RmiServiceExporter createExporter(T impl, Class type, URL url, boolean isGeneric) { - final RmiServiceExporter rmiServiceExporter = new RmiServiceExporter(); - rmiServiceExporter.setRegistryPort(url.getPort()); - if (isGeneric) { - rmiServiceExporter.setServiceName(url.getPath() + "/" + GENERIC_KEY); - } else { - rmiServiceExporter.setServiceName(url.getPath()); - } - rmiServiceExporter.setServiceInterface(type); - rmiServiceExporter.setService(impl); - try { - rmiServiceExporter.afterPropertiesSet(); - } catch (RemoteException e) { - throw new RpcException(e.getMessage(), e); - } - return rmiServiceExporter; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java b/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java deleted file mode 100644 index 33b16e3e28..0000000000 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/java/org/apache/dubbo/rpc/protocol/rmi/RmiRemoteInvocation.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.rmi; - -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.rpc.RpcContext; - -import org.aopalliance.intercept.MethodInvocation; -import org.springframework.remoting.support.RemoteInvocation; - -import java.lang.reflect.InvocationTargetException; -import java.util.HashMap; -import java.util.Map; - -import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; - -public class RmiRemoteInvocation extends RemoteInvocation { - private static final long serialVersionUID = 1L; - private static final String DUBBO_ATTACHMENTS_ATTR_NAME = "dubbo.attachments"; - - /** - * executed on consumer side - */ - public RmiRemoteInvocation(MethodInvocation methodInvocation) { - super(methodInvocation); - addAttribute(DUBBO_ATTACHMENTS_ATTR_NAME, new HashMap<>(RpcContext.getContext().getObjectAttachments())); - } - - /** - * Need to restore context on provider side (Though context will be overridden by Invocation's attachment - * when ContextFilter gets executed, we will restore the attachment when Invocation is constructed, check more - * from {@link org.apache.dubbo.rpc.proxy.InvokerInvocationHandler} - */ - @SuppressWarnings("unchecked") - @Override - public Object invoke(Object targetObject) throws NoSuchMethodException, IllegalAccessException, - InvocationTargetException { - RpcContext context = RpcContext.getContext(); - context.setObjectAttachments((Map) getAttribute(DUBBO_ATTACHMENTS_ATTR_NAME)); - String generic = (String) getAttribute(GENERIC_KEY); - if (StringUtils.isNotEmpty(generic)) { - context.setAttachment(GENERIC_KEY, generic); - } - try { - return super.invoke(targetObject); - } finally { - context.setObjectAttachments(null); - } - } -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-rmi/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol deleted file mode 100644 index a1e30e3af6..0000000000 --- a/dubbo-rpc/dubbo-rpc-rmi/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -rmi=org.apache.dubbo.rpc.protocol.rmi.RmiProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/DemoService.java b/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/DemoService.java deleted file mode 100644 index 4f88fa9c30..0000000000 --- a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/DemoService.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.rmi; - -/** - * TestService - */ - -public interface DemoService { - void sayHello(String name); - - String sayHi(String name); - - String echo(String text); - - long timestamp(); - - void throwTimeout(); - - String getThreadName(); - - int getSize(String[] strs); - - int getSize(Object[] os); - - Object invoke(String service, String method) throws Exception; - - int stringLength(String str); - - Type enumlength(Type... types); - - String getRemoteApplicationName(); -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/DemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/DemoServiceImpl.java deleted file mode 100644 index c2300c4b84..0000000000 --- a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/DemoServiceImpl.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.rmi; - -import org.apache.dubbo.rpc.RpcContext; - -/** - * DemoServiceImpl - */ - -public class DemoServiceImpl implements DemoService { - public DemoServiceImpl() { - super(); - } - - public void sayHello(String name) { - System.out.println("hello " + name); - } - - public String sayHi(String name) { - return "Hi, " + name; - } - - public String echo(String text) { - return text; - } - - public long timestamp() { - return System.currentTimeMillis(); - } - - public String getThreadName() { - return Thread.currentThread().getName(); - } - - public int getSize(String[] strs) { - if (strs == null) - return -1; - return strs.length; - } - - public int getSize(Object[] os) { - if (os == null) - return -1; - return os.length; - } - - public Object invoke(String service, String method) throws Exception { - System.out.println("RpcContext.getContext().getRemoteHost()=" + RpcContext.getContext().getRemoteHost()); - return service + ":" + method; - } - - public Type enumlength(Type... types) { - if (types.length == 0) - return Type.Lower; - return types[0]; - } - - public int stringLength(String str) { - return str.length(); - } - - public void throwTimeout() { - try { - Thread.sleep(6000); - } catch (InterruptedException e) { - } - } - - - @Override - public String getRemoteApplicationName() { - return RpcContext.getContext().getRemoteApplicationName(); - } -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RemoteService.java b/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RemoteService.java deleted file mode 100644 index b28fad0324..0000000000 --- a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RemoteService.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.rmi; - -import java.rmi.Remote; -import java.rmi.RemoteException; - -public interface RemoteService extends Remote { - String sayHello(String name) throws RemoteException; - - String getThreadName() throws RemoteException; -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RemoteServiceImpl.java b/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RemoteServiceImpl.java deleted file mode 100644 index 0447117e2e..0000000000 --- a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RemoteServiceImpl.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.rmi; - -import org.apache.dubbo.rpc.RpcContext; - -import java.rmi.RemoteException; - -public class RemoteServiceImpl implements RemoteService { - public String getThreadName() throws RemoteException { - System.out.println("RpcContext.getContext().getRemoteHost()=" + RpcContext.getContext().getRemoteHost()); - return Thread.currentThread().getName(); - } - - public String sayHello(String name) throws RemoteException { - return "hello " + name + "@" + RemoteServiceImpl.class.getName(); - } -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocolTest.java b/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocolTest.java deleted file mode 100644 index a1b9af2634..0000000000 --- a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/RmiProtocolTest.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.rmi; - - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.service.EchoService; -import org.apache.dubbo.rpc.service.GenericService; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -public class RmiProtocolTest { - private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - int availablePort = NetUtils.getAvailablePort(); - - /* - @Test - public void test_getRemoteClass() throws Exception { - Class clazz = RmiProtocol.getRemoteClass(NonStdRmiInterface.class); - assertEquals(clazz, RmiProtocol.getRemoteClass(NonStdRmiInterface.class)); - } - */ - @Test - public void testRmiProtocolTimeout() throws Exception { - System.setProperty("sun.rmi.transport.tcp.responseTimeout", "1000"); - DemoService service = new DemoServiceImpl(); - Exporter rpcExporter = protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService"))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService"))); - try { - try { - service.throwTimeout(); - } catch (RpcException e) { - assertTrue(e.isTimeout()); - assertTrue(e.getMessage().contains("Read timed out")); - } - } finally { - rpcExporter.unexport(); - } - } - - @Test - public void testRmiProtocol() throws Exception { - { - DemoService service = new DemoServiceImpl(); - Exporter rpcExporter = protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService"))); - - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService"))); - assertEquals(service.getSize(null), -1); - assertEquals(service.getSize(new String[]{"", "", ""}), 3); - Object result = service.invoke("rmi://127.0.0.1:" + availablePort + "/TestService", "invoke"); - assertEquals("rmi://127.0.0.1:" + availablePort + "/TestService:invoke", result); - - rpcExporter.unexport(); - } - - { - int port = NetUtils.getAvailablePort(); - RemoteService remoteService = new RemoteServiceImpl(); - Exporter rpcExporter = protocol.export(proxy.getInvoker(remoteService, RemoteService.class, URL.valueOf("rmi://127.0.0.1:" + port + "/remoteService"))); - - remoteService = proxy.getProxy(protocol.refer(RemoteService.class, URL.valueOf("rmi://127.0.0.1:" + port + "/remoteService"))); - remoteService.getThreadName(); - for (int i = 0; i < 100; i++) { - String say = remoteService.sayHello("abcd"); - assertEquals("hello abcd@" + RemoteServiceImpl.class.getName(), say); - } - rpcExporter.unexport(); - } - } - - // FIXME RMI protocol doesn't support casting to EchoService yet. - @Disabled - @Test - public void testRmiProtocol_echoService() throws Exception { - DemoService service = new DemoServiceImpl(); - Exporter rpcExporter = protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService"))); - - // cast to EchoService - EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService"))); - assertEquals(echo.$echo("test"), "test"); - assertEquals(echo.$echo("abcdefg"), "abcdefg"); - assertEquals(echo.$echo(1234), 1234); - - rpcExporter.unexport(); - - RemoteService remoteService = new RemoteServiceImpl(); - rpcExporter = protocol.export(proxy.getInvoker(remoteService, RemoteService.class, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/remoteService"))); - - // cast to EchoService - echo = proxy.getProxy(protocol.refer(EchoService.class, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/remoteService"))); - assertEquals(echo.$echo("test"), "test"); - assertEquals(echo.$echo("abcdefg"), "abcdefg"); - assertEquals(echo.$echo(1234), 1234); - - rpcExporter.unexport(); - } - - @Test - public void testGenericInvoke() { - DemoService service = new DemoServiceImpl(); - URL url = URL.valueOf("rmi://127.0.0.1:" + availablePort + "/" + DemoService.class.getName() + "?release=2.7.0"); - Exporter exporter = protocol.export(proxy.getInvoker(service, DemoService.class, url)); - Invoker invoker = protocol.refer(GenericService.class, url); - GenericService client = proxy.getProxy(invoker, true); - String result = (String) client.$invoke("sayHi", new String[]{"java.lang.String"}, new Object[]{"haha"}); - Assertions.assertEquals("Hi, haha", result); - invoker.destroy(); - exporter.unexport(); - } - - - @Test - public void testRemoteApplicationName() throws Exception { - DemoService service = new DemoServiceImpl(); - URL url = URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService?release=2.7.0").addParameter("application", "consumer"); - Exporter rpcExporter = protocol.export(proxy.getInvoker(service, DemoService.class, url)); - - service = proxy.getProxy(protocol.refer(DemoService.class, url)); - assertEquals(service.getRemoteApplicationName(), "consumer"); - - rpcExporter.unexport(); - - } - - public interface NonStdRmiInterface { - void bark(); - } - - /*@Test - public void testRpcInvokerGroup() throws Exception - { - DemoService service = new DemoServiceImpl(); - RpcUtils.export("demo://127.0.0.1:9030/org.apache.dubbo.rpc.TestService",DemoService.class,service); - RpcUtils.export("dubbo://127.0.0.1:9031/TestService",DemoService.class,service); - RpcUtils.export("rmi://127.0.0.1:9032/org.apache.dubbo.rpc.TestService",DemoService.class,service); - RpcUtils.export("rmi://127.0.0.1:9033/org.apache.dubbo.rpc.TestService",DemoService.class,service); - - service = RpcUtils.createProxy(DemoService.class, - new String[]{ - "demo://127.0.0.1:9030/org.apache.dubbo.rpc.TestService?weight=20", - "dubbo://127.0.0.1:9031/TestService?weight=20", - "rmi://127.0.0.1:9032/org.apache.dubbo.rpc.TestService", - }); - assertEquals(service.getSize(null), -1); - assertEquals(service.getSize(new String[]{"","",""}), 3); - - // cast to EchoService - EchoService echo = RpcUtils.createProxy(EchoService.class, - new String[]{ - "demo://127.0.0.1:9030/org.apache.dubbo.rpc.TestService?weight=20", - "dubbo://127.0.0.1:9031/TestService?weight=20", - "rmi://127.0.0.1:9032/org.apache.dubbo.rpc.TestService", - }); - assertEquals(echo.$echo("test"), "test"); - assertEquals(echo.$echo("abcdefg"), "abcdefg"); - assertEquals(echo.$echo(1234), 1234); - }*/ - - /*public void testForkInvoke() throws Exception - { - DemoService service = new DemoServiceImpl(); - protocol.export(proxy.createInvoker("dubbo://127.0.0.1:9040/TestService", DemoService.class, service); - protocol.export(proxy.createInvoker("dubbo://127.0.0.1:9041/TestService", DemoService.class, service); - protocol.export(proxy.createInvoker("rmi://127.0.0.1:9042/org.apache.dubbo.rpc.TestService", DemoService.class, service); - protocol.export(proxy.createInvoker("rmi://127.0.0.1:9043/org.apache.dubbo.rpc.TestService", DemoService.class, service); - - RpcInvokerGroup group = Proxies.createInvoker(DemoService.class, new String[]{ - "dubbo://127.0.0.1:9040/TestService", - "dubbo://127.0.0.1:9041/TestService", - "rmi://127.0.0.1:9042/org.apache.dubbo.rpc.TestService", - "rmi://127.0.0.1:9043/org.apache.dubbo.rpc.TestService", - }); - group.getMethodSettings("echo").setFork(true); - group.getMethodSettings("echo").setForkInvokeCallback(new ForkInvokeCallback(){ - public Object merge(RpcInvocation invocation, RpcResult[] results) throws Throwable - { - System.out.println("merge result begin:"); - for( RpcResult result : results ) - { - if( result.hasException() ) - System.out.println("exception:"+result.getException().getMessage()); - else - System.out.println("result:"+result.getResult()); - } - System.out.println("merge result end:"); - return "aaaa"; - } - }); - - service = proxy.createProxy(protocol.refer(DemoService.class, group); - service.echo("test"); - - // cast to EchoService - EchoService echo = proxy.createProxy(protocol.refer(EchoService.class, group); - assertEquals(echo.$echo("test"), "test"); - assertEquals(echo.$echo("abcdefg"), "abcdefg"); - assertEquals(echo.$echo(1234), 1234); - }*/ - -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/Type.java b/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/Type.java deleted file mode 100644 index 0f22495045..0000000000 --- a/dubbo-rpc/dubbo-rpc-rmi/src/test/java/org/apache/dubbo/rpc/protocol/rmi/Type.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.rmi; - -public enum Type { - High, Normal, Lower -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/pom.xml b/dubbo-rpc/dubbo-rpc-thrift/pom.xml deleted file mode 100644 index e6c21304fe..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-thrift - jar - ${project.artifactId} - The thrift rpc module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-rpc-dubbo - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-netty4 - ${project.parent.version} - - - org.apache.thrift - libthrift - - - org.springframework - spring-context - - - org.apache.dubbo - dubbo-config-spring - ${project.parent.version} - test - - - org.apache.dubbo - dubbo-registry-multicast - ${project.parent.version} - test - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ClassNameGenerator.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ClassNameGenerator.java deleted file mode 100644 index c88c2e7b04..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ClassNameGenerator.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.extension.SPI; -/** - * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead - */ -@Deprecated -@SPI(DubboClassNameGenerator.NAME) -public interface ClassNameGenerator { - - String generateArgsClassName(String serviceName, String methodName); - - String generateResultClassName(String serviceName, String methodName); - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/DubboClassNameGenerator.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/DubboClassNameGenerator.java deleted file mode 100644 index cc4b1b2158..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/DubboClassNameGenerator.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; -/** - * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead - */ -@Deprecated -public class DubboClassNameGenerator implements ClassNameGenerator { - - public static final String NAME = "dubbo"; - - @Override - public String generateArgsClassName(String serviceName, String methodName) { - return ThriftUtils.generateMethodArgsClassName(serviceName, methodName); - } - - @Override - public String generateResultClassName(String serviceName, String methodName) { - return ThriftUtils.generateMethodResultClassName(serviceName, methodName); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftClassNameGenerator.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftClassNameGenerator.java deleted file mode 100644 index ce8b35947e..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftClassNameGenerator.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; -/** - * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead - */ -@Deprecated -public class ThriftClassNameGenerator implements ClassNameGenerator { - - public static final String NAME = "thrift"; - - @Override - public String generateArgsClassName(String serviceName, String methodName) { - return ThriftUtils.generateMethodArgsClassNameThrift(serviceName, methodName); - } - - @Override - public String generateResultClassName(String serviceName, String methodName) { - return ThriftUtils.generateMethodResultClassNameThrift(serviceName, methodName); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java deleted file mode 100644 index 5f58ae7e22..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodec.java +++ /dev/null @@ -1,697 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.ClassUtils; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.Codec2; -import org.apache.dubbo.remoting.buffer.ChannelBuffer; -import org.apache.dubbo.remoting.buffer.ChannelBufferInputStream; -import org.apache.dubbo.remoting.exchange.Request; -import org.apache.dubbo.remoting.exchange.Response; -import org.apache.dubbo.rpc.AppResponse; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; - -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 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 static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; - -/** - * 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. - *
    - *

    - */ - -/** - * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead - */ -@Deprecated -public class ThriftCodec implements Codec2 { - - 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; - static final ConcurrentMap CACHED_REQUEST = - new ConcurrentHashMap<>(); - private static final AtomicInteger THRIFT_SEQ_ID = new AtomicInteger(0); - private static final ConcurrentMap> CACHED_CLASS = - new ConcurrentHashMap<>(); - - private static int nextSeqId() { - return THRIFT_SEQ_ID.incrementAndGet(); - } - - // just for test - static int getSeqId() { - return THRIFT_SEQ_ID.get(); - } - - @Override - 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("Thrift codec only support encode " - + Request.class.getName() + " and " + Response.class.getName()); - } - - } - - @Override - 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("Unknown magic code " + magic); - } - - if (available < messageLength) { - return DecodeResult.NEED_MORE_INPUT; - } - - return decode(protocol); - - } - - } - - private Object decode(TProtocol protocol) - throws IOException { - - // version - String serviceName; - String path; - long id; - - TMessage message; - - try { - protocol.readI16(); - protocol.readByte(); - serviceName = protocol.readString(); - path = 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(INTERFACE_KEY, serviceName); - result.setAttachment(PATH_KEY, path); - 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 = CACHED_CLASS.get(argsClassName); - - if (clazz == null) { - try { - - clazz = ClassUtils.forNameWithThreadContextClassLoader(argsClassName); - - CACHED_CLASS.putIfAbsent(argsClassName, clazz); - - } catch (ClassNotFoundException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - } - - TBase args; - - try { - args = (TBase) clazz.newInstance(); - } catch (InstantiationException | 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 | InvocationTargetException e) { - throw new RpcException( - RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - } - - result.setArguments(parameters.toArray()); - result.setParameterTypes(parameterTypes.toArray(new Class[0])); - - Request request = new Request(id); - request.setData(result); - - CACHED_REQUEST.putIfAbsent(id, - RequestData.create(message.seqid, serviceName, message.name)); - - return request; - - } else if (message.type == TMessageType.EXCEPTION) { - - TApplicationException exception; - - try { - exception = TApplicationException.readFrom(protocol); - protocol.readMessageEnd(); - } catch (TException e) { - throw new IOException(e.getMessage(), e); - } - - AppResponse result = new AppResponse(); - - 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("Could not infer service result class name from service name " - + serviceName + ", the service name you specified may not generated by thrift idl compiler"); - } - - Class clazz = CACHED_CLASS.get(resultClassName); - - if (clazz == null) { - - try { - - clazz = ClassUtils.forNameWithThreadContextClassLoader(resultClassName); - - CACHED_CLASS.putIfAbsent(resultClassName, clazz); - - } catch (ClassNotFoundException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - } - - TBase result; - try { - result = (TBase) clazz.newInstance(); - } catch (InstantiationException | 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); - - AppResponse appResponse = new AppResponse(); - - if (realResult instanceof Throwable) { - appResponse.setException((Throwable) realResult); - } else { - appResponse.setValue(realResult); - } - - response.setResult(appResponse); - - 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(INTERFACE_KEY); - - if (StringUtils.isEmpty(serviceName)) { - throw new IllegalArgumentException("Could not find service name in attachment with key " - + INTERFACE_KEY); - } - - 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, - "Could not encode request, the specified interface may be incorrect."); - } - - Class clazz = CACHED_CLASS.get(methodArgs); - - if (clazz == null) { - - try { - - clazz = ClassUtils.forNameWithThreadContextClassLoader(methodArgs); - - CACHED_CLASS.putIfAbsent(methodArgs, clazz); - - } catch (ClassNotFoundException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - } - - TBase args; - - try { - args = (TBase) clazz.newInstance(); - } catch (InstantiationException | 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 | 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); - // path - protocol.writeString(inv.getAttachment(PATH_KEY)); - // 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 { - - AppResponse result = (AppResponse) response.getResult(); - - RequestData rd = CACHED_REQUEST.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, - "Could not encode response, the specified interface may be incorrect."); - } - - Class clazz = CACHED_CLASS.get(resultClassName); - - if (clazz == null) { - - try { - clazz = ClassUtils.forNameWithThreadContextClassLoader(resultClassName); - CACHED_CLASS.putIfAbsent(resultClassName, clazz); - } catch (ClassNotFoundException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - - } - - TBase resultObj; - - try { - resultObj = (TBase) clazz.newInstance(); - } catch (InstantiationException | 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 | InvocationTargetException | IllegalAccessException e) { - throw new RpcException(RpcException.SERIALIZATION_EXCEPTION, e.getMessage(), e); - } - } - - if (!found) { - applicationException = new TApplicationException(throwable.getMessage()); - } - - } else { - Object realResult = result.getValue(); - // 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 | InvocationTargetException | 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; - default: - } - 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()); - - } - - 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/org/apache/dubbo/rpc/protocol/thrift/ThriftConstants.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftConstants.java deleted file mode 100644 index 55fb5521ae..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftConstants.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; -/** - * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead - */ -@Deprecated -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/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java deleted file mode 100644 index a18925d469..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftInvoker.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.AtomicPositiveInteger; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.TimeoutException; -import org.apache.dubbo.remoting.exchange.ExchangeClient; -import org.apache.dubbo.rpc.AppResponse; -import org.apache.dubbo.rpc.AsyncRpcResult; -import org.apache.dubbo.rpc.FutureContext; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.protocol.AbstractInvoker; - -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.locks.ReentrantLock; - -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; -import static org.apache.dubbo.remoting.Constants.CHANNEL_ATTRIBUTE_READONLY_KEY; -import static org.apache.dubbo.rpc.Constants.TOKEN_KEY; - - -/** - * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead - */ -@Deprecated -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[]{INTERFACE_KEY, GROUP_KEY, TOKEN_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(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, TIMEOUT_KEY, DEFAULT_TIMEOUT); - - ExecutorService executor = getCallbackExecutor(getUrl(), inv); - CompletableFuture appResponseFuture = currentClient.request(inv, timeout, executor).thenApply(obj -> (AppResponse) obj); - // save for 2.6.x compatibility, for example, TraceFilter in Zipkin uses com.alibaba.xxx.FutureAdapter - FutureContext.getContext().setCompatibleFuture(appResponseFuture); - AsyncRpcResult result = new AsyncRpcResult(appResponseFuture, invocation); - result.setExecutor(executor); - return result; - } 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(CHANNEL_ATTRIBUTE_READONLY_KEY)) { - //cannot write == not Available ? - return true; - } - } - return false; - } - - @Override - public void destroy() { - // in order to avoid closing a client multiple times, a counter is used in case of connection per jvm, every - // time when client.close() is called, counter counts down once, and when counter reaches zero, client will be - // closed. - if (super.isDestroyed()) { - return; - } else { - // double check to avoid dup close - 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/org/apache/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java deleted file mode 100644 index 612417752f..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftNativeCodec.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.Codec2; -import org.apache.dubbo.remoting.buffer.ChannelBuffer; -import org.apache.dubbo.remoting.buffer.ChannelBufferOutputStream; -import org.apache.dubbo.remoting.exchange.Request; -import org.apache.dubbo.remoting.exchange.Response; -import org.apache.dubbo.rpc.Invocation; -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 java.io.IOException; -import java.util.concurrent.atomic.AtomicInteger; -/** - * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead - */ -@Deprecated -public class ThriftNativeCodec implements Codec2 { - - private final AtomicInteger thriftSeq = new AtomicInteger(0); - - 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); - } - - @Override - 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 { - - } - - @Override - public Object decode(Channel channel, ChannelBuffer buffer) throws IOException { - return null; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java deleted file mode 100644 index 2758c5eaac..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocol.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.config.ConfigurationUtils; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.StringUtils; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.RemotingException; -import org.apache.dubbo.remoting.RemotingServer; -import org.apache.dubbo.remoting.Transporter; -import org.apache.dubbo.remoting.exchange.ExchangeChannel; -import org.apache.dubbo.remoting.exchange.ExchangeClient; -import org.apache.dubbo.remoting.exchange.ExchangeHandler; -import org.apache.dubbo.remoting.exchange.ExchangeServer; -import org.apache.dubbo.remoting.exchange.Exchangers; -import org.apache.dubbo.remoting.exchange.support.ExchangeHandlerAdapter; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Invocation; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.ProtocolServer; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.AbstractProtocol; -import org.apache.dubbo.rpc.protocol.dubbo.DubboExporter; - -import java.util.ArrayList; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.function.Function; - -import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; -import static org.apache.dubbo.remoting.Constants.CHANNEL_READONLYEVENT_SENT_KEY; -import static org.apache.dubbo.remoting.Constants.CLIENT_KEY; -import static org.apache.dubbo.remoting.Constants.CODEC_KEY; -import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY; -import static org.apache.dubbo.remoting.Constants.SERVER_KEY; -import static org.apache.dubbo.rpc.Constants.IS_SERVER_KEY; - -/** - * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead - */ -@Deprecated -public class ThriftProtocol extends AbstractProtocol { - - public static final int DEFAULT_PORT = 40880; - - public static final String NAME = "thrift"; - - private ExchangeHandler handler = new ExchangeHandlerAdapter() { - - @Override - public CompletableFuture reply(ExchangeChannel channel, Object msg) throws RemotingException { - - if (msg instanceof Invocation) { - Invocation inv = (Invocation) msg; - String path = (String) inv.getObjectAttachments().get(PATH_KEY); - String serviceKey = serviceKey(channel.getLocalAddress().getPort(), - path, 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()); - - Result result = exporter.getInvoker().invoke(inv); - return result.thenApply(Function.identity()); - } - - 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); - } - } - - }; - - @Override - public int getDefaultPort() { - return DEFAULT_PORT; - } - - @Override - public Exporter export(Invoker invoker) throws RpcException { - - // can use thrift codec only - URL url = invoker.getUrl().addParameter(CODEC_KEY, ThriftCodec.NAME); - // find server. - String key = url.getAddress(); - // client can expose a service for server to invoke only. - boolean isServer = url.getParameter(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; - } - - @Override - public void destroy() { - - super.destroy(); - - for (String key : new ArrayList(serverMap.keySet())) { - - ProtocolServer protocolServer = serverMap.remove(key); - - if (protocolServer != null) { - RemotingServer server = protocolServer.getRemotingServer(); - try { - if (logger.isInfoEnabled()) { - logger.info("Close dubbo server: " + server.getLocalAddress()); - } - server.close(ConfigurationUtils.getServerShutdownTimeout()); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } // ~ end of if ( server != null ) - - } // ~ end of loop serverMap - - } // ~ end of method destroy - - @Override - protected Invoker protocolBindingRefer(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(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(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 ProtocolServer getServer(URL url) { - // enable sending readonly event when server closes by default - url = url.addParameterIfAbsent(CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString()); - String str = url.getParameter(SERVER_KEY, org.apache.dubbo.rpc.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(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 new ThriftProtocolServer(server); - } - - private class ThriftProtocolServer implements ProtocolServer { - - private ExchangeServer server; - private String address; - - public ThriftProtocolServer(ExchangeServer server) { - this.server = server; - } - - @Override - public RemotingServer getRemotingServer() { - return server; - } - - @Override - public String getAddress() { - return StringUtils.isNotEmpty(address) ? address : server.getUrl().getAddress(); - } - - @Override - public void setAddress(String address) { - this.address = address; - } - - @Override - public URL getUrl() { - return server.getUrl(); - } - - @Override - public void reset(URL url) { - server.reset(url); - } - - @Override - public void close() { - server.close(); - } - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftType.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftType.java deleted file mode 100644 index 85ede89548..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftType.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import java.util.HashMap; -import java.util.Map; -/** - * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead - */ -@Deprecated -public enum ThriftType { - - BOOL, BYTE, I16, I32, I64, DOUBLE, STRING; - - private static final Map, ThriftType> TYPES = - new HashMap, ThriftType>(); - - static { - put(boolean.class, BOOL); - put(Boolean.class, BOOL); - put(byte.class, BYTE); - put(Byte.class, BYTE); - put(short.class, I16); - } - - public static ThriftType get(Class key) { - if (key != null) { - return TYPES.get(key); - } - throw new NullPointerException("key == null"); - } - - private static void put(Class key, ThriftType value) { - TYPES.put(key, value); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtils.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtils.java deleted file mode 100644 index cbba6a93dd..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtils.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; -/** - * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift instead - */ -@Deprecated -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, 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, 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, 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, 0, index + 1) - .append(methodName) - .append("_result") - .toString(); - } - - return null; - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java deleted file mode 100644 index bb3d818049..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/ext/MultiServiceProcessor.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift.ext; - -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.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; - -/** - * @since 2.7.0, use https://github.com/dubbo/dubbo-rpc-native-thrift to instead of this module - */ -@Deprecated -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() { - } - - @Override - public boolean process(TProtocol in, TProtocol out) throws TException { - - short magic = in.readI16(); - - if (magic != ThriftCodec.MAGIC) { - logger.error("Unsupported magic " + magic); - 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("Could not find processor for service " + serviceName); - 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/org/apache/dubbo/rpc/protocol/thrift/io/InputStreamWrapper.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/io/InputStreamWrapper.java deleted file mode 100644 index c1eb69dde7..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/io/InputStreamWrapper.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift.io; - -import java.io.IOException; -import java.io.InputStream; -@Deprecated -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/org/apache/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java b/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java deleted file mode 100644 index 660dd8031d..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/java/org/apache/dubbo/rpc/protocol/thrift/io/RandomAccessByteArrayOutputStream.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift.io; - -import org.apache.dubbo.common.io.Bytes; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -@Deprecated -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]; - } - - @Override - 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; - } - - @Override - 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); - } - - @Override - public String toString() { - - return new String(buffer, 0, count); - } - - public String toString(String charset) throws UnsupportedEncodingException { - - return new String(buffer, 0, count, charset); - } - - @Override - public void close() throws IOException { - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Codec2 b/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Codec2 deleted file mode 100644 index 600662d572..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.Codec2 +++ /dev/null @@ -1 +0,0 @@ -thrift=org.apache.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/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol deleted file mode 100644 index 3800f4cb9d..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -thrift=org.apache.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/org.apache.dubbo.rpc.protocol.thrift.ClassNameGenerator b/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.thrift.ClassNameGenerator deleted file mode 100644 index 18d912ec26..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.protocol.thrift.ClassNameGenerator +++ /dev/null @@ -1,2 +0,0 @@ -dubbo=org.apache.dubbo.rpc.protocol.thrift.DubboClassNameGenerator -thrift=org.apache.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 c7f92d7b5e..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/$__ClassNameTestDubboStub.java +++ /dev/null @@ -1,681 +0,0 @@ -/* - * 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. - */ -/* - * 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 org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Collections; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -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"); - } - - public echo_args getEmptyArgsInstance() { - return new echo_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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 { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - - 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); - } - - // isset id assignments - - public String arg; // required - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echo_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - - 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); - } - - // isset id assignments - - public String success; // required - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - -} 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 eb2cc55655..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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. - */ - -import org.apache.dubbo.rpc.protocol.thrift.ThriftUtils; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class ClassNameTest { - - @Test - public void testThriftUtils() { - - Assertions.assertEquals($__ClassNameTestDubboStub.echo_args.class.getName(), - ThriftUtils.generateMethodArgsClassName( - ClassNameTestDubbo.class.getName(), "echo")); - - Assertions.assertEquals($__ClassNameTestDubboStub.echo_result.class.getName(), - ThriftUtils.generateMethodResultClassName( - ClassNameTestDubbo.class.getName(), "echo")); - - Assertions.assertEquals(ClassNameTestThrift.echo_args.class.getName(), - ThriftUtils.generateMethodArgsClassNameThrift( - ClassNameTestThrift.Iface.class.getName(), "echo")); - - Assertions.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 5f4eaa560a..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestDubbo.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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. - */ -/* - * 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 - */ - -public interface ClassNameTestDubbo { - - 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 4a1a3bf212..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/ClassNameTestThrift.java +++ /dev/null @@ -1,767 +0,0 @@ -/** - * Autogenerated by Thrift Compiler (0.7.0) - *

    - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Collections; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -public class ClassNameTestThrift { - - public interface Iface { - - String echo(String arg) throws org.apache.thrift.TException; - - } - - public interface AsyncIface { - - 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 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 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 static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { - 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 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 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"); - } - - public echo_args getEmptyArgsInstance() { - return new echo_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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 { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - - 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); - } - - // isset id assignments - - public String arg; // required - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echo_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - - 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); - } - - // isset id assignments - - public String success; // required - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/$__DemoStub.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/$__DemoStub.java deleted file mode 100644 index 04b6353d72..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/$__DemoStub.java +++ /dev/null @@ -1,4347 +0,0 @@ -/* - * 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. - */ -/* - * 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 org.apache.dubbo.rpc.gen.dubbo; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.BitSet; -import java.util.Collections; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -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"); - } - - public echoBool_args getEmptyArgsInstance() { - return new echoBool_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoByte_args getEmptyArgsInstance() { - return new echoByte_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoI16_args getEmptyArgsInstance() { - return new echoI16_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoI32_args getEmptyArgsInstance() { - return new echoI32_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoI64_args getEmptyArgsInstance() { - return new echoI64_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoDouble_args getEmptyArgsInstance() { - return new echoDouble_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoString_args getEmptyArgsInstance() { - return new echoString_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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 { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 boolean arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoBool_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 boolean success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoByte_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 byte arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoByte_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 byte success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI16_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 short arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI16_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 short success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI32_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 int arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI32_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 int success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI64_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 long arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI64_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 long success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoDouble_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 double arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoDouble_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 double success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoString_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - - 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); - } - - // isset id assignments - - public String arg; // required - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoString_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - - 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); - } - - // isset id assignments - - public String success; // required - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/Demo.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/Demo.java deleted file mode 100644 index 08ab4190a2..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/dubbo/Demo.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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. - */ -/* - * 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 org.apache.dubbo.rpc.gen.dubbo; - -public interface Demo { - - boolean echoBool(boolean arg); - - byte echoByte(byte arg); - - short echoI16(short arg); - - int echoI32(int arg); - - long echoI64(long arg); - - double echoDouble(double arg); - - String echoString(String arg); - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/thrift/Demo.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/thrift/Demo.java deleted file mode 100644 index a1f76597a1..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/gen/thrift/Demo.java +++ /dev/null @@ -1,4753 +0,0 @@ -/** - * Autogenerated by Thrift Compiler (0.7.0) - *

    - * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING - */ -package org.apache.dubbo.rpc.gen.thrift; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.BitSet; -import java.util.Collections; -import java.util.EnumMap; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - -public class Demo { - - public interface Iface { - - boolean echoBool(boolean arg) throws org.apache.thrift.TException; - - byte echoByte(byte arg) throws org.apache.thrift.TException; - - short echoI16(short arg) throws org.apache.thrift.TException; - - int echoI32(int arg) throws org.apache.thrift.TException; - - long echoI64(long arg) throws org.apache.thrift.TException; - - double echoDouble(double arg) throws org.apache.thrift.TException; - - String echoString(String arg) throws org.apache.thrift.TException; - - } - - public interface AsyncIface { - - void echoBool(boolean arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - void echoByte(byte arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - void echoI16(short arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - void echoI32(int arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - void echoI64(long arg, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - void echoDouble(double arg, - org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException; - - 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 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 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 static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface { - 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 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 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 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 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 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 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 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 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 Object 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 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 Object 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 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 Object 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 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 Object 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 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 Object 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 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 Object 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 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"); - } - - public echoBool_args getEmptyArgsInstance() { - return new echoBool_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoByte_args getEmptyArgsInstance() { - return new echoByte_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoI16_args getEmptyArgsInstance() { - return new echoI16_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoI32_args getEmptyArgsInstance() { - return new echoI32_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoI64_args getEmptyArgsInstance() { - return new echoI64_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoDouble_args getEmptyArgsInstance() { - return new echoDouble_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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"); - } - - public echoString_args getEmptyArgsInstance() { - return new echoString_args(); - } - - @Override - protected boolean isOneway() { - return false; - } - - public 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 { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 boolean arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoBool_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 boolean success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoByte_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 byte arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoByte_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 byte success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI16_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 short arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI16_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 short success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI32_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 int arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI32_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 int success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI64_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 long arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoI64_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 long success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoDouble_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __ARG_ISSET_ID = 0; - - 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 double arg; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoDouble_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - // isset id assignments - private static final int __SUCCESS_ISSET_ID = 0; - - 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 double success; // required - private BitSet __isset_bit_vector = new BitSet(1); - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoString_args implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - - 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); - } - - // isset id assignments - - public String arg; // required - - 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); - } - } - - /** 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - - public static class echoString_result implements org.apache.thrift.TBase, java.io.Serializable, Cloneable { - public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; - 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); - - 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); - } - - // isset id assignments - - public String success; // required - - 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); - } - } - - /** - * 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); - } - } - - private final short _thriftId; - private final String _fieldName; - - _Fields(short thriftId, String fieldName) { - _thriftId = thriftId; - _fieldName = fieldName; - } - - /** - * 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); - } - - public short getThriftFieldId() { - return _thriftId; - } - - public String getFieldName() { - return _fieldName; - } - } - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/AbstractTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/AbstractTest.java deleted file mode 100644 index 52a549f609..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/AbstractTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.gen.dubbo.$__DemoStub; -import org.apache.dubbo.rpc.gen.dubbo.Demo; -import org.apache.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.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; - -public abstract class AbstractTest { - - protected int PORT = NetUtils.getAvailablePort(); - - protected TServer server; - - protected Protocol protocol; - - protected Invoker invoker; - - TServerTransport serverTransport; - - protected void init() throws Exception { - - 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; - } - - try { - if (serverTransport != null) { - // release port if used - serverTransport.close(); - } - } catch (Exception e) { - // ignore - } - - } - - protected TTransportFactory getTransportFactory() { - return new FramedTransportFactory(); - } - - protected $__DemoStub.Iface getServiceImpl() { - return new DubboDemoImpl(); - } - - protected TProcessor getProcessor() { - MultiServiceProcessor result = new MultiServiceProcessor(); - result.addProcessor( - org.apache.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()); - } - - @AfterEach - public void tearDown() throws Exception { - destroy(); - } - - @BeforeEach - public void setUp() throws Exception { - init(); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/DemoImpl.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/DemoImpl.java deleted file mode 100644 index 8737714603..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/DemoImpl.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -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/org/apache/dubbo/rpc/protocol/thrift/DubboDemoImpl.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/DubboDemoImpl.java deleted file mode 100644 index ce04d1a0c4..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/DubboDemoImpl.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.rpc.gen.dubbo.$__DemoStub; -import org.apache.dubbo.rpc.gen.dubbo.Demo; - -public class DubboDemoImpl extends DemoImpl implements Demo, $__DemoStub.Iface { -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/FramedTransportFactory.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/FramedTransportFactory.java deleted file mode 100644 index d48248d7e2..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/FramedTransportFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TTransport; -import org.apache.thrift.transport.TTransportFactory; - -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/org/apache/dubbo/rpc/protocol/thrift/MockedChannel.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/MockedChannel.java deleted file mode 100644 index c871db018f..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/MockedChannel.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.ChannelHandler; -import org.apache.dubbo.remoting.RemotingException; - -import java.net.InetSocketAddress; - -public class MockedChannel implements Channel { - - private URL url; - - public MockedChannel(URL url) { - this.url = url; - } - - @Override - public InetSocketAddress getRemoteAddress() { - - return null; - } - - @Override - public boolean isConnected() { - - return false; - } - - @Override - public boolean hasAttribute(String key) { - - return false; - } - - @Override - public Object getAttribute(String key) { - - return null; - } - - @Override - public void setAttribute(String key, Object value) { - - } - - @Override - public void removeAttribute(String key) { - - } - - @Override - public URL getUrl() { - return url; - } - - @Override - public ChannelHandler getChannelHandler() { - - return null; - } - - @Override - public InetSocketAddress getLocalAddress() { - - return null; - } - - @Override - public void send(Object message) throws RemotingException { - - } - - @Override - public void send(Object message, boolean sent) throws RemotingException { - - } - - @Override - public void close() { - - } - - @Override - public void close(int timeout) { - - } - - @Override - public void startClose() { - - } - - @Override - public boolean isClosed() { - - return false; - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServerExceptionTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServerExceptionTest.java deleted file mode 100644 index 0b9be90b02..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServerExceptionTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.Result; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.gen.dubbo.$__DemoStub; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -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) { - // On server side, thrift can not handle exceptions not declared in idl - throw new RuntimeException("just for test"); - } - }; - - } - - @Test - public void testServerException() throws Exception { - Assertions.assertThrows(RpcException.class, () -> { - Assertions.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/org/apache/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java deleted file mode 100644 index bb6857603e..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ServiceMethodNotFoundTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.rpc.gen.dubbo.$__DemoStub; -import org.apache.dubbo.rpc.gen.dubbo.Demo; -import org.apache.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.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Field; -import java.util.Map; - -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); - } - - } - - @BeforeEach - public void setUp() throws Exception { - - init(); - - protocol = new ThriftProtocol(); - - url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:" + PORT + "/" + Demo.class.getName()); - - } - - @AfterEach - 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.jupiter.api.Assertions.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 ); - - Assertions.assertNull( result.getResult() ); - - Assertions.assertTrue( result.getException() instanceof RpcException );*/ - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java deleted file mode 100644 index 9f6d7e098f..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftCodecTest.java +++ /dev/null @@ -1,477 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.Channel; -import org.apache.dubbo.remoting.buffer.ChannelBuffer; -import org.apache.dubbo.remoting.buffer.ChannelBuffers; -import org.apache.dubbo.remoting.exchange.Request; -import org.apache.dubbo.remoting.exchange.Response; -import org.apache.dubbo.remoting.exchange.support.DefaultFuture; -import org.apache.dubbo.rpc.AppResponse; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.RpcInvocation; -import org.apache.dubbo.rpc.gen.thrift.Demo; -import org.apache.dubbo.rpc.protocol.thrift.io.RandomAccessByteArrayOutputStream; - -import org.apache.thrift.TApplicationException; -import org.apache.thrift.protocol.TBinaryProtocol; -import org.apache.thrift.protocol.TMessage; -import org.apache.thrift.protocol.TMessageType; -import org.apache.thrift.transport.TFramedTransport; -import org.apache.thrift.transport.TIOStreamTransport; -import org.apache.thrift.transport.TTransport; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayInputStream; - -import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.PATH_KEY; - -public class ThriftCodecTest { - - private ThriftCodec codec = new ThriftCodec(); - private Channel channel = new MockedChannel(URL.valueOf("thrift://127.0.0.1")); - - 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; - } - - @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 - Assertions.assertEquals(ThriftCodec.MAGIC, protocol.readI16()); - - // message length - int messageLength = protocol.readI32(); - Assertions.assertEquals(messageLength + 4, bytes.length); - - // header length - short headerLength = protocol.readI16(); - // version - Assertions.assertEquals(ThriftCodec.VERSION, protocol.readByte()); - // service name - Assertions.assertEquals(Demo.Iface.class.getName(), protocol.readString()); - // path - Assertions.assertEquals(Demo.Iface.class.getName(), protocol.readString()); - // dubbo request id - Assertions.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(); - - Assertions.assertEquals("echoString", message.name); - - Assertions.assertEquals(TMessageType.CALL, message.type); - - Assertions.assertEquals("Hello, World!", args.getArg()); - - } - - @Test - public void testDecodeReplyResponse() throws Exception { - - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:" + port + "/" + Demo.Iface.class.getName()); - - Channel channel = new MockedChannel(url); - - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(128); - - Request request = createRequest(); - - DefaultFuture future = DefaultFuture.newFuture(channel, request, 10, null); - - 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()); - // path - 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); - - Assertions.assertNotNull(obj); - - Assertions.assertTrue(obj instanceof Response); - - Response response = (Response) obj; - - Assertions.assertEquals(request.getId(), response.getId()); - - Assertions.assertTrue(response.getResult() instanceof AppResponse); - - AppResponse result = (AppResponse) response.getResult(); - - Assertions.assertTrue(result.getValue() instanceof String); - - Assertions.assertEquals(methodResult.success, result.getValue()); - - } - - @Test - public void testDecodeExceptionResponse() throws Exception { - - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:" + port + "/" + Demo.class.getName()); - - Channel channel = new MockedChannel(url); - - RandomAccessByteArrayOutputStream bos = new RandomAccessByteArrayOutputStream(128); - - Request request = createRequest(); - - DefaultFuture future = DefaultFuture.newFuture(channel, request, 10, null); - - 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()); - // path - 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); - - Assertions.assertNotNull(obj); - - Assertions.assertTrue(obj instanceof Response); - - Response response = (Response) obj; - - Assertions.assertTrue(response.getResult() instanceof AppResponse); - - AppResponse result = (AppResponse) response.getResult(); - - Assertions.assertTrue(result.hasException()); - - Assertions.assertTrue(result.getException() instanceof RpcException); - - } - - @Test - public void testEncodeReplyResponse() throws Exception { - - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:" + port + "/" + Demo.Iface.class.getName()); - - Channel channel = new MockedChannel(url); - - Request request = createRequest(); - - AppResponse appResponse = new AppResponse(); - appResponse.setValue("Hello, World!"); - - Response response = new Response(); - response.setResult(appResponse); - response.setId(request.getId()); - ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024); - - ThriftCodec.RequestData rd = ThriftCodec.RequestData.create( - ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString"); - ThriftCodec.CACHED_REQUEST.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); - - Assertions.assertEquals(ThriftCodec.MAGIC, protocol.readI16()); - Assertions.assertEquals(protocol.readI32() + 4, bos.writerIndex()); - int headerLength = protocol.readI16(); - - Assertions.assertEquals(ThriftCodec.VERSION, protocol.readByte()); - Assertions.assertEquals(Demo.Iface.class.getName(), protocol.readString()); - Assertions.assertEquals(request.getId(), protocol.readI64()); - - if (bis.markSupported()) { - bis.reset(); - bis.skip(headerLength); - } - - TMessage message = protocol.readMessageBegin(); - Assertions.assertEquals("echoString", message.name); - Assertions.assertEquals(TMessageType.REPLY, message.type); - //Assertions.assertEquals(ThriftCodec.getSeqId(), message.seqid); - Demo.echoString_result result = new Demo.echoString_result(); - result.read(protocol); - protocol.readMessageEnd(); - - Assertions.assertEquals(appResponse.getValue(), result.getSuccess()); - } - - @Test - public void testEncodeExceptionResponse() throws Exception { - - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:" + port + "/" + Demo.Iface.class.getName()); - - Channel channel = new MockedChannel(url); - - Request request = createRequest(); - - AppResponse appResponse = new AppResponse(); - String exceptionMessage = "failed"; - appResponse.setException(new RuntimeException(exceptionMessage)); - - Response response = new Response(); - response.setResult(appResponse); - response.setId(request.getId()); - ChannelBuffer bos = ChannelBuffers.dynamicBuffer(1024); - - ThriftCodec.RequestData rd = ThriftCodec.RequestData.create( - ThriftCodec.getSeqId(), Demo.Iface.class.getName(), "echoString"); - ThriftCodec.CACHED_REQUEST.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); - - Assertions.assertEquals(ThriftCodec.MAGIC, protocol.readI16()); - Assertions.assertEquals(protocol.readI32() + 4, bos.writerIndex()); - int headerLength = protocol.readI16(); - - Assertions.assertEquals(ThriftCodec.VERSION, protocol.readByte()); - Assertions.assertEquals(Demo.Iface.class.getName(), protocol.readString()); - Assertions.assertEquals(request.getId(), protocol.readI64()); - - if (bis.markSupported()) { - bis.reset(); - bis.skip(headerLength); - } - - TMessage message = protocol.readMessageBegin(); - Assertions.assertEquals("echoString", message.name); - Assertions.assertEquals(TMessageType.EXCEPTION, message.type); - Assertions.assertEquals(ThriftCodec.getSeqId(), message.seqid); - TApplicationException exception = TApplicationException.readFrom(protocol); - protocol.readMessageEnd(); - - Assertions.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(INTERFACE_KEY)); - protocol.writeString( - ((RpcInvocation) request.getData()) - .getAttachment(PATH_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()))); - - Assertions.assertTrue(obj instanceof Request); - - obj = ((Request) obj).getData(); - - Assertions.assertTrue(obj instanceof RpcInvocation); - - RpcInvocation invocation = (RpcInvocation) obj; - - Assertions.assertEquals("echoString", invocation.getMethodName()); - Assertions.assertArrayEquals(new Class[]{String.class}, invocation.getParameterTypes()); - Assertions.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(INTERFACE_KEY, Demo.Iface.class.getName()); - invocation.setAttachment(PATH_KEY, Demo.Iface.class.getName()); - - Request request = new Request(1L); - - request.setData(invocation); - - return request; - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftDemoImpl.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftDemoImpl.java deleted file mode 100644 index 7c561adb1e..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftDemoImpl.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.rpc.gen.thrift.Demo; - -public class ThriftDemoImpl extends DemoImpl implements Demo.Iface { -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java deleted file mode 100644 index 967b77abcd..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftProtocolTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.gen.dubbo.Demo; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; - -public class ThriftProtocolTest extends AbstractTest { - - public final int DEFAULT_PORT = NetUtils.getAvailablePort(); - - private ThriftProtocol protocol; - - private Invoker invoker; - - private URL url; - - @BeforeEach - public void setUp() throws Exception { - - init(); - - protocol = new ThriftProtocol(); - - url = URL.valueOf(ThriftProtocol.NAME + "://127.0.0.1:" + PORT + "/" + Demo.class.getName()); - - } - - @AfterEach - 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 ); - - Assertions.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 ); - - Assertions.assertEquals( arg, result.getResult() );*//* - - }*/ - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java deleted file mode 100644 index 9a0e2b4cbe..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/ThriftUtilsTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift; - -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.rpc.gen.dubbo.$__DemoStub; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -public class ThriftUtilsTest { - - @Test - public void testGenerateMethodArgsClassName() { - - Assertions.assertEquals( - $__DemoStub.echoString_args.class.getName(), - ThriftUtils.generateMethodArgsClassName( - org.apache.dubbo.rpc.gen.dubbo.Demo.class.getName(), - "echoString")); - - Assertions.assertEquals( - $__DemoStub.echoString_args.class.getName(), - ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) - .getExtension(DubboClassNameGenerator.NAME).generateArgsClassName( - org.apache.dubbo.rpc.gen.dubbo.Demo.class.getName(), "echoString")); - - } - - @Test - public void testGenerateMethodResultClassName() { - - Assertions.assertEquals($__DemoStub.echoString_result.class.getName(), - ThriftUtils.generateMethodResultClassName( - org.apache.dubbo.rpc.gen.dubbo.Demo.class.getName(), - "echoString")); - - Assertions.assertEquals($__DemoStub.echoString_result.class.getName(), - ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) - .getExtension(DubboClassNameGenerator.NAME).generateResultClassName( - org.apache.dubbo.rpc.gen.dubbo.Demo.class.getName(), "echoString")); - - } - - @Test - public void testGenerateMethodArgsClassNameThrift() { - Assertions.assertEquals(org.apache.dubbo.rpc.gen.thrift.Demo.echoString_args.class.getName(), - ThriftUtils.generateMethodArgsClassNameThrift( - org.apache.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString")); - - Assertions.assertEquals(org.apache.dubbo.rpc.gen.thrift.Demo.echoString_args.class.getName(), - ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) - .getExtension(ThriftClassNameGenerator.NAME).generateArgsClassName( - org.apache.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString")); - - } - - @Test - public void testGenerateMethodResultClassNameThrift() { - Assertions.assertEquals(org.apache.dubbo.rpc.gen.thrift.Demo.echoString_result.class.getName(), - ThriftUtils.generateMethodResultClassNameThrift( - org.apache.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString")); - - Assertions.assertEquals(org.apache.dubbo.rpc.gen.thrift.Demo.echoString_result.class.getName(), - ExtensionLoader.getExtensionLoader(ClassNameGenerator.class) - .getExtension(ThriftClassNameGenerator.NAME).generateResultClassName( - org.apache.dubbo.rpc.gen.thrift.Demo.Iface.class.getName(), - "echoString")); - - } - -} diff --git a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java deleted file mode 100644 index a631cdd59e..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoConsumer.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift.examples; - -import org.apache.dubbo.rpc.gen.thrift.Demo; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -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/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoProvider.java b/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoProvider.java deleted file mode 100644 index d87be9de13..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/java/org/apache/dubbo/rpc/protocol/thrift/examples/DubboDemoProvider.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.thrift.examples; - -import org.springframework.context.support.ClassPathXmlApplicationContext; - -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 3dccf35dbe..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-consumer.xml +++ /dev/null @@ -1,32 +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 cf375c5551..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/resources/dubbo-demo-provider.xml +++ /dev/null @@ -1,34 +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 3e2023a9e1..0000000000 --- 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 ccac7a1e0a..0000000000 --- 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 8e66074a1d..0000000000 --- a/dubbo-rpc/dubbo-rpc-thrift/src/test/thrift/Demo.thrift +++ /dev/null @@ -1,16 +0,0 @@ -namespace dubbo_java org.apache.dubbo.rpc.gen.dubbo -namespace dubbo_cpp org.apache.dubbo.rpc.gen.dubbo - -namespace java org.apache.dubbo.rpc.gen.thrift -namespace cpp org.apache.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-webservice/pom.xml b/dubbo-rpc/dubbo-rpc-webservice/pom.xml deleted file mode 100644 index ff08b3804b..0000000000 --- a/dubbo-rpc/dubbo-rpc-webservice/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - dubbo-rpc-webservice - jar - ${project.artifactId} - The webservice rpc module of dubbo project - - false - - - - org.apache.dubbo - dubbo-rpc-api - ${project.parent.version} - - - org.apache.dubbo - dubbo-remoting-http - ${project.parent.version} - - - javax.xml.bind - jaxb-api - - - com.sun.xml.bind - jaxb-impl - - - com.sun.xml.bind - jaxb-core - - - javax.activation - javax.activation-api - - - com.sun.activation - javax.activation - - - org.apache.cxf - cxf-rt-frontend-simple - - - org.apache.cxf - cxf-rt-transports-http - - - org.springframework - spring-context - - - - \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java b/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java deleted file mode 100644 index 6e40d30af7..0000000000 --- a/dubbo-rpc/dubbo-rpc-webservice/src/main/java/org/apache/dubbo/rpc/protocol/webservice/WebServiceProtocol.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.webservice; - -import org.apache.cxf.binding.soap.SoapTransportFactory; -import org.apache.cxf.common.util.StringUtils; -import org.apache.cxf.endpoint.Server; -import org.apache.cxf.service.model.OperationInfo; -import org.apache.cxf.transport.Destination; - -import org.apache.cxf.transport.http.HTTPConduit; -import org.apache.cxf.transport.http.AbstractHTTPDestination; -import org.apache.cxf.transport.http.DestinationRegistry; -import org.apache.cxf.transport.http.DestinationRegistryImpl; -import org.apache.cxf.transport.http.HttpDestinationFactory; -import org.apache.cxf.wsdl.service.factory.AbstractServiceConfiguration; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.Constants; -import org.apache.dubbo.remoting.RemotingServer; -import org.apache.dubbo.remoting.http.HttpBinder; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.remoting.http.servlet.DispatcherServlet; -import org.apache.dubbo.rpc.ProtocolServer; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; - -import org.apache.cxf.bus.extension.ExtensionManagerBus; -import org.apache.cxf.endpoint.Client; -import org.apache.cxf.frontend.ClientProxy; -import org.apache.cxf.frontend.ClientProxyFactoryBean; -import org.apache.cxf.frontend.ServerFactoryBean; -import org.apache.cxf.interceptor.Fault; -import org.apache.cxf.transport.servlet.ServletController; -import org.apache.cxf.transport.servlet.ServletDestinationFactory; -import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; - -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.lang.reflect.Method; -import java.net.SocketTimeoutException; - -import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_PATH_PREFIX; -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT; -import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_SERVER; -import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_SERVER_SERVLET; -import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY; - -/** - * WebServiceProtocol. - */ -public class WebServiceProtocol extends AbstractProxyProtocol { - - public static final int DEFAULT_PORT = 80; - - private final ExtensionManagerBus bus = new ExtensionManagerBus(); - - private SoapTransportFactory transportFactory = null; - - private ServerFactoryBean serverFactoryBean = null; - - private DestinationRegistry destinationRegistry=null; - - private HttpBinder httpBinder; - - private Server server = null; - - public WebServiceProtocol() { - super(Fault.class); - bus.setExtension(new ServletDestinationFactory(), HttpDestinationFactory.class); - } - - public void setHttpBinder(HttpBinder httpBinder) { - this.httpBinder = httpBinder; - } - - @Override - public int getDefaultPort() { - return DEFAULT_PORT; - } - - - @Override - protected Runnable doExport(T impl, Class type, URL url) throws RpcException { - transportFactory = new SoapTransportFactory(); - destinationRegistry = new DestinationRegistryImpl(); - String addr = getAddr(url); - ProtocolServer protocolServer = serverMap.get(addr); - if (protocolServer == null) { - RemotingServer remotingServer = httpBinder.bind(url, new WebServiceHandler()); - serverMap.put(addr, new ProxyProtocolServer(remotingServer)); - } - serverFactoryBean = new ServerFactoryBean(); - serverFactoryBean.setAddress(url.getAbsolutePath()); - serverFactoryBean.setServiceClass(type); - serverFactoryBean.setServiceBean(impl); - serverFactoryBean.setBus(bus); - serverFactoryBean.setDestinationFactory(transportFactory); - serverFactoryBean.getServiceFactory().getConfigurations().add(new URLHashMethodNameSoapActionServiceConfiguration()); - server = serverFactoryBean.create(); - return new Runnable() { - @Override - public void run() { - if(serverFactoryBean.getServer()!= null) { - serverFactoryBean.getServer().destroy(); - } - if(serverFactoryBean.getBus()!=null) { - serverFactoryBean.getBus().shutdown(true); - } - ProtocolServer httpServer = serverMap.get(addr); - if(httpServer != null){ - httpServer.close(); - serverMap.remove(addr); - } - } - }; - } - - @Override - @SuppressWarnings("unchecked") - protected T doRefer(final Class serviceType, URL url) throws RpcException { - ClientProxyFactoryBean proxyFactoryBean = new ClientProxyFactoryBean(); - String servicePathPrefix = url.getParameter(SERVICE_PATH_PREFIX); - if (!StringUtils.isEmpty(servicePathPrefix) && PROTOCOL_SERVER_SERVLET.equals(url.getParameter(PROTOCOL_SERVER))) { - url = url.setPath(servicePathPrefix + "/" + url.getPath()); - } - 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(TIMEOUT_KEY, DEFAULT_TIMEOUT)); - conduit.setClient(policy); - return ref; - } - - @Override - protected int getErrorCode(Throwable e) { - if (e instanceof Fault) { - e = e.getCause(); - } - if (e instanceof SocketTimeoutException) { - return RpcException.TIMEOUT_EXCEPTION; - } else if (e instanceof IOException) { - return RpcException.NETWORK_EXCEPTION; - } - return super.getErrorCode(e); - } - - private class WebServiceHandler implements HttpHandler { - - private volatile ServletController servletController; - - @Override - 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) { - - if(server == null){ - server = WebServiceProtocol.this.serverFactoryBean.getServer(); - } - Destination d = WebServiceProtocol.this.transportFactory.getDestination(server.getEndpoint().getEndpointInfo(),bus); - destinationRegistry.addDestination((AbstractHTTPDestination) d); - this.servletController = new ServletController(destinationRegistry, httpServlet.getServletConfig(), httpServlet); - } - } - } - RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); - servletController.invoke(request, response); - } - - } - - private class URLHashMethodNameSoapActionServiceConfiguration extends AbstractServiceConfiguration { - public String getAction(OperationInfo op, Method method) { - String uri = op.getName().getNamespaceURI(); - String action = op.getName().getLocalPart(); - if (StringUtils.isEmpty(action)) { - action = method.getName(); - } - return uri+"#"+action; - } - } - -} diff --git a/dubbo-rpc/dubbo-rpc-webservice/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-webservice/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol deleted file mode 100644 index fbebc4dd35..0000000000 --- a/dubbo-rpc/dubbo-rpc-webservice/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -webservice=org.apache.dubbo.rpc.protocol.webservice.WebServiceProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/DemoService.java b/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/DemoService.java deleted file mode 100644 index d66e86d385..0000000000 --- a/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/DemoService.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.webservice; - -/** - * TestService - */ - -public interface DemoService { - void sayHello(String name); - - String echo(String text); - - long timestamp(); - - void throwTimeout(); - - String getThreadName(); - - int getSize(String[] strs); - - int getSize(Object[] os); - - Object invoke(String service, String method) throws Exception; - - int stringLength(String str); - - User create(int age, String name); -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/DemoServiceImpl.java b/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/DemoServiceImpl.java deleted file mode 100644 index e9b5fc1b61..0000000000 --- a/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/DemoServiceImpl.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.webservice; - -import org.apache.dubbo.rpc.RpcContext; - -/** - * DemoServiceImpl - */ - -public class DemoServiceImpl implements DemoService { - public DemoServiceImpl() { - super(); - } - - public void sayHello(String name) { - System.out.println("hello " + name); - } - - public String echo(String text) { - return text; - } - - public long timestamp() { - return System.currentTimeMillis(); - } - - public String getThreadName() { - return Thread.currentThread().getName(); - } - - public int getSize(String[] strs) { - if (strs == null) - return -1; - return strs.length; - } - - public int getSize(Object[] os) { - if (os == null) - return -1; - return os.length; - } - - public Object invoke(String service, String method) throws Exception { - System.out.println("RpcContext.getContext().getRemoteHost()=" + RpcContext.getContext().getRemoteHost()); - return service + ":" + method; - } - - public User create(int age, String name){ - User user = new User(); - user.setAge(age); - user.setName(name); - return user; - } - - public int stringLength(String str) { - return str.length(); - } - - public void throwTimeout() { - try { - Thread.sleep(6000); - } catch (InterruptedException e) { - } - } -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/User.java b/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/User.java deleted file mode 100644 index 9fc2dc2c2a..0000000000 --- a/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/User.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.webservice; - -public class User { - private int age; - private String name; - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/WebserviceProtocolTest.java b/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/WebserviceProtocolTest.java deleted file mode 100644 index da18ba4960..0000000000 --- a/dubbo-rpc/dubbo-rpc-webservice/src/test/java/org/apache/dubbo/rpc/protocol/webservice/WebserviceProtocolTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * 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.apache.dubbo.rpc.protocol.webservice; - -import org.apache.catalina.Context; -import org.apache.catalina.LifecycleException; -import org.apache.catalina.connector.Connector; -import org.apache.catalina.startup.Tomcat; -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.URLBuilder; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.remoting.http.servlet.DispatcherServlet; -import org.apache.dubbo.remoting.http.servlet.ServletManager; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; - -import org.junit.jupiter.api.Test; - -import java.io.File; - -import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_PATH_PREFIX; -import static org.junit.jupiter.api.Assertions.assertEquals; - - -/** - * - */ - -public class WebserviceProtocolTest { - private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - - @Test - public void testDemoProtocol() throws Exception { - DemoService service = new DemoServiceImpl(); - int port = NetUtils.getAvailablePort(); - Exporter exporter = protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("webservice://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange"))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("webservice://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?codec=exchange&timeout=3000"))); - assertEquals(service.getSize(new String[]{"", "", ""}), 3); - exporter.unexport(); - } - - @Test - public void testWebserviceProtocol() throws Exception { - DemoService service = new DemoServiceImpl(); - int port = NetUtils.getAvailablePort(); - protocol.export(proxy.getInvoker(service, DemoService.class, URL.valueOf("webservice://127.0.0.1:" + port + "/" + DemoService.class.getName()))); - service = proxy.getProxy(protocol.refer(DemoService.class, URL.valueOf("webservice://127.0.0.1:" + port + "/" + DemoService.class.getName() + "?timeout=3000"))); - assertEquals(service.create(1, "kk").getName(), "kk"); - assertEquals(service.getSize(null), -1); - assertEquals(service.getSize(new String[]{"", "", ""}), 3); - Object object = service.invoke("webservice://127.0.0.1:" + port + "/" + DemoService.class.getName() + "", "invoke"); - System.out.println(object); - assertEquals("webservice://127.0.0.1:" + port + "/org.apache.dubbo.rpc.protocol.webservice.DemoService:invoke", object); - - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < 1024 * 32 + 32; i++) - buf.append('A'); - assertEquals(32800, service.stringLength(buf.toString())); - -// a method start with $ is illegal in soap -// // cast to EchoService -// EchoService echo = proxy.getProxy(protocol.refer(EchoService.class, URL.valueOf("webservice://127.0.0.1:9010/" + DemoService.class.getName() + "?client=netty"))); -// assertEquals(echo.echo(buf.toString()), buf.toString()); -// assertEquals(echo.$echo("test"), "test"); -// assertEquals(echo.$echo("abcdefg"), "abcdefg"); -// assertEquals(echo.$echo(1234), 1234); - } - - @Test - public void testWebserviceServlet() throws LifecycleException { - int port = 55065; - Tomcat tomcat = buildTomcat("/dubbo-webservice", "/services/*", port); - DemoService service = new DemoServiceImpl(); - - - URLBuilder builder = new URLBuilder() - .setProtocol("webservice") - .setHost("127.0.0.1") - .setPort(port) - .setPath("dubbo-webservice2/" + DemoService.class.getName()) - .addParameter("server", "servlet") - .addParameter("bind.port", 55065) - .addParameter("contextpath", "dubbo-webservice2") - .addParameter(SERVICE_PATH_PREFIX, "dubbo-webservice/services") - .addParameter("codec", "exchange") - .addParameter("timeout", 600000); - URL url = builder.build(); - - tomcat.start(); - Exporter exporter = protocol.export(proxy.getInvoker(service, DemoService.class, url)); - service = proxy.getProxy(protocol.refer(DemoService.class, url)); - assertEquals(service.getSize(new String[]{"", "", ""}), 3); - exporter.unexport(); - tomcat.stop(); - tomcat.destroy(); - } - - @Test - public void testWebserviceJetty() throws LifecycleException { - Tomcat tomcat = buildTomcat("/dubbo-webservice", "/services/*", 55065); - DemoService service = new DemoServiceImpl(); - int port = 55066; - - URLBuilder builder = new URLBuilder() - .setProtocol("webservice") - .setHost("127.0.0.1") - .setPort(port) - .setPath("dubbo-webservice3/" + DemoService.class.getName()) - .addParameter("server", "jetty") - .addParameter("bind.port", 55066) - .addParameter("contextpath", "dubbo-webservice2") - .addParameter("codec", "exchange") - .addParameter("timeout", 3000); - URL url = builder.build(); - - tomcat.start(); - Exporter exporter = protocol.export(proxy.getInvoker(service, DemoService.class, url)); - service = proxy.getProxy(protocol.refer(DemoService.class, url)); - assertEquals(service.getSize(new String[]{"", "", ""}), 3); - exporter.unexport(); - tomcat.stop(); - tomcat.destroy(); - } - - private Tomcat buildTomcat(String servicePathPrefix, String servletPattern, int port) { - String baseDir = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath(); - - Tomcat tomcat = new Tomcat(); - Connector connector = tomcat.getConnector(); - connector.setPort(port); - connector.setProperty("maxThreads", "5"); - connector.setProperty("maxConnections", "-1"); - connector.setProperty("URIEncoding", "UTF-8"); - connector.setProperty("connectionTimeout", "60000"); - connector.setProperty("maxKeepAliveRequests", "-1"); - - tomcat.setBaseDir(baseDir); - tomcat.setPort(port); - - Context context = tomcat.addContext(servicePathPrefix, baseDir); - Tomcat.addServlet(context, "dispatcher", new DispatcherServlet()); - - context.addServletMappingDecoded(servletPattern, "dispatcher"); - ServletManager.getInstance().addServletContext(port, context.getServletContext()); - - // tell tomcat to fail on startup failures. - System.setProperty("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true"); - return tomcat; - } -} diff --git a/dubbo-rpc/dubbo-rpc-xml/README.md b/dubbo-rpc/dubbo-rpc-xml/README.md deleted file mode 100644 index 67cec24638..0000000000 --- a/dubbo-rpc/dubbo-rpc-xml/README.md +++ /dev/null @@ -1,88 +0,0 @@ - -dubbo-rpc-xmlrpc -===================== -A RPC Extension for XML-RPC(http://ws.apache.org/xmlrpc) - -## Maven dependency: -```xml - - org.apache.dubbo - dubbo-rpc - 2.7.3-SNAPSHOT - - -``` - -## Configure: -Define xmlrpc protocol: -```xml - -``` - -Set default protocol: -```xml - -``` - -Set service protocol: -```xml - -``` - -Multi port: -```xml - - -``` -Multi protocol: -```xml - - -``` - -```xml - -``` - - -Jetty Server: (default) -```xml - - -Or Jetty9: - - -``` -Maven: -```xml - - org.mortbay.jetty - jetty - 6.1.26 - -``` - -Servlet Bridge Server: (recommend) -```xml - - -``` - -web.xml: -```xml - - dubbo - com.alibaba.dubbo.remoting.http.servlet.DispatcherServlet - 1 - - - dubbo - /* - -``` -Cors support: -```xml - - - -``` diff --git a/dubbo-rpc/dubbo-rpc-xml/pom.xml b/dubbo-rpc/dubbo-rpc-xml/pom.xml deleted file mode 100644 index bd45e0fe22..0000000000 --- a/dubbo-rpc/dubbo-rpc-xml/pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - 4.0.0 - - - org.apache.dubbo - dubbo-rpc - ${revision} - ../pom.xml - - - dubbo-rpc-xml - jar - ${project.artifactId} - The xml rpc module of dubbo project - - 3.1.3 - 1.8 - 1.8 - UTF-8 - UTF-8 - false - - https://github.com/apache/dubbo - - - - org.apache.xmlrpc - xmlrpc-server - ${xmlrpc_version} - - - - org.apache.xmlrpc - xmlrpc-client - ${xmlrpc_version} - - - - org.apache.dubbo - dubbo-remoting-http - ${project.parent.version} - - - - org.apache.dubbo - dubbo-compatible - ${project.parent.version} - - - - diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java deleted file mode 100644 index 3db0780f55..0000000000 --- a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocol.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * 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.apache.dubbo.xml.rpc.protocol.xmlrpc; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.remoting.RemotingServer; -import org.apache.dubbo.remoting.http.HttpBinder; -import org.apache.dubbo.remoting.http.HttpHandler; -import org.apache.dubbo.rpc.ProtocolServer; -import org.apache.dubbo.rpc.RpcContext; -import org.apache.dubbo.rpc.RpcException; -import org.apache.dubbo.rpc.protocol.AbstractProxyProtocol; - -import org.apache.xmlrpc.XmlRpcException; -import org.apache.xmlrpc.XmlRpcRequest; -import org.apache.xmlrpc.server.PropertyHandlerMapping; -import org.apache.xmlrpc.server.RequestProcessorFactoryFactory; -import org.apache.xmlrpc.server.XmlRpcServerConfigImpl; -import org.apache.xmlrpc.webserver.XmlRpcServletServer; -import org.springframework.remoting.RemoteAccessException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.ArrayList; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -public class XmlRpcProtocol extends AbstractProxyProtocol { - - public static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER = "Access-Control-Allow-Origin"; - public static final String ACCESS_CONTROL_ALLOW_METHODS_HEADER = "Access-Control-Allow-Methods"; - public static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER = "Access-Control-Allow-Headers"; - - private final Map skeletonMap = new ConcurrentHashMap<>(); - - private HttpBinder httpBinder; - - public XmlRpcProtocol() { - super(XmlRpcException.class); - } - - public void setHttpBinder(HttpBinder httpBinder) { - this.httpBinder = httpBinder; - } - - @Override - public int getDefaultPort() { - return 80; - } - - private class InternalHandler implements HttpHandler { - - private boolean cors; - - public InternalHandler(boolean cors) { - this.cors = cors; - } - - @Override - public void handle(HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException { - String uri = request.getRequestURI(); - XmlRpcServletServer xmlrpc = skeletonMap.get(uri); - if (cors) { - response.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*"); - response.setHeader(ACCESS_CONTROL_ALLOW_METHODS_HEADER, "POST"); - response.setHeader(ACCESS_CONTROL_ALLOW_HEADERS_HEADER, "*"); - } - if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { - response.setStatus(200); - } else if ("POST".equalsIgnoreCase(request.getMethod())) { - - RpcContext.getContext().setRemoteAddress(request.getRemoteAddr(), request.getRemotePort()); - try { - xmlrpc.execute(request, response); - } catch (Throwable e) { - throw new ServletException(e); - } - } else { - response.setStatus(500); - } - } - - } - - @Override - protected Runnable doExport(T impl, Class type, URL url) throws RpcException { - final URL httpUrl = url.setProtocol("http"); - String addr = httpUrl.getIp() + ":" + httpUrl.getPort(); - ProtocolServer protocolServer = serverMap.get(addr); - if (protocolServer == null) { - RemotingServer remotingServer = httpBinder.bind(httpUrl, new InternalHandler(httpUrl.getParameter("cors", false))); - serverMap.put(addr, new ProxyProtocolServer(remotingServer)); - } - final String path = httpUrl.getAbsolutePath(); - - XmlRpcServletServer xmlRpcServer = new XmlRpcServletServer(); - - PropertyHandlerMapping propertyHandlerMapping = new PropertyHandlerMapping(); - try { - - propertyHandlerMapping.setRequestProcessorFactoryFactory(new RequestProcessorFactoryFactory() { - @Override - public RequestProcessorFactory getRequestProcessorFactory(Class pClass) throws XmlRpcException { - return new RequestProcessorFactory() { - @Override - public Object getRequestProcessor(XmlRpcRequest pRequest) throws XmlRpcException { - return impl; - } - }; - } - }); - - propertyHandlerMapping.addHandler(XmlRpcProxyFactoryBean.replace(type.getName()), type); - - } catch (Exception e) { - throw new RpcException(e); - } - xmlRpcServer.setHandlerMapping(propertyHandlerMapping); - - XmlRpcServerConfigImpl xmlRpcServerConfig = (XmlRpcServerConfigImpl) xmlRpcServer.getConfig(); - xmlRpcServerConfig.setEnabledForExceptions(true); - xmlRpcServerConfig.setContentLengthOptional(false); - - skeletonMap.put(path, xmlRpcServer); - return new Runnable() { - @Override - public void run() { - skeletonMap.remove(path); - } - }; - } - - @Override - protected T doRefer(final Class serviceType, URL url) throws RpcException { - @SuppressWarnings("unchecked") - XmlRpcProxyFactoryBean xmlRpcProxyFactoryBean = new XmlRpcProxyFactoryBean(); - xmlRpcProxyFactoryBean.setServiceUrl(url.setProtocol("http").toIdentityString()); - xmlRpcProxyFactoryBean.setServiceInterface(serviceType); - xmlRpcProxyFactoryBean.afterPropertiesSet(); - return (T) xmlRpcProxyFactoryBean.getObject(); - } - - @Override - protected int getErrorCode(Throwable e) { - if (e instanceof RemoteAccessException) { - e = e.getCause(); - } - if (e != null) { - Class cls = e.getClass(); - 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 super.getErrorCode(e); - } - - @Override - public void destroy() { - super.destroy(); - for (String key : new ArrayList<>(serverMap.keySet())) { - ProtocolServer server = serverMap.remove(key); - if (server != null) { - try { - if (logger.isInfoEnabled()) { - logger.info("Close xml server " + server.getUrl()); - } - server.close(); - } catch (Throwable t) { - logger.warn(t.getMessage(), t); - } - } - } - } -} diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java b/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java deleted file mode 100644 index 18419c130e..0000000000 --- a/dubbo-rpc/dubbo-rpc-xml/src/main/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProxyFactoryBean.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * 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.apache.dubbo.xml.rpc.protocol.xmlrpc; - -import org.apache.dubbo.rpc.RpcException; - -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; -import org.apache.xmlrpc.client.XmlRpcClient; -import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; -import org.springframework.aop.framework.ProxyFactory; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.remoting.support.UrlBasedRemoteAccessor; - -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.net.MalformedURLException; -import java.net.URL; - -public class XmlRpcProxyFactoryBean extends UrlBasedRemoteAccessor - implements MethodInterceptor, - InitializingBean, - FactoryBean, - ApplicationContextAware { - - private Object proxyObject = null; - private XmlRpcClient xmlRpcClient = null; -// private Map extraHttpHeaders = new HashMap(); - - - private ApplicationContext applicationContext; - - /** - * {@inheritDoc} - */ - @Override - @SuppressWarnings("unchecked") - public void afterPropertiesSet() { - super.afterPropertiesSet(); - - // create proxy - proxyObject = ProxyFactory.getProxy(getServiceInterface(), this); - - // create XmlRpcHttpClient - try { - xmlRpcClient = new XmlRpcClient(); - - XmlRpcClientConfigImpl xmlRpcClientConfig = new XmlRpcClientConfigImpl(); - xmlRpcClientConfig.setServerURL(new URL(getServiceUrl())); - xmlRpcClient.setConfig(xmlRpcClientConfig); - - } catch (MalformedURLException mue) { - throw new RpcException(mue); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Object invoke(MethodInvocation invocation) - throws Throwable { - - // handle toString() - Method method = invocation.getMethod(); - if (method.getDeclaringClass() == Object.class && "toString".equals(method.getName())) { - return proxyObject.getClass().getName() + "@" + System.identityHashCode(proxyObject); - } - - // get return type - Type retType = (invocation.getMethod().getGenericReturnType() != null) - ? invocation.getMethod().getGenericReturnType() - : invocation.getMethod().getReturnType(); - - return xmlRpcClient.execute(replace(method.getDeclaringClass().getName())+"." - +invocation.getMethod().getName(),invocation.getArguments()); - -// // get arguments -// Object arguments = ReflectionUtil.parseArguments( -// invocation.getMethod(), invocation.getArguments(), useNamedParams); -// -// // invoke it -// return jsonRpcHttpClient.invoke( -// invocation.getMethod().getName(), -// arguments, -// retType, extraHttpHeaders); - } - - /** - * {@inheritDoc} - */ - @Override - public Object getObject() { - return proxyObject; - } - - /** - * {@inheritDoc} - */ - @Override - public Class getObjectType() { - return getServiceInterface(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isSingleton() { - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public void setApplicationContext(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - public static final String replace(String name) { - return name.replaceAll("\\.","_"); - } - -} diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder b/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder deleted file mode 100644 index e9453f2021..0000000000 --- a/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.remoting.http.HttpBinder +++ /dev/null @@ -1 +0,0 @@ -jetty9=org.apache.dubbo.remoting.http.jetty.JettyHttpBinder \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol b/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol deleted file mode 100644 index d2f1ce82cb..0000000000 --- a/dubbo-rpc/dubbo-rpc-xml/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.rpc.Protocol +++ /dev/null @@ -1 +0,0 @@ -xmlrpc=org.apache.dubbo.xml.rpc.protocol.xmlrpc.XmlRpcProtocol \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocolTest.java b/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocolTest.java deleted file mode 100644 index 3c67918fa2..0000000000 --- a/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcProtocolTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * 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.apache.dubbo.xml.rpc.protocol.xmlrpc; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.extension.ExtensionLoader; -import org.apache.dubbo.common.utils.NetUtils; -import org.apache.dubbo.rpc.Exporter; -import org.apache.dubbo.rpc.Invoker; -import org.apache.dubbo.rpc.Protocol; -import org.apache.dubbo.rpc.ProxyFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - - -public class XmlRpcProtocolTest { - - @Test - public void testXmlRpcProtocol() { - XmlRpcServiceImpl server = new XmlRpcServiceImpl(); - Assertions.assertFalse(server.isCalled()); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("xmlrpc://127.0.0.1:" + port + "/" + XmlRpcService.class.getName() + "?version=1.0.0"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, XmlRpcService.class, url)); - Invoker invoker = protocol.refer(XmlRpcService.class, url); - XmlRpcService client = proxyFactory.getProxy(invoker); - String result = client.sayHello("haha"); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - public void testXmlRpcProtocolForServerJetty9() { - XmlRpcServiceImpl server = new XmlRpcServiceImpl(); - Assertions.assertFalse(server.isCalled()); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("xmlrpc://127.0.0.1:" + port + "/" + XmlRpcService.class.getName() + "?version=1.0.0&server=jetty9"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, XmlRpcService.class, url)); - Invoker invoker = protocol.refer(XmlRpcService.class, url); - XmlRpcService client = proxyFactory.getProxy(invoker); - String result = client.sayHello("haha"); - Assertions.assertTrue(server.isCalled()); - Assertions.assertEquals("Hello, haha", result); - invoker.destroy(); - exporter.unexport(); - } - - @Test - @Disabled - public void testCustomException() { - XmlRpcServiceImpl server = new XmlRpcServiceImpl(); - ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); - Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension(); - int port = NetUtils.getAvailablePort(); - URL url = URL.valueOf("xmlrpc://127.0.0.1:" + port + "/" + - XmlRpcService.class.getName() + "?version=1.0.0&server=jetty9"); - Exporter exporter = protocol.export(proxyFactory.getInvoker(server, XmlRpcService.class, url)); - Invoker invoker = protocol.refer(XmlRpcService.class, url); - XmlRpcService client = proxyFactory.getProxy(invoker); - try { - client.customException(); - Assertions.fail(); - } catch (XmlRpcServiceImpl.MyException expected) { - } - invoker.destroy(); - exporter.unexport(); - } - -} \ No newline at end of file diff --git a/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcService.java b/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcService.java deleted file mode 100644 index 3355ba6f41..0000000000 --- a/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcService.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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.apache.dubbo.xml.rpc.protocol.xmlrpc; - -public interface XmlRpcService { - String sayHello(String name); - - void timeOut(int millis); - - String customException(); -} diff --git a/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcServiceImpl.java b/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcServiceImpl.java deleted file mode 100644 index 0a6111d86a..0000000000 --- a/dubbo-rpc/dubbo-rpc-xml/src/test/java/org/apache/dubbo/xml/rpc/protocol/xmlrpc/XmlRpcServiceImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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.apache.dubbo.xml.rpc.protocol.xmlrpc; - -public class XmlRpcServiceImpl implements XmlRpcService { - private boolean called; - - public String sayHello(String name) { - called = true; - return "Hello, " + name; - } - - public boolean isCalled() { - return called; - } - - public void timeOut(int millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - public String customException() { - throw new MyException("custom exception"); - } - - static class MyException extends RuntimeException{ - - private static final long serialVersionUID = -3051041116483629056L; - - public MyException(String message) { - super(message); - } - } -} diff --git a/dubbo-rpc/pom.xml b/dubbo-rpc/pom.xml index 9b45c3757e..b0283437c6 100644 --- a/dubbo-rpc/pom.xml +++ b/dubbo-rpc/pom.xml @@ -33,16 +33,7 @@ dubbo-rpc-api dubbo-rpc-dubbo dubbo-rpc-injvm - dubbo-rpc-http - dubbo-rpc-rmi - dubbo-rpc-hessian - dubbo-rpc-webservice - dubbo-rpc-native-thrift - dubbo-rpc-thrift - dubbo-rpc-memcached - dubbo-rpc-redis dubbo-rpc-rest - dubbo-rpc-xml dubbo-rpc-grpc diff --git a/dubbo-serialization/dubbo-serialization-avro/pom.xml b/dubbo-serialization/dubbo-serialization-avro/pom.xml deleted file mode 100644 index 75bbff7799..0000000000 --- a/dubbo-serialization/dubbo-serialization-avro/pom.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-serialization - ${revision} - ../pom.xml - - dubbo-serialization-avro - jar - ${project.artifactId} - The avro serialization module of dubbo project - - false - - - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - org.apache.avro - avro - - - \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroObjectInput.java b/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroObjectInput.java deleted file mode 100644 index 0d85ec7b24..0000000000 --- a/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroObjectInput.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.avro; - -import org.apache.dubbo.common.serialize.ObjectInput; - -import org.apache.avro.io.BinaryDecoder; -import org.apache.avro.io.DecoderFactory; -import org.apache.avro.reflect.ReflectDatumReader; -import org.apache.avro.util.Utf8; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; - -public class AvroObjectInput implements ObjectInput { - private static DecoderFactory decoderFactory = DecoderFactory.get(); - private BinaryDecoder decoder; - - public AvroObjectInput(InputStream in) { - decoder = decoderFactory.binaryDecoder(in, null); - } - - @Override - public boolean readBool() throws IOException { - return decoder.readBoolean(); - } - - @Override - public byte readByte() throws IOException { - byte[] bytes = new byte[1]; - decoder.readFixed(bytes); - return bytes[0]; - } - - @Override - public short readShort() throws IOException { - return (short) decoder.readInt(); - } - - @Override - public int readInt() throws IOException { - return decoder.readInt(); - } - - @Override - public long readLong() throws IOException { - return decoder.readLong(); - } - - @Override - public float readFloat() throws IOException { - return decoder.readFloat(); - } - - @Override - public double readDouble() throws IOException { - return decoder.readDouble(); - } - - @Override - public String readUTF() throws IOException { - Utf8 result = new Utf8(); - result = decoder.readString(result); - return result.toString(); - } - - @Override - public byte[] readBytes() throws IOException { - String resultStr = decoder.readString(); - return resultStr.getBytes(StandardCharsets.UTF_8); - } - - /** - * will lost all attribute - */ - @Override - public Object readObject() throws IOException, ClassNotFoundException { - ReflectDatumReader reader = new ReflectDatumReader<>(Object.class); - return reader.read(null, decoder); - } - - @Override - @SuppressWarnings(value = {"unchecked"}) - public T readObject(Class cls) throws IOException, ClassNotFoundException { - //Map interface class change to HashMap implement - if (cls == Map.class) { - cls = (Class) HashMap.class; - } - - ReflectDatumReader reader = new ReflectDatumReader<>(cls); - return reader.read(null, decoder); - } - - @Override - public T readObject(Class cls, Type type) throws IOException, ClassNotFoundException { - ReflectDatumReader reader = new ReflectDatumReader<>(cls); - return reader.read(null, decoder); - } - -} diff --git a/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroObjectOutput.java b/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroObjectOutput.java deleted file mode 100644 index 42a34e05f0..0000000000 --- a/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroObjectOutput.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.avro; - -import org.apache.dubbo.common.serialize.ObjectOutput; - -import org.apache.avro.io.BinaryEncoder; -import org.apache.avro.io.EncoderFactory; -import org.apache.avro.reflect.ReflectDatumWriter; -import org.apache.avro.util.Utf8; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; - -public class AvroObjectOutput implements ObjectOutput { - private static EncoderFactory encoderFactory = EncoderFactory.get(); - private BinaryEncoder encoder; - - public AvroObjectOutput(OutputStream out) { - encoder = encoderFactory.binaryEncoder(out, null); - } - - @Override - public void writeBool(boolean v) throws IOException { - encoder.writeBoolean(v); - } - - @Override - public void writeByte(byte v) throws IOException { - encoder.writeFixed(new byte[]{v}); - } - - @Override - public void writeShort(short v) throws IOException { - encoder.writeInt(v); - } - - @Override - public void writeInt(int v) throws IOException { - encoder.writeInt(v); - } - - @Override - public void writeLong(long v) throws IOException { - encoder.writeLong(v); - } - - @Override - public void writeFloat(float v) throws IOException { - encoder.writeFloat(v); - } - - @Override - public void writeDouble(double v) throws IOException { - encoder.writeDouble(v); - } - - @Override - public void writeUTF(String v) throws IOException { - encoder.writeString(new Utf8(v)); - } - - @Override - public void writeBytes(byte[] v) throws IOException { - encoder.writeString(new String(v, StandardCharsets.UTF_8)); - } - - @Override - public void writeBytes(byte[] v, int off, int len) throws IOException { - byte[] v2 = Arrays.copyOfRange(v, off, off + len); - encoder.writeString(new String(v2, StandardCharsets.UTF_8)); - } - - @Override - public void flushBuffer() throws IOException { - encoder.flush(); - } - - @Override - @SuppressWarnings(value = {"rawtypes", "unchecked"}) - public void writeObject(Object obj) throws IOException { - if (obj == null) { - encoder.writeNull(); - return; - } - ReflectDatumWriter dd = new ReflectDatumWriter<>(obj.getClass()); - dd.write(obj, encoder); - } - -} diff --git a/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java b/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java deleted file mode 100644 index 7eb291ec34..0000000000 --- a/dubbo-serialization/dubbo-serialization-avro/src/main/java/org/apache/dubbo/common/serialize/avro/AvroSerialization.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.avro; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import static org.apache.dubbo.common.serialize.Constants.AVRO_SERIALIZATION_ID; - -public class AvroSerialization implements Serialization { - - @Override - public byte getContentTypeId() { - return AVRO_SERIALIZATION_ID; - } - - @Override - public String getContentType() { - return "avro/binary"; - } - - @Override - public ObjectOutput serialize(URL url, OutputStream output) throws IOException { - return new AvroObjectOutput(output); - } - - @Override - public ObjectInput deserialize(URL url, InputStream input) throws IOException { - return new AvroObjectInput(input); - } - -} diff --git a/dubbo-serialization/dubbo-serialization-avro/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization b/dubbo-serialization/dubbo-serialization-avro/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization deleted file mode 100644 index d8cba3e1ba..0000000000 --- a/dubbo-serialization/dubbo-serialization-avro/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization +++ /dev/null @@ -1 +0,0 @@ -avro=org.apache.dubbo.common.serialize.avro.AvroSerialization \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-fastjson/pom.xml b/dubbo-serialization/dubbo-serialization-fastjson/pom.xml deleted file mode 100644 index 48bd0c6da7..0000000000 --- a/dubbo-serialization/dubbo-serialization-fastjson/pom.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-serialization - ${revision} - ../pom.xml - - dubbo-serialization-fastjson - jar - ${project.artifactId} - The fastjson serialization module of dubbo project - - false - - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - com.alibaba - fastjson - - - \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectInput.java b/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectInput.java deleted file mode 100644 index ccf6a2b3d5..0000000000 --- a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectInput.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.fastjson; - -import org.apache.dubbo.common.serialize.ObjectInput; - -import com.alibaba.fastjson.JSON; - -import java.io.BufferedReader; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.lang.reflect.Type; - -/** - * FastJson object input implementation - */ -public class FastJsonObjectInput implements ObjectInput { - - private final BufferedReader reader; - - public FastJsonObjectInput(InputStream in) { - this(new InputStreamReader(in)); - } - - public FastJsonObjectInput(Reader reader) { - this.reader = new BufferedReader(reader); - } - - @Override - public boolean readBool() throws IOException { - return read(boolean.class); - } - - @Override - public byte readByte() throws IOException { - return read(byte.class); - } - - @Override - public short readShort() throws IOException { - return read(short.class); - } - - @Override - public int readInt() throws IOException { - return read(int.class); - } - - @Override - public long readLong() throws IOException { - return read(long.class); - } - - @Override - public float readFloat() throws IOException { - return read(float.class); - } - - @Override - public double readDouble() throws IOException { - return read(double.class); - } - - @Override - public String readUTF() throws IOException { - return read(String.class); - } - - @Override - public byte[] readBytes() throws IOException { - return readLine().getBytes(); - } - - @Override - public Object readObject() throws IOException, ClassNotFoundException { - String json = readLine(); - return JSON.parse(json); - } - - @Override - public T readObject(Class cls) throws IOException, ClassNotFoundException { - return read(cls); - } - - @Override - @SuppressWarnings("unchecked") - public T readObject(Class cls, Type type) throws IOException, ClassNotFoundException { - String json = readLine(); - return (T) JSON.parseObject(json, type); - } - - private String readLine() throws IOException, EOFException { - String line = reader.readLine(); - if (line == null || line.trim().length() == 0) { - throw new EOFException(); - } - return line; - } - - private T read(Class cls) throws IOException { - String json = readLine(); - return JSON.parseObject(json, cls); - } -} diff --git a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectOutput.java b/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectOutput.java deleted file mode 100644 index 3f9ec2083d..0000000000 --- a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonObjectOutput.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.fastjson; - -import org.apache.dubbo.common.serialize.ObjectOutput; - -import com.alibaba.fastjson.serializer.JSONSerializer; -import com.alibaba.fastjson.serializer.SerializeWriter; -import com.alibaba.fastjson.serializer.SerializerFeature; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Writer; - -/** - * FastJson object output implementation - */ -public class FastJsonObjectOutput implements ObjectOutput { - - private final PrintWriter writer; - - public FastJsonObjectOutput(OutputStream out) { - this(new OutputStreamWriter(out)); - } - - public FastJsonObjectOutput(Writer writer) { - this.writer = new PrintWriter(writer); - } - - @Override - public void writeBool(boolean v) throws IOException { - writeObject(v); - } - - @Override - public void writeByte(byte v) throws IOException { - writeObject(v); - } - - @Override - public void writeShort(short v) throws IOException { - writeObject(v); - } - - @Override - public void writeInt(int v) throws IOException { - writeObject(v); - } - - @Override - public void writeLong(long v) throws IOException { - writeObject(v); - } - - @Override - public void writeFloat(float v) throws IOException { - writeObject(v); - } - - @Override - public void writeDouble(double v) throws IOException { - writeObject(v); - } - - @Override - public void writeUTF(String v) throws IOException { - writeObject(v); - } - - @Override - public void writeBytes(byte[] b) throws IOException { - writer.println(new String(b)); - } - - @Override - public void writeBytes(byte[] b, int off, int len) throws IOException { - writer.println(new String(b, off, len)); - } - - @Override - public void writeObject(Object obj) throws IOException { - SerializeWriter out = new SerializeWriter(); - JSONSerializer serializer = new JSONSerializer(out); - serializer.config(SerializerFeature.WriteEnumUsingToString, true); - serializer.write(obj); - out.writeTo(writer); - out.close(); // for reuse SerializeWriter buf - writer.println(); - writer.flush(); - } - - @Override - public void flushBuffer() throws IOException { - writer.flush(); - } - -} diff --git a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java b/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java deleted file mode 100644 index 84c5721ce5..0000000000 --- a/dubbo-serialization/dubbo-serialization-fastjson/src/main/java/org/apache/dubbo/common/serialize/fastjson/FastJsonSerialization.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.fastjson; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import static org.apache.dubbo.common.serialize.Constants.FASTJSON_SERIALIZATION_ID; - -/** - * FastJson serialization implementation - * - *
    - *     e.g. <dubbo:protocol serialization="fastjson" />
    - * 
    - */ -public class FastJsonSerialization implements Serialization { - - @Override - public byte getContentTypeId() { - return FASTJSON_SERIALIZATION_ID; - } - - @Override - public String getContentType() { - return "text/json"; - } - - @Override - public ObjectOutput serialize(URL url, OutputStream output) throws IOException { - return new FastJsonObjectOutput(output); - } - - @Override - public ObjectInput deserialize(URL url, InputStream input) throws IOException { - return new FastJsonObjectInput(input); - } - -} diff --git a/dubbo-serialization/dubbo-serialization-fastjson/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization b/dubbo-serialization/dubbo-serialization-fastjson/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization deleted file mode 100644 index cb8c9867dd..0000000000 --- a/dubbo-serialization/dubbo-serialization-fastjson/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization +++ /dev/null @@ -1 +0,0 @@ -fastjson=org.apache.dubbo.common.serialize.fastjson.FastJsonSerialization \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-fst/pom.xml b/dubbo-serialization/dubbo-serialization-fst/pom.xml deleted file mode 100644 index 7bcaaf8d49..0000000000 --- a/dubbo-serialization/dubbo-serialization-fst/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-serialization - ${revision} - ../pom.xml - - dubbo-serialization-fst - jar - ${project.artifactId} - The fst serialization module of dubbo project - - false - - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - de.ruedigermoeller - fst - - - \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstFactory.java b/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstFactory.java deleted file mode 100644 index f73259ff3b..0000000000 --- a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.fst; - -import org.apache.dubbo.common.serialize.support.SerializableClassRegistry; - -import org.nustaq.serialization.FSTConfiguration; -import org.nustaq.serialization.FSTObjectInput; -import org.nustaq.serialization.FSTObjectOutput; - -import java.io.InputStream; -import java.io.OutputStream; - -/** - * Fst object input/output factory - */ -public class FstFactory { - - private static final FstFactory FACTORY = new FstFactory(); - - private final FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration(); - - - public static FstFactory getDefaultFactory() { - return FACTORY; - } - - public FstFactory() { - SerializableClassRegistry.getRegisteredClasses().keySet().forEach(conf::registerClass); - } - - public FSTObjectOutput getObjectOutput(OutputStream outputStream) { - return conf.getObjectOutput(outputStream); - } - - public FSTObjectInput getObjectInput(InputStream inputStream) { - return conf.getObjectInput(inputStream); - } -} diff --git a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstObjectInput.java b/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstObjectInput.java deleted file mode 100644 index 51e8340a98..0000000000 --- a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstObjectInput.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.fst; - -import org.apache.dubbo.common.serialize.ObjectInput; - -import org.nustaq.serialization.FSTObjectInput; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; - -/** - * Fst object input implementation - */ -public class FstObjectInput implements ObjectInput { - - private FSTObjectInput input; - - public FstObjectInput(InputStream inputStream) { - input = FstFactory.getDefaultFactory().getObjectInput(inputStream); - } - - @Override - public boolean readBool() throws IOException { - return input.readBoolean(); - } - - @Override - public byte readByte() throws IOException { - return input.readByte(); - } - - @Override - public short readShort() throws IOException { - return input.readShort(); - } - - @Override - public int readInt() throws IOException { - return input.readInt(); - } - - @Override - public long readLong() throws IOException { - return input.readLong(); - } - - @Override - public float readFloat() throws IOException { - return input.readFloat(); - } - - @Override - public double readDouble() throws IOException { - return input.readDouble(); - } - - @Override - public byte[] readBytes() throws IOException { - int len = input.readInt(); - if (len < 0) { - return null; - } else if (len == 0) { - return new byte[]{}; - } else { - byte[] b = new byte[len]; - input.readFully(b); - return b; - } - } - - @Override - public String readUTF() throws IOException { - return input.readUTF(); - } - - @Override - public Object readObject() throws IOException, ClassNotFoundException { - return input.readObject(); - } - - - @Override - @SuppressWarnings("unchecked") - public T readObject(Class clazz) throws IOException, ClassNotFoundException { - try { - return (T) input.readObject(clazz); - } catch (Exception e) { - throw new IOException(e); - } - } - - @Override - @SuppressWarnings("unchecked") - public T readObject(Class clazz, Type type) throws IOException, ClassNotFoundException { - try { - return (T) input.readObject(clazz); - } catch (Exception e) { - throw new IOException(e); - } - } -} diff --git a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstObjectOutput.java b/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstObjectOutput.java deleted file mode 100644 index a2c40e5d0d..0000000000 --- a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstObjectOutput.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.fst; - -import org.apache.dubbo.common.serialize.ObjectOutput; - -import org.nustaq.serialization.FSTObjectOutput; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Fst object output implementation - */ -public class FstObjectOutput implements ObjectOutput { - - private FSTObjectOutput output; - - public FstObjectOutput(OutputStream outputStream) { - output = FstFactory.getDefaultFactory().getObjectOutput(outputStream); - } - - @Override - public void writeBool(boolean v) throws IOException { - output.writeBoolean(v); - } - - @Override - public void writeByte(byte v) throws IOException { - output.writeByte(v); - } - - @Override - public void writeShort(short v) throws IOException { - output.writeShort(v); - } - - @Override - public void writeInt(int v) throws IOException { - output.writeInt(v); - } - - @Override - public void writeLong(long v) throws IOException { - output.writeLong(v); - } - - @Override - public void writeFloat(float v) throws IOException { - output.writeFloat(v); - } - - @Override - public void writeDouble(double v) throws IOException { - output.writeDouble(v); - } - - @Override - public void writeBytes(byte[] v) throws IOException { - if (v == null) { - output.writeInt(-1); - } else { - writeBytes(v, 0, v.length); - } - } - - @Override - public void writeBytes(byte[] v, int off, int len) throws IOException { - if (v == null) { - output.writeInt(-1); - } else { - output.writeInt(len); - output.write(v, off, len); - } - } - - - @Override - public void writeUTF(String v) throws IOException { - output.writeUTF(v); - } - - @Override - public void writeObject(Object v) throws IOException { - output.writeObject(v); - } - - @Override - public void flushBuffer() throws IOException { - output.flush(); - } -} diff --git a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java b/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java deleted file mode 100644 index b8862f377c..0000000000 --- a/dubbo-serialization/dubbo-serialization-fst/src/main/java/org/apache/dubbo/common/serialize/fst/FstSerialization.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.fst; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import static org.apache.dubbo.common.serialize.Constants.FST_SERIALIZATION_ID; - -/** - * Fst serialization implementation - * - *
    - *     e.g. <dubbo:protocol serialization="fst" />
    - * 
    - */ -public class FstSerialization implements Serialization { - - @Override - public byte getContentTypeId() { - return FST_SERIALIZATION_ID; - } - - @Override - public String getContentType() { - return "x-application/fst"; - } - - @Override - public ObjectOutput serialize(URL url, OutputStream out) throws IOException { - return new FstObjectOutput(out); - } - - @Override - public ObjectInput deserialize(URL url, InputStream is) throws IOException { - return new FstObjectInput(is); - } -} diff --git a/dubbo-serialization/dubbo-serialization-fst/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization b/dubbo-serialization/dubbo-serialization-fst/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization deleted file mode 100644 index 793fede18b..0000000000 --- a/dubbo-serialization/dubbo-serialization-fst/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization +++ /dev/null @@ -1 +0,0 @@ -fst=org.apache.dubbo.common.serialize.fst.FstSerialization \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-gson/pom.xml b/dubbo-serialization/dubbo-serialization-gson/pom.xml deleted file mode 100644 index 52e1588a17..0000000000 --- a/dubbo-serialization/dubbo-serialization-gson/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - dubbo-serialization - org.apache.dubbo - ${revision} - ../pom.xml - - dubbo-serialization-gson - jar - ${project.artifactId} - The GSON serialization implement for dubbo - - false - - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - com.google.code.gson - gson - - - \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectInput.java b/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectInput.java deleted file mode 100644 index f6bbd134d9..0000000000 --- a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectInput.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.gson; - -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.utils.PojoUtils; - -import com.google.gson.Gson; - -import java.io.BufferedReader; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.lang.reflect.Type; - -public class GsonJsonObjectInput implements ObjectInput { - private final BufferedReader reader; - private Gson gson; - - public GsonJsonObjectInput(InputStream in) { - this(new InputStreamReader(in)); - } - - public GsonJsonObjectInput(Reader reader) { - this.reader = new BufferedReader(reader); - gson = new Gson(); - } - - @Override - public boolean readBool() throws IOException { - return read(boolean.class); - } - - @Override - public byte readByte() throws IOException { - return read(byte.class); - } - - @Override - public short readShort() throws IOException { - return read(short.class); - } - - @Override - public int readInt() throws IOException { - return read(int.class); - } - - @Override - public long readLong() throws IOException { - return read(long.class); - } - - @Override - public float readFloat() throws IOException { - return read(float.class); - } - - @Override - public double readDouble() throws IOException { - return read(double.class); - } - - @Override - public String readUTF() throws IOException { - return read(String.class); - } - - @Override - public byte[] readBytes() throws IOException { - return readLine().getBytes(); - } - - @Override - public Object readObject() throws IOException, ClassNotFoundException { - String json = readLine(); - return gson.fromJson(json, Object.class); - } - - @Override - public T readObject(Class cls) throws IOException, ClassNotFoundException { - return read(cls); - } - - @Override - @SuppressWarnings("unchecked") - public T readObject(Class cls, Type type) throws IOException, ClassNotFoundException { - Object value = readObject(cls); - return (T) PojoUtils.realize(value, cls, type); - } - - private String readLine() throws IOException { - String line = reader.readLine(); - if (line == null || line.trim().length() == 0) { - throw new EOFException(); - } - return line; - } - - private T read(Class cls) throws IOException { - String json = readLine(); - return gson.fromJson(json, cls); - } -} diff --git a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectOutput.java b/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectOutput.java deleted file mode 100644 index 41155da477..0000000000 --- a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectOutput.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.gson; - -import com.google.gson.Gson; -import org.apache.dubbo.common.serialize.ObjectOutput; - -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Writer; -import java.io.IOException; - - -public class GsonJsonObjectOutput implements ObjectOutput { - - private final PrintWriter writer; - private Gson gson = null; - - public GsonJsonObjectOutput(OutputStream out) { - this(new OutputStreamWriter(out)); - } - - public GsonJsonObjectOutput(Writer writer) { - this.gson = new Gson(); - this.writer = new PrintWriter(writer); - } - - @Override - public void writeBool(boolean v) throws IOException { - writeObject(v); - } - - @Override - public void writeByte(byte v) throws IOException { - writeObject(v); - } - - @Override - public void writeShort(short v) throws IOException { - writeObject(v); - } - - @Override - public void writeInt(int v) throws IOException { - writeObject(v); - } - - @Override - public void writeLong(long v) throws IOException { - writeObject(v); - } - - @Override - public void writeFloat(float v) throws IOException { - writeObject(v); - } - - @Override - public void writeDouble(double v) throws IOException { - writeObject(v); - } - - @Override - public void writeUTF(String v) throws IOException { - writeObject(v); - } - - @Override - public void writeBytes(byte[] b) throws IOException { - writer.println(new String(b)); - } - - @Override - public void writeBytes(byte[] b, int off, int len) throws IOException { - writer.println(new String(b, off, len)); - } - - @Override - public void writeObject(Object obj) throws IOException { - char[] json = gson.toJson(obj).toCharArray(); - writer.write(json, 0, json.length); - writer.println(); - writer.flush(); - json = null; - } - - @Override - public void flushBuffer() throws IOException { - writer.flush(); - } - -} diff --git a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java b/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java deleted file mode 100644 index a22769a280..0000000000 --- a/dubbo-serialization/dubbo-serialization-gson/src/main/java/org/apache/dubbo/common/serialize/gson/GsonSerialization.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.gson; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import static org.apache.dubbo.common.serialize.Constants.GSON_SERIALIZATION_ID; - -public class GsonSerialization implements Serialization { - - - @Override - public byte getContentTypeId() { - return GSON_SERIALIZATION_ID; - } - - @Override - public String getContentType() { - return "text/json"; - } - - @Override - public ObjectOutput serialize(URL url, OutputStream output) throws IOException { - return new GsonJsonObjectOutput(output); - } - - @Override - public ObjectInput deserialize(URL url, InputStream input) throws IOException { - return new GsonJsonObjectInput(input); - } -} diff --git a/dubbo-serialization/dubbo-serialization-gson/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization b/dubbo-serialization/dubbo-serialization-gson/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization deleted file mode 100644 index f0cd8df6b2..0000000000 --- a/dubbo-serialization/dubbo-serialization-gson/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization +++ /dev/null @@ -1 +0,0 @@ -gson=org.apache.dubbo.common.serialize.gson.GsonSerialization diff --git a/dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectOutputTest.java b/dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectOutputTest.java deleted file mode 100644 index 0ff2633458..0000000000 --- a/dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/GsonJsonObjectOutputTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.gson; - - - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; -import static org.hamcrest.CoreMatchers.nullValue; -import static org.hamcrest.MatcherAssert.assertThat; - -public class GsonJsonObjectOutputTest { - private GsonJsonObjectOutput gsonJsonObjectOutput; - private GsonJsonObjectInput gsonJsonObjectInput; - private ByteArrayOutputStream byteArrayOutputStream; - private ByteArrayInputStream byteArrayInputStream; - - @BeforeEach - public void setUp() throws Exception { - this.byteArrayOutputStream = new ByteArrayOutputStream(); - this.gsonJsonObjectOutput = new GsonJsonObjectOutput(byteArrayOutputStream); - } - - @Test - public void testWriteBool() throws IOException { - this.gsonJsonObjectOutput.writeBool(true); - this.flushToInput(); - - assertThat(gsonJsonObjectInput.readBool(), is(true)); - } - - @Test - public void testWriteShort() throws IOException { - this.gsonJsonObjectOutput.writeShort((short) 2); - this.flushToInput(); - - assertThat(gsonJsonObjectInput.readShort(), is((short) 2)); - } - - @Test - public void testWriteInt() throws IOException { - this.gsonJsonObjectOutput.writeInt(1); - this.flushToInput(); - - assertThat(gsonJsonObjectInput.readInt(), is(1)); - } - - @Test - public void testWriteLong() throws IOException { - this.gsonJsonObjectOutput.writeLong(1000L); - this.flushToInput(); - - assertThat(gsonJsonObjectInput.readLong(), is(1000L)); - } - - @Test - public void testWriteUTF() throws IOException { - this.gsonJsonObjectOutput.writeUTF("Pace Hasîtî 和平 Мир"); - this.flushToInput(); - - assertThat(gsonJsonObjectInput.readUTF(), is("Pace Hasîtî 和平 Мир")); - } - - - @Test - public void testWriteFloat() throws IOException { - this.gsonJsonObjectOutput.writeFloat(1.88f); - this.flushToInput(); - - assertThat(this.gsonJsonObjectInput.readFloat(), is(1.88f)); - } - - @Test - public void testWriteDouble() throws IOException { - this.gsonJsonObjectOutput.writeDouble(1.66d); - this.flushToInput(); - - assertThat(this.gsonJsonObjectInput.readDouble(), is(1.66d)); - } - - @Test - public void testWriteBytes() throws IOException { - this.gsonJsonObjectOutput.writeBytes("hello".getBytes()); - this.flushToInput(); - - assertThat(this.gsonJsonObjectInput.readBytes(), is("hello".getBytes())); - } - - @Test - public void testWriteBytesWithSubLength() throws IOException { - this.gsonJsonObjectOutput.writeBytes("hello".getBytes(), 2, 2); - this.flushToInput(); - - assertThat(this.gsonJsonObjectInput.readBytes(), is("ll".getBytes())); - } - - @Test - public void testWriteByte() throws IOException { - this.gsonJsonObjectOutput.writeByte((byte) 123); - this.flushToInput(); - - assertThat(this.gsonJsonObjectInput.readByte(), is((byte) 123)); - } - - @Test - public void testWriteObject() throws IOException, ClassNotFoundException { - Image image = new Image("http://dubbo.apache.org/img/dubbo_white.png", "logo", 300, 480, Image.Size.SMALL); - this.gsonJsonObjectOutput.writeObject(image); - this.flushToInput(); - - Image readObjectForImage = gsonJsonObjectInput.readObject(Image.class); - assertThat(readObjectForImage, not(nullValue())); - assertThat(readObjectForImage, is(image)); - } - - private void flushToInput() throws IOException { - this.gsonJsonObjectOutput.flushBuffer(); - this.byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); - this.gsonJsonObjectInput = new GsonJsonObjectInput(byteArrayInputStream); - } -} diff --git a/dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/GsonJsonSerializationTest.java b/dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/GsonJsonSerializationTest.java deleted file mode 100644 index 51fca3df01..0000000000 --- a/dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/GsonJsonSerializationTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.gson; - -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.hamcrest.Matchers; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; -import static org.mockito.Mockito.mock; - -public class GsonJsonSerializationTest { - private GsonSerialization gsonJsonSerialization; - - @BeforeEach - public void setUp() { - this.gsonJsonSerialization = new GsonSerialization(); - } - - @Test - public void testContentType() { - assertThat(gsonJsonSerialization.getContentType(), is("text/json")); - } - - @Test - public void testContentTypeId() { - assertThat(gsonJsonSerialization.getContentTypeId(), is((byte) 16)); - } - - @Test - public void testObjectOutput() throws IOException { - ObjectOutput objectOutput = gsonJsonSerialization.serialize(null, mock(OutputStream.class)); - assertThat(objectOutput, Matchers.instanceOf(GsonJsonObjectOutput.class)); - } - - @Test - public void testObjectInput() throws IOException { - ObjectInput objectInput = gsonJsonSerialization.deserialize(null, mock(InputStream.class)); - assertThat(objectInput, Matchers.instanceOf(GsonJsonObjectInput.class)); - } -} diff --git a/dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/Image.java b/dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/Image.java deleted file mode 100644 index d1316d37d8..0000000000 --- a/dubbo-serialization/dubbo-serialization-gson/src/test/java/org/apache/dubbo/common/serialize/gson/Image.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.gson; - - -public class Image implements java.io.Serializable { - private static final long serialVersionUID = 1L; - public String uri; - public String title; // Can be null - public int width; - public int height; - public Size size; - - public Image() { - } - - public Image(String uri, String title, int width, int height, Size size) { - this.height = height; - this.title = title; - this.uri = uri; - this.width = width; - this.size = size; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - Image image = (Image) o; - - if (height != image.height) return false; - if (width != image.width) return false; - if (size != image.size) return false; - if (title != null ? !title.equals(image.title) : image.title != null) return false; - if (uri != null ? !uri.equals(image.uri) : image.uri != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = uri != null ? uri.hashCode() : 0; - result = 31 * result + (title != null ? title.hashCode() : 0); - result = 31 * result + width; - result = 31 * result + height; - result = 31 * result + (size != null ? size.hashCode() : 0); - return result; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[Image "); - sb.append("uri=").append(uri); - sb.append(", title=").append(title); - sb.append(", width=").append(width); - sb.append(", height=").append(height); - sb.append(", size=").append(size); - sb.append("]"); - return sb.toString(); - } - - public String getUri() { - return uri; - } - - public void setUri(String uri) { - this.uri = uri; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public int getWidth() { - return width; - } - - public void setWidth(int width) { - this.width = width; - } - - public int getHeight() { - return height; - } - - public void setHeight(int height) { - this.height = height; - } - - public Size getSize() { - return size; - } - - public void setSize(Size size) { - this.size = size; - } - - public enum Size { - SMALL, LARGE - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/pom.xml b/dubbo-serialization/dubbo-serialization-kryo/pom.xml deleted file mode 100644 index 9e22ed0b57..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-serialization - ${revision} - ../pom.xml - - dubbo-serialization-kryo - jar - ${project.artifactId} - The kryo serialization module of dubbo project - - false - - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - com.esotericsoftware - kryo - - - de.javakaffee - kryo-serializers - - - \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/CompatibleKryo.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/CompatibleKryo.java deleted file mode 100644 index 69e4b35b16..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/CompatibleKryo.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo; - -import org.apache.dubbo.common.logger.Logger; -import org.apache.dubbo.common.logger.LoggerFactory; -import org.apache.dubbo.common.serialize.kryo.utils.ReflectionUtils; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.Serializer; -import com.esotericsoftware.kryo.serializers.JavaSerializer; - -public class CompatibleKryo extends Kryo { - - private static final Logger logger = LoggerFactory.getLogger(CompatibleKryo.class); - - @Override - public Serializer getDefaultSerializer(Class type) { - if (type == null) { - throw new IllegalArgumentException("type cannot be null."); - } - - /** - * Kryo requires every class to provide a zero argument constructor. For any class does not match this condition, kryo have two ways: - * 1. Use JavaSerializer, - * 2. Set 'kryo.setInstantiatorStrategy(new DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));', StdInstantiatorStrategy can generate an instance bypassing the constructor. - * - * In practice, it's not possible for Dubbo users to register kryo Serializer for every customized class. So in most cases, customized classes with/without zero argument constructor will - * default to the default serializer. - * It is the responsibility of kryo to handle with every standard jdk classes, so we will just escape these classes. - */ - if (!ReflectionUtils.isJdk(type) && !type.isArray() && !type.isEnum() && !ReflectionUtils.checkZeroArgConstructor(type)) { - if (logger.isWarnEnabled()) { - logger.warn(type + " has no zero-arg constructor and this will affect the serialization performance"); - } - return new JavaSerializer(); - } - return super.getDefaultSerializer(type); - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoObjectInput.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoObjectInput.java deleted file mode 100644 index 91648e5c62..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoObjectInput.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo; - -import org.apache.dubbo.common.serialize.Cleanable; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.kryo.utils.KryoUtils; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.KryoException; -import com.esotericsoftware.kryo.io.Input; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; - -/** - * Kryo object input implementation, kryo object can be clean - */ -public class KryoObjectInput implements ObjectInput, Cleanable { - - private Kryo kryo; - private Input input; - - public KryoObjectInput(InputStream inputStream) { - input = new Input(inputStream); - this.kryo = KryoUtils.get(); - } - - @Override - public boolean readBool() throws IOException { - try { - return input.readBoolean(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public byte readByte() throws IOException { - try { - return input.readByte(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public short readShort() throws IOException { - try { - return input.readShort(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public int readInt() throws IOException { - try { - return input.readInt(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public long readLong() throws IOException { - try { - return input.readLong(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public float readFloat() throws IOException { - try { - return input.readFloat(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public double readDouble() throws IOException { - try { - return input.readDouble(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public byte[] readBytes() throws IOException { - try { - int len = input.readInt(); - if (len < 0) { - return null; - } else if (len == 0) { - return new byte[]{}; - } else { - return input.readBytes(len); - } - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public String readUTF() throws IOException { - try { - return input.readString(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public Object readObject() throws IOException, ClassNotFoundException { - // TODO optimization - try { - return kryo.readClassAndObject(input); - } catch (KryoException e) { - throw new IOException(e); - } - } - - - @Override - @SuppressWarnings("unchecked") - public T readObject(Class clazz) throws IOException, ClassNotFoundException { - // TODO optimization - return (T) readObject(); - } - - @Override - @SuppressWarnings("unchecked") - public T readObject(Class clazz, Type type) throws IOException, ClassNotFoundException { - // TODO optimization - return readObject(clazz); - } - - @Override - public void cleanup() { - KryoUtils.release(kryo); - kryo = null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoObjectOutput.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoObjectOutput.java deleted file mode 100644 index dd127005fe..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoObjectOutput.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo; - -import org.apache.dubbo.common.serialize.Cleanable; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.kryo.utils.KryoUtils; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.io.Output; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Kryo object output implementation, kryo object can be clean - */ -public class KryoObjectOutput implements ObjectOutput, Cleanable { - - private Output output; - private Kryo kryo; - - public KryoObjectOutput(OutputStream outputStream) { - output = new Output(outputStream); - this.kryo = KryoUtils.get(); - } - - @Override - public void writeBool(boolean v) throws IOException { - output.writeBoolean(v); - } - - @Override - public void writeByte(byte v) throws IOException { - output.writeByte(v); - } - - @Override - public void writeShort(short v) throws IOException { - output.writeShort(v); - } - - @Override - public void writeInt(int v) throws IOException { - output.writeInt(v); - } - - @Override - public void writeLong(long v) throws IOException { - output.writeLong(v); - } - - @Override - public void writeFloat(float v) throws IOException { - output.writeFloat(v); - } - - @Override - public void writeDouble(double v) throws IOException { - output.writeDouble(v); - } - - @Override - public void writeBytes(byte[] v) throws IOException { - if (v == null) { - output.writeInt(-1); - } else { - writeBytes(v, 0, v.length); - } - } - - @Override - public void writeBytes(byte[] v, int off, int len) throws IOException { - if (v == null) { - output.writeInt(-1); - } else { - output.writeInt(len); - output.write(v, off, len); - } - } - - - @Override - public void writeUTF(String v) throws IOException { - output.writeString(v); - } - - @Override - public void writeObject(Object v) throws IOException { - // TODO carries class info every time. - kryo.writeClassAndObject(output, v); - } - - @Override - public void flushBuffer() throws IOException { - output.flush(); - } - - @Override - public void cleanup() { - KryoUtils.release(kryo); - kryo = null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java deleted file mode 100644 index 369192a9cd..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/KryoSerialization.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import static org.apache.dubbo.common.serialize.Constants.KRYO_SERIALIZATION_ID; - -/** - * TODO for now kryo serialization doesn't deny classes that don't implement the serializable interface - * - *
    - *     e.g. <dubbo:protocol serialization="kryo" />
    - * 
    - */ -public class KryoSerialization implements Serialization { - - @Override - public byte getContentTypeId() { - return KRYO_SERIALIZATION_ID; - } - - @Override - public String getContentType() { - return "x-application/kryo"; - } - - @Override - public ObjectOutput serialize(URL url, OutputStream out) throws IOException { - return new KryoObjectOutput(out); - } - - @Override - public ObjectInput deserialize(URL url, InputStream is) throws IOException { - return new KryoObjectInput(is); - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoObjectInput2.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoObjectInput2.java deleted file mode 100644 index b1b9e68b93..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoObjectInput2.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo.optimized; - -import org.apache.dubbo.common.serialize.Cleanable; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.kryo.utils.KryoUtils; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.KryoException; -import com.esotericsoftware.kryo.io.Input; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; - -/** - * Kryo object input implementation, kryo object can be clean - */ -public class KryoObjectInput2 implements ObjectInput, Cleanable { - - private Kryo kryo; - private Input input; - - public KryoObjectInput2(InputStream inputStream) { - input = new Input(inputStream); - this.kryo = KryoUtils.get(); - } - - @Override - public boolean readBool() throws IOException { - try { - return input.readBoolean(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public byte readByte() throws IOException { - try { - return input.readByte(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public short readShort() throws IOException { - try { - return input.readShort(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public int readInt() throws IOException { - try { - return input.readInt(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public long readLong() throws IOException { - try { - return input.readLong(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public float readFloat() throws IOException { - try { - return input.readFloat(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public double readDouble() throws IOException { - try { - return input.readDouble(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public byte[] readBytes() throws IOException { - try { - int len = input.readInt(); - if (len < 0) { - return null; - } else if (len == 0) { - return new byte[]{}; - } else { - return input.readBytes(len); - } - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public String readUTF() throws IOException { - try { - return input.readString(); - } catch (KryoException e) { - throw new IOException(e); - } - } - - @Override - public Object readObject() throws IOException, ClassNotFoundException { - try { - return kryo.readObjectOrNull(input, String.class); - } catch (KryoException e) { - throw new UnsupportedOperationException("Kryo serialization must know the input type when deserialize.", e); - } - } - - @Override - public Throwable readThrowable() throws IOException, ClassNotFoundException { - return (Throwable) kryo.readClassAndObject(input); - } - - @Override - public Object readEvent() throws IOException, ClassNotFoundException { - return kryo.readObjectOrNull(input, String.class); - } - - @Override - @SuppressWarnings("unchecked") - public T readObject(Class clazz) throws IOException, ClassNotFoundException { - return kryo.readObjectOrNull(input, clazz); - } - - @Override - @SuppressWarnings("unchecked") - public T readObject(Class clazz, Type type) throws IOException, ClassNotFoundException { - return readObject(clazz); - } - - @Override - public void cleanup() { - KryoUtils.release(kryo); - kryo = null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoObjectOutput2.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoObjectOutput2.java deleted file mode 100644 index 8500a06b7e..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoObjectOutput2.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo.optimized; - -import org.apache.dubbo.common.serialize.Cleanable; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.kryo.utils.KryoUtils; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.io.Output; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Kryo object output implementation, kryo object can be clean - */ -public class KryoObjectOutput2 implements ObjectOutput, Cleanable { - - private Output output; - private Kryo kryo; - - public KryoObjectOutput2(OutputStream outputStream) { - output = new Output(outputStream); - this.kryo = KryoUtils.get(); - } - - @Override - public void writeBool(boolean v) throws IOException { - output.writeBoolean(v); - } - - @Override - public void writeByte(byte v) throws IOException { - output.writeByte(v); - } - - @Override - public void writeShort(short v) throws IOException { - output.writeShort(v); - } - - @Override - public void writeInt(int v) throws IOException { - output.writeInt(v); - } - - @Override - public void writeLong(long v) throws IOException { - output.writeLong(v); - } - - @Override - public void writeFloat(float v) throws IOException { - output.writeFloat(v); - } - - @Override - public void writeDouble(double v) throws IOException { - output.writeDouble(v); - } - - @Override - public void writeBytes(byte[] v) throws IOException { - if (v == null) { - output.writeInt(-1); - } else { - writeBytes(v, 0, v.length); - } - } - - @Override - public void writeBytes(byte[] v, int off, int len) throws IOException { - if (v == null) { - output.writeInt(-1); - } else { - output.writeInt(len); - output.write(v, off, len); - } - } - - - @Override - public void writeUTF(String v) throws IOException { - output.writeString(v); - } - - @Override - public void writeObject(Object v) throws IOException { - kryo.writeObjectOrNull(output, v, v.getClass()); - } - - @Override - public void writeThrowable(Object v) throws IOException { - kryo.writeClassAndObject(output, v); - } - - @Override - public void flushBuffer() throws IOException { - output.flush(); - } - - @Override - public void cleanup() { - KryoUtils.release(kryo); - kryo = null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoSerialization2.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoSerialization2.java deleted file mode 100644 index 189cfde667..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/optimized/KryoSerialization2.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo.optimized; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.serialize.Constants; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * TODO for now kryo serialization doesn't deny classes that don't implement the serializable interface - * - *
    - *     e.g. <dubbo:protocol serialization="kryo" />
    - * 
    - */ -public class KryoSerialization2 implements Serialization { - - @Override - public byte getContentTypeId() { - return Constants.KRYO_SERIALIZATION2_ID; - } - - @Override - public String getContentType() { - return "x-application/kryo"; - } - - @Override - public ObjectOutput serialize(URL url, OutputStream out) throws IOException { - return new KryoObjectOutput2(out); - } - - @Override - public ObjectInput deserialize(URL url, InputStream is) throws IOException { - return new KryoObjectInput2(is); - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/AbstractKryoFactory.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/AbstractKryoFactory.java deleted file mode 100644 index a8b058dd7d..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/AbstractKryoFactory.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo.utils; - -import com.esotericsoftware.kryo.serializers.JavaSerializer; -import org.apache.dubbo.common.serialize.kryo.CompatibleKryo; -import org.apache.dubbo.common.serialize.support.SerializableClassRegistry; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.Serializer; -import com.esotericsoftware.kryo.pool.KryoFactory; -import com.esotericsoftware.kryo.serializers.DefaultSerializers; -import de.javakaffee.kryoserializers.ArraysAsListSerializer; -import de.javakaffee.kryoserializers.BitSetSerializer; -import de.javakaffee.kryoserializers.GregorianCalendarSerializer; -import de.javakaffee.kryoserializers.JdkProxySerializer; -import de.javakaffee.kryoserializers.RegexSerializer; -import de.javakaffee.kryoserializers.SynchronizedCollectionsSerializer; -import de.javakaffee.kryoserializers.URISerializer; -import de.javakaffee.kryoserializers.UUIDSerializer; -import de.javakaffee.kryoserializers.UnmodifiableCollectionsSerializer; - -import java.lang.reflect.InvocationHandler; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.URI; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.BitSet; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Hashtable; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.Set; -import java.util.TreeSet; -import java.util.UUID; -import java.util.Vector; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Pattern; - -public abstract class AbstractKryoFactory implements KryoFactory { - - private final Set registrations = new LinkedHashSet(); - - private boolean registrationRequired; - - private volatile boolean kryoCreated; - - public AbstractKryoFactory() { - - } - - /** - * only supposed to be called at startup time - * - * later may consider adding support for custom serializer, custom id, etc - */ - public void registerClass(Class clazz) { - - if (kryoCreated) { - throw new IllegalStateException("Can't register class after creating kryo instance"); - } - registrations.add(clazz); - } - - @Override - public Kryo create() { - if (!kryoCreated) { - kryoCreated = true; - } - - Kryo kryo = new CompatibleKryo(); - - // TODO -// kryo.setReferences(false); - kryo.setRegistrationRequired(registrationRequired); - - kryo.addDefaultSerializer(Throwable.class, new JavaSerializer()); - kryo.register(Arrays.asList("").getClass(), new ArraysAsListSerializer()); - kryo.register(GregorianCalendar.class, new GregorianCalendarSerializer()); - kryo.register(InvocationHandler.class, new JdkProxySerializer()); - kryo.register(BigDecimal.class, new DefaultSerializers.BigDecimalSerializer()); - kryo.register(BigInteger.class, new DefaultSerializers.BigIntegerSerializer()); - kryo.register(Pattern.class, new RegexSerializer()); - kryo.register(BitSet.class, new BitSetSerializer()); - kryo.register(URI.class, new URISerializer()); - kryo.register(UUID.class, new UUIDSerializer()); - UnmodifiableCollectionsSerializer.registerSerializers(kryo); - SynchronizedCollectionsSerializer.registerSerializers(kryo); - - // now just added some very common classes - // TODO optimization - kryo.register(HashMap.class); - kryo.register(ArrayList.class); - kryo.register(LinkedList.class); - kryo.register(HashSet.class); - kryo.register(TreeSet.class); - kryo.register(Hashtable.class); - kryo.register(Date.class); - kryo.register(Calendar.class); - kryo.register(ConcurrentHashMap.class); - kryo.register(SimpleDateFormat.class); - kryo.register(GregorianCalendar.class); - kryo.register(Vector.class); - kryo.register(BitSet.class); - kryo.register(StringBuffer.class); - kryo.register(StringBuilder.class); - kryo.register(Object.class); - kryo.register(Object[].class); - kryo.register(String[].class); - kryo.register(byte[].class); - kryo.register(char[].class); - kryo.register(int[].class); - kryo.register(float[].class); - kryo.register(double[].class); - - for (Class clazz : registrations) { - kryo.register(clazz); - } - - SerializableClassRegistry.getRegisteredClasses().forEach((clazz, ser) -> { - if (ser == null) { - kryo.register(clazz); - } else { - kryo.register(clazz, (Serializer) ser); - } - }); - - return kryo; - } - - public void setRegistrationRequired(boolean registrationRequired) { - this.registrationRequired = registrationRequired; - } - - public abstract void returnKryo(Kryo kryo); - - public abstract Kryo getKryo(); -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/KryoUtils.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/KryoUtils.java deleted file mode 100644 index 93cbb5dfa6..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/KryoUtils.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo.utils; - -import com.esotericsoftware.kryo.Kryo; - -/** - * The kryo utils used by dubbo - * - * @since 2.6.0 - */ -public class KryoUtils { - private static AbstractKryoFactory kryoFactory = new ThreadLocalKryoFactory(); - - public static Kryo get() { - return kryoFactory.getKryo(); - } - - public static void release(Kryo kryo) { - kryoFactory.returnKryo(kryo); - } - - public static void register(Class clazz) { - kryoFactory.registerClass(clazz); - } - - public static void setRegistrationRequired(boolean registrationRequired) { - kryoFactory.setRegistrationRequired(registrationRequired); - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/PooledKryoFactory.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/PooledKryoFactory.java deleted file mode 100644 index d9102e186d..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/PooledKryoFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo.utils; - -import com.esotericsoftware.kryo.Kryo; -import com.esotericsoftware.kryo.pool.KryoPool; - -public class PooledKryoFactory extends AbstractKryoFactory { - - private KryoPool pool; - - public PooledKryoFactory() { - // Build pool with SoftReferences enabled (optional) - pool = new KryoPool.Builder(this).softReferences().build(); - } - - @Override - public Kryo getKryo() { - return pool.borrow(); - } - - @Override - public void returnKryo(Kryo kryo) { - pool.release(kryo); - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/PrototypeKryoFactory.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/PrototypeKryoFactory.java deleted file mode 100644 index 5a53f468e5..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/PrototypeKryoFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo.utils; - -import com.esotericsoftware.kryo.Kryo; - -public class PrototypeKryoFactory extends AbstractKryoFactory { - - @Override - public void returnKryo(Kryo kryo) { - // do nothing - } - - @Override - public Kryo getKryo() { - return create(); - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/ReflectionUtils.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/ReflectionUtils.java deleted file mode 100644 index 7c3b45a816..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/ReflectionUtils.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo.utils; - -public abstract class ReflectionUtils { - - public static boolean checkZeroArgConstructor(Class clazz) { - try { - clazz.getDeclaredConstructor(); - return true; - } catch (NoSuchMethodException e) { - return false; - } - } - - public static boolean isJdk(Class clazz) { - return clazz.getName().startsWith("java.") || clazz.getName().startsWith("javax."); - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/ThreadLocalKryoFactory.java b/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/ThreadLocalKryoFactory.java deleted file mode 100644 index d3599ec224..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/java/org/apache/dubbo/common/serialize/kryo/utils/ThreadLocalKryoFactory.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.kryo.utils; - -import com.esotericsoftware.kryo.Kryo; - -public class ThreadLocalKryoFactory extends AbstractKryoFactory { - - private final ThreadLocal holder = new ThreadLocal() { - @Override - protected Kryo initialValue() { - return create(); - } - }; - - @Override - public void returnKryo(Kryo kryo) { - // do nothing - } - - @Override - public Kryo getKryo() { - return holder.get(); - } -} diff --git a/dubbo-serialization/dubbo-serialization-kryo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization b/dubbo-serialization/dubbo-serialization-kryo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization deleted file mode 100644 index 331e520ec9..0000000000 --- a/dubbo-serialization/dubbo-serialization-kryo/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization +++ /dev/null @@ -1,2 +0,0 @@ -kryo=org.apache.dubbo.common.serialize.kryo.KryoSerialization -kryo2=org.apache.dubbo.common.serialize.kryo.optimized.KryoSerialization2 \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-native-hession/pom.xml b/dubbo-serialization/dubbo-serialization-native-hession/pom.xml deleted file mode 100644 index 8c710f6e9e..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - org.apache.dubbo - dubbo-serialization - ${revision} - ../pom.xml - - 4.0.0 - - dubbo-serialization-native-hession - jar - ${project.artifactId} - The native-hession serialization module of dubbo project - - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - com.caucho - hessian - - - \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectInput.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectInput.java deleted file mode 100644 index 4bbb13fc97..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectInput.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian; - -import com.caucho.hessian.io.Hessian2Input; -import org.apache.dubbo.common.serialize.ObjectInput; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; - -/** - * Hessian2 Object input. - */ -public class Hessian2ObjectInput implements ObjectInput { - private final Hessian2Input input; - - public Hessian2ObjectInput(InputStream is) { - input = new Hessian2Input(is); - input.setSerializerFactory(Hessian2SerializerFactory.INSTANCE); - } - - @Override - public boolean readBool() throws IOException { - return input.readBoolean(); - } - - @Override - public byte readByte() throws IOException { - return (byte) input.readInt(); - } - - @Override - public short readShort() throws IOException { - return (short) input.readInt(); - } - - @Override - public int readInt() throws IOException { - return input.readInt(); - } - - @Override - public long readLong() throws IOException { - return input.readLong(); - } - - @Override - public float readFloat() throws IOException { - return (float) input.readDouble(); - } - - @Override - public double readDouble() throws IOException { - return input.readDouble(); - } - - @Override - public byte[] readBytes() throws IOException { - return input.readBytes(); - } - - @Override - public String readUTF() throws IOException { - return input.readString(); - } - - @Override - public Object readObject() throws IOException { - return input.readObject(); - } - - @Override - @SuppressWarnings("unchecked") - public T readObject(Class cls) throws IOException { - return (T) input.readObject(cls); - } - - @Override - public T readObject(Class cls, Type type) throws IOException { - return readObject(cls); - } - -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectOutput.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectOutput.java deleted file mode 100644 index e3f5fa2661..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2ObjectOutput.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian; - -import com.caucho.hessian.io.Hessian2Output; -import org.apache.dubbo.common.serialize.ObjectOutput; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Hessian2 Object output. - */ -public class Hessian2ObjectOutput implements ObjectOutput { - private final Hessian2Output output; - - public Hessian2ObjectOutput(OutputStream os) { - output = new Hessian2Output(os); - output.setSerializerFactory(Hessian2SerializerFactory.INSTANCE); - } - - @Override - public void writeBool(boolean v) throws IOException { - output.writeBoolean(v); - } - - @Override - public void writeByte(byte v) throws IOException { - output.writeInt(v); - } - - @Override - public void writeShort(short v) throws IOException { - output.writeInt(v); - } - - @Override - public void writeInt(int v) throws IOException { - output.writeInt(v); - } - - @Override - public void writeLong(long v) throws IOException { - output.writeLong(v); - } - - @Override - public void writeFloat(float v) throws IOException { - output.writeDouble(v); - } - - @Override - public void writeDouble(double v) throws IOException { - output.writeDouble(v); - } - - @Override - public void writeBytes(byte[] b) throws IOException { - output.writeBytes(b); - } - - @Override - public void writeBytes(byte[] b, int off, int len) throws IOException { - output.writeBytes(b, off, len); - } - - @Override - public void writeUTF(String v) throws IOException { - output.writeString(v); - } - - @Override - public void writeObject(Object obj) throws IOException { - output.writeObject(obj); - } - - @Override - public void flushBuffer() throws IOException { - output.flushBuffer(); - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java deleted file mode 100644 index ee5887682d..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2Serialization.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian; - - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import static org.apache.dubbo.common.serialize.Constants.NATIVE_HESSIAN_SERIALIZATION_ID; - -public class Hessian2Serialization implements Serialization { - - @Override - public byte getContentTypeId() { - return NATIVE_HESSIAN_SERIALIZATION_ID; - } - - @Override - public String getContentType() { - return "x-application/native-hessian"; - } - - @Override - public ObjectOutput serialize(URL url, OutputStream out) throws IOException { - return new Hessian2ObjectOutput(out); - } - - @Override - public ObjectInput deserialize(URL url, InputStream is) throws IOException { - return new Hessian2ObjectInput(is); - } - -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2SerializerFactory.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2SerializerFactory.java deleted file mode 100644 index 2e87375c5f..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Hessian2SerializerFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian; - -import com.caucho.hessian.io.Deserializer; -import com.caucho.hessian.io.HessianProtocolException; -import com.caucho.hessian.io.Serializer; -import com.caucho.hessian.io.SerializerFactory; - -public class Hessian2SerializerFactory extends SerializerFactory { - public static final SerializerFactory INSTANCE = new Hessian2SerializerFactory(); - - private Hessian2SerializerFactory() { - super(); - } - - @Override - protected Serializer loadSerializer(Class cl) throws HessianProtocolException { - Serializer serializer = Java8SerializerFactory.INSTANCE.getSerializer(cl); - return serializer != null ? serializer : super.loadSerializer(cl); - } - - @Override - protected Deserializer loadDeserializer(Class cl) throws HessianProtocolException { - Deserializer deserializer = Java8SerializerFactory.INSTANCE.getDeserializer(cl); - return deserializer != null ? deserializer : super.loadDeserializer(cl); - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Java8SerializerFactory.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Java8SerializerFactory.java deleted file mode 100644 index 6280023315..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/Java8SerializerFactory.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian; - - -import com.caucho.hessian.io.AbstractSerializerFactory; -import com.caucho.hessian.io.ExtSerializerFactory; -import com.caucho.hessian.io.HessianProtocolException; -import com.caucho.hessian.io.Serializer; -import org.apache.dubbo.serialize.hessian.serializer.java8.DurationHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.InstantHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.LocalDateHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.LocalDateTimeHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.LocalTimeHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.MonthDayHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.OffsetDateTimeHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.OffsetTimeHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.PeriodHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.YearHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.YearMonthHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.ZoneIdSerializer; -import org.apache.dubbo.serialize.hessian.serializer.java8.ZoneOffsetHandle; -import org.apache.dubbo.serialize.hessian.serializer.java8.ZonedDateTimeHandle; - -import static org.apache.dubbo.serialize.hessian.serializer.java8.Java8TimeSerializer.create; - - -public class Java8SerializerFactory extends ExtSerializerFactory { - public static final AbstractSerializerFactory INSTANCE = new Java8SerializerFactory(); - - private Java8SerializerFactory() { - if (isJava8()) { - try { - this.addSerializer(Class.forName("java.time.LocalTime"), create(LocalTimeHandle.class)); - this.addSerializer(Class.forName("java.time.LocalDate"), create(LocalDateHandle.class)); - this.addSerializer(Class.forName("java.time.LocalDateTime"), create(LocalDateTimeHandle.class)); - - this.addSerializer(Class.forName("java.time.Instant"), create(InstantHandle.class)); - this.addSerializer(Class.forName("java.time.Duration"), create(DurationHandle.class)); - this.addSerializer(Class.forName("java.time.Period"), create(PeriodHandle.class)); - - this.addSerializer(Class.forName("java.time.Year"), create(YearHandle.class)); - this.addSerializer(Class.forName("java.time.YearMonth"), create(YearMonthHandle.class)); - this.addSerializer(Class.forName("java.time.MonthDay"), create(MonthDayHandle.class)); - - this.addSerializer(Class.forName("java.time.OffsetDateTime"), create(OffsetDateTimeHandle.class)); - this.addSerializer(Class.forName("java.time.ZoneOffset"), create(ZoneOffsetHandle.class)); - this.addSerializer(Class.forName("java.time.OffsetTime"), create(OffsetTimeHandle.class)); - this.addSerializer(Class.forName("java.time.ZonedDateTime"), create(ZonedDateTimeHandle.class)); - } catch (ClassNotFoundException e) { - // ignore - } - } - } - - @Override - public Serializer getSerializer(Class cl) throws HessianProtocolException { - return isZoneId(cl) ? ZoneIdSerializer.getInstance() : super.getSerializer(cl); - } - - private static boolean isZoneId(Class cl) { - try { - return isJava8() && Class.forName("java.time.ZoneId").isAssignableFrom(cl); - } catch (ClassNotFoundException e) { - // ignore - } - return false; - } - - private static boolean isJava8() { - String javaVersion = System.getProperty("java.specification.version"); - return Double.valueOf(javaVersion) >= 1.8; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/DurationHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/DurationHandle.java deleted file mode 100755 index 67615f3d86..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/DurationHandle.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.Duration; - -public class DurationHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = -4367309317780077156L; - - private long seconds; - private int nanos; - - public DurationHandle() { - } - - public DurationHandle(Object o) { - try { - Duration duration = (Duration) o; - this.seconds = duration.getSeconds(); - this.nanos = duration.getNano(); - } catch (Throwable t) { - // ignore - } - } - - private Object readResolve() { - try { - return Duration.ofSeconds(seconds, nanos); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/InstantHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/InstantHandle.java deleted file mode 100755 index 6b9a1a8d9b..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/InstantHandle.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.Instant; - -public class InstantHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = -4367309317780077156L; - - private long seconds; - private int nanos; - - public InstantHandle() { - } - - public InstantHandle(Object o) { - try { - Instant instant = (Instant) o; - this.seconds = instant.getEpochSecond(); - this.nanos = instant.getNano(); - } catch (Throwable t) { - // ignore - } - } - - - private Object readResolve() { - try { - return Instant.ofEpochSecond(seconds, nanos); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/Java8TimeSerializer.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/Java8TimeSerializer.java deleted file mode 100755 index 4b4494db52..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/Java8TimeSerializer.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.AbstractHessianOutput; -import com.caucho.hessian.io.AbstractSerializer; - -import java.io.IOException; -import java.lang.reflect.Constructor; - -public class Java8TimeSerializer extends AbstractSerializer { - - // Type of handle - private Class handleType; - - private Java8TimeSerializer(Class handleType) { - this.handleType = handleType; - } - - public static Java8TimeSerializer create(Class handleType) { - return new Java8TimeSerializer(handleType); - } - - @Override - public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { - if (obj == null) { - out.writeNull(); - return; - } - - T handle = null; - try { - Constructor constructor = handleType.getConstructor(Object.class); - handle = constructor.newInstance(obj); - } catch (Exception e) { - throw new RuntimeException("the class :" + handleType.getName() + " construct failed:" + e.getMessage(), e); - } - - out.writeObject(handle); - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateHandle.java deleted file mode 100755 index f994bc4c2d..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateHandle.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.LocalDate; - -public class LocalDateHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = 166018689500019951L; - - private int year; - private int month; - private int day; - - public LocalDateHandle() { - } - - public LocalDateHandle(Object o) { - try { - LocalDate localDate = (LocalDate) o; - this.year = localDate.getYear(); - this.month = localDate.getMonthValue(); - this.day = localDate.getDayOfMonth(); - } catch (Throwable t) { - // ignore - } - } - - public Object readResolve() { - try { - return LocalDate.of(year, month, day); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateTimeHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateTimeHandle.java deleted file mode 100755 index 094ced53c4..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalDateTimeHandle.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; - -public class LocalDateTimeHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = 7563825215275989361L; - - private LocalDate date; - private LocalTime time; - - public LocalDateTimeHandle() { - } - - public LocalDateTimeHandle(Object o) { - try { - LocalDateTime localDateTime = (LocalDateTime) o; - date = localDateTime.toLocalDate(); - time = localDateTime.toLocalTime(); - } catch (Throwable t) { - // ignore - } - } - - private Object readResolve() { - try { - return LocalDateTime.of(date, time); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalTimeHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalTimeHandle.java deleted file mode 100755 index b0d9619901..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/LocalTimeHandle.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.LocalTime; - -public class LocalTimeHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = -5892919085390462315L; - - private int hour; - private int minute; - private int second; - private int nano; - - public LocalTimeHandle() { - } - - public LocalTimeHandle(Object o) { - try { - LocalTime localTime = (LocalTime) o; - this.hour = localTime.getHour(); - this.minute = localTime.getMinute(); - this.second = localTime.getSecond(); - this.nano = localTime.getNano(); - } catch (Throwable t) { - // ignore - } - } - - private Object readResolve() { - try { - return LocalTime.of(hour, minute, second, nano); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/MonthDayHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/MonthDayHandle.java deleted file mode 100755 index 8c19273c10..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/MonthDayHandle.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.MonthDay; - -public class MonthDayHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = 5288238558666577745L; - - private int month; - private int day; - - public MonthDayHandle() { - } - - public MonthDayHandle(Object o) { - try { - MonthDay monthDay = (MonthDay) o; - this.month = monthDay.getMonthValue(); - this.day = monthDay.getDayOfMonth(); - } catch (Throwable t) { - // ignore - } - } - - private Object readResolve() { - try { - return MonthDay.of(month, day); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetDateTimeHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetDateTimeHandle.java deleted file mode 100755 index b785266ef2..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetDateTimeHandle.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; - -public class OffsetDateTimeHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = -7823900532640515312L; - - private LocalDateTime dateTime; - private ZoneOffset offset; - - public OffsetDateTimeHandle() { - } - - public OffsetDateTimeHandle(Object o) { - try { - OffsetDateTime offsetDateTime = (OffsetDateTime) o; - this.dateTime = offsetDateTime.toLocalDateTime(); - this.offset = offsetDateTime.getOffset(); - } catch (Throwable t) { - // ignore - } - } - - private Object readResolve() { - try { - return OffsetDateTime.of(dateTime, offset); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetTimeHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetTimeHandle.java deleted file mode 100755 index 5a5730054f..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/OffsetTimeHandle.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.LocalTime; -import java.time.OffsetTime; -import java.time.ZoneOffset; - -public class OffsetTimeHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = -3269846941421652860L; - - private LocalTime localTime; - private ZoneOffset zoneOffset; - - public OffsetTimeHandle() { - } - - public OffsetTimeHandle(Object o) { - try { - OffsetTime offsetTime = (OffsetTime) o; - this.zoneOffset = offsetTime.getOffset(); - this.localTime = offsetTime.toLocalTime(); - } catch (Throwable t) { - // ignore - } - } - - private Object readResolve() { - try { - return OffsetTime.of(localTime, zoneOffset); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/PeriodHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/PeriodHandle.java deleted file mode 100755 index d29b39f771..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/PeriodHandle.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.Period; - - -public class PeriodHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = 4399720381283781186L; - - private int years; - private int months; - private int days; - - public PeriodHandle() { - } - - public PeriodHandle(Object o) { - try { - Period period = (Period) o; - this.years = period.getYears(); - this.months = period.getMonths(); - this.days = period.getDays(); - } catch (Throwable t) { - // ignore - } - } - - private Object readResolve() { - try { - return Period.of(years, months, days); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearHandle.java deleted file mode 100755 index 6560c0d839..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearHandle.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.Year; - -public class YearHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = -6299552890287487926L; - - private int year; - - public YearHandle() { - } - - public YearHandle(Object o) { - try { - Year y = (Year) o; - this.year = y.getValue(); - } catch (Throwable t) { - // ignore - } - - } - - private Object readResolve() { - try { - return Year.of(year); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearMonthHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearMonthHandle.java deleted file mode 100755 index 5f67c2ef75..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/YearMonthHandle.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.YearMonth; - -public class YearMonthHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = -4150786187896925314L; - - private int year; - private int month; - - public YearMonthHandle() { - } - - public YearMonthHandle(Object o) { - try { - YearMonth yearMonth = (YearMonth) o; - this.year = yearMonth.getYear(); - this.month = yearMonth.getMonthValue(); - } catch (Throwable t) { - // ignore - } - } - - private Object readResolve() { - try { - return YearMonth.of(year, month); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdHandle.java deleted file mode 100755 index f1254690d7..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdHandle.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.ZoneId; - -public class ZoneIdHandle implements HessianHandle, Serializable { - - private static final long serialVersionUID = 8789182864066905552L; - - private String zoneId; - - public ZoneIdHandle() { - } - - public ZoneIdHandle(Object o) { - try { - ZoneId zoneId = (ZoneId) o; - this.zoneId = zoneId.getId(); - } catch (Throwable t) { - // ignore - } - } - - private Object readResolve() { - try { - return ZoneId.of(this.zoneId); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdSerializer.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdSerializer.java deleted file mode 100755 index 7104670296..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneIdSerializer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.AbstractHessianOutput; -import com.caucho.hessian.io.AbstractSerializer; - -import java.io.IOException; - -public class ZoneIdSerializer extends AbstractSerializer { - - private static final ZoneIdSerializer SERIALIZER = new ZoneIdSerializer(); - - public static ZoneIdSerializer getInstance() { - return SERIALIZER; - } - - @Override - public void writeObject(Object obj, AbstractHessianOutput out) throws IOException { - if (obj == null) { - out.writeNull(); - } else { - out.writeObject(new ZoneIdHandle(obj)); - } - } - -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneOffsetHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneOffsetHandle.java deleted file mode 100755 index f7e622a73c..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZoneOffsetHandle.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.ZoneOffset; - -public class ZoneOffsetHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = 8841589723587858789L; - - private int seconds; - - public ZoneOffsetHandle() { - } - - public ZoneOffsetHandle(Object o) { - try { - ZoneOffset zoneOffset = (ZoneOffset) o; - this.seconds = zoneOffset.getTotalSeconds(); - } catch (Throwable t) { - // ignore - } - } - - private Object readResolve() { - try { - return ZoneOffset.ofTotalSeconds(seconds); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZonedDateTimeHandle.java b/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZonedDateTimeHandle.java deleted file mode 100755 index 44b3ff536c..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/java/org/apache/dubbo/serialize/hessian/serializer/java8/ZonedDateTimeHandle.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian.serializer.java8; - - -import com.caucho.hessian.io.HessianHandle; - -import java.io.Serializable; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; - -public class ZonedDateTimeHandle implements HessianHandle, Serializable { - private static final long serialVersionUID = -6933460123278647569L; - - private LocalDateTime dateTime; - private ZoneOffset offset; - private String zoneId; - - - public ZonedDateTimeHandle() { - } - - public ZonedDateTimeHandle(Object o) { - try { - ZonedDateTime zonedDateTime = (ZonedDateTime) o; - this.dateTime = zonedDateTime.toLocalDateTime(); - this.offset = zonedDateTime.getOffset(); - ZoneId zone = zonedDateTime.getZone(); - if (zone != null) { - this.zoneId = zone.getId(); - } - } catch (Throwable t) { - // ignore - } - } - - private Object readResolve() { - try { - return ZonedDateTime.ofLocal(dateTime, ZoneId.of(zoneId), offset); - } catch (Throwable t) { - // ignore - } - return null; - } -} diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization b/dubbo-serialization/dubbo-serialization-native-hession/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization deleted file mode 100644 index ad6601604e..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization +++ /dev/null @@ -1 +0,0 @@ -native-hessian=org.apache.dubbo.serialize.hessian.Hessian2Serialization \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-native-hession/src/test/java/org/apache/dubbo/serialize/hessian/Java8TimeSerializerTest.java b/dubbo-serialization/dubbo-serialization-native-hession/src/test/java/org/apache/dubbo/serialize/hessian/Java8TimeSerializerTest.java deleted file mode 100644 index a481dc0cca..0000000000 --- a/dubbo-serialization/dubbo-serialization-native-hession/src/test/java/org/apache/dubbo/serialize/hessian/Java8TimeSerializerTest.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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.apache.dubbo.serialize.hessian; - -import com.caucho.hessian.io.Hessian2Input; -import com.caucho.hessian.io.Hessian2Output; -import com.caucho.hessian.io.SerializerFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.time.Duration; -import java.time.Instant; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.LocalTime; -import java.time.MonthDay; -import java.time.OffsetDateTime; -import java.time.OffsetTime; -import java.time.Period; -import java.time.Year; -import java.time.YearMonth; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.util.Calendar; - -/** - * Test Java8TimeSerializer class - */ -public class Java8TimeSerializerTest { - - private static SerializerFactory factory = Hessian2SerializerFactory.INSTANCE; - private static ByteArrayOutputStream os = new ByteArrayOutputStream(); - - @Test - public void testNull() throws IOException { - testJava8Time(null); - } - - @Test - public void testInstant() throws Exception { - Instant.now(); - testJava8Time(Instant.now()); - } - - @Test - public void testDuration() throws Exception { - testJava8Time(Duration.ofDays(2)); - } - - @Test - public void testLocalDate() throws Exception { - testJava8Time(LocalDate.now()); - } - - @Test - public void testLocalDateTime() throws Exception { - testJava8Time(LocalDateTime.now()); - } - - @Test - public void testLocalTime() throws Exception { - testJava8Time(LocalTime.now()); - } - - @Test - public void testYear() throws Exception { - testJava8Time(Year.now()); - } - - @Test - public void testYearMonth() throws Exception { - testJava8Time(YearMonth.now()); - } - - @Test - public void testMonthDay() throws Exception { - testJava8Time(MonthDay.now()); - } - - @Test - public void testPeriod() throws Exception { - testJava8Time(Period.ofDays(3)); - } - - @Test - public void testOffsetTime() throws Exception { - testJava8Time(OffsetTime.now()); - } - - @Test - public void testZoneOffset() throws Exception { - testJava8Time(ZoneOffset.ofHours(8)); - } - - @Test - public void testOffsetDateTime() throws Throwable { - testJava8Time(OffsetDateTime.now()); - } - - @Test - public void testZonedDateTime() throws Exception { - testJava8Time(ZonedDateTime.now()); - } - - @Test - public void testZoneId() throws Exception { - testJava8Time(ZoneId.of("America/New_York")); - } - - - @Test - public void testCalendar() throws IOException { - testJava8Time(Calendar.getInstance()); - } - - private void testJava8Time(Object expected) throws IOException { - os.reset(); - - Hessian2Output output = new Hessian2Output(os); - output.setSerializerFactory(factory); - output.writeObject(expected); - output.flush(); - - ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); - Hessian2Input input = new Hessian2Input(is); - input.setSerializerFactory(factory); - Object actual = input.readObject(); - - Assertions.assertEquals(expected, actual); - } -} diff --git a/dubbo-serialization/dubbo-serialization-protobuf/pom.xml b/dubbo-serialization/dubbo-serialization-protobuf/pom.xml deleted file mode 100644 index 65eb7b7a96..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - 4.0.0 - - org.apache.dubbo - dubbo-serialization - ${revision} - ../pom.xml - - dubbo-serialization-protobuf - jar - ${project.artifactId} - The protobuf serialization module of dubbo project - - false - 0.0.1-SNAPSHOT - - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - com.google.protobuf - protobuf-java - - - com.google.protobuf - protobuf-java-util - - - - - - - kr.motd.maven - os-maven-plugin - 1.6.1 - - - - - org.xolstice.maven.plugins - protobuf-maven-plugin - 0.5.1 - true - - com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier} - build/generated/source/proto/main/java - false - - - - - compile - test-compile - - - - - - org.codehaus.mojo - build-helper-maven-plugin - - - generate-sources - - add-source - - - - build/generated/source/proto/main/java - - - - - - - - diff --git a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonObjectInput.java b/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonObjectInput.java deleted file mode 100644 index 6a327471d2..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonObjectInput.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protobuf.support; - -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.protobuf.support.wrapper.MapValue; -import org.apache.dubbo.common.serialize.protobuf.support.wrapper.ThrowablePB; - -import com.google.protobuf.BoolValue; -import com.google.protobuf.BytesValue; -import com.google.protobuf.DoubleValue; -import com.google.protobuf.FloatValue; -import com.google.protobuf.Int32Value; -import com.google.protobuf.Int64Value; -import com.google.protobuf.StringValue; - -import java.io.BufferedReader; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - -import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; -import static org.apache.dubbo.common.constants.CommonConstants.MOCK_HEARTBEAT_EVENT; - -/** - * GenericGoogleProtobuf object input implementation - */ -public class GenericProtobufJsonObjectInput implements ObjectInput { - private final BufferedReader reader; - - public GenericProtobufJsonObjectInput(InputStream in) { - this.reader = new BufferedReader(new InputStreamReader(in)); - } - - @Override - public boolean readBool() throws IOException { - return read(BoolValue.class).getValue(); - } - - @Override - public byte readByte() throws IOException { - return (byte) read(Int32Value.class).getValue(); - } - - @Override - public short readShort() throws IOException { - return (short) read(Int32Value.class).getValue(); - } - - @Override - public int readInt() throws IOException { - return read(Int32Value.class).getValue(); - } - - @Override - public long readLong() throws IOException { - return read(Int64Value.class).getValue(); - } - - @Override - public float readFloat() throws IOException { - return read(FloatValue.class).getValue(); - } - - @Override - public double readDouble() throws IOException { - return read(DoubleValue.class).getValue(); - } - - @Override - public String readUTF() throws IOException { - return read(StringValue.class).getValue(); - } - - @Override - public byte[] readBytes() throws IOException { - return read(BytesValue.class).getValue().toByteArray(); - } - - @Override - public Object readObject() { - throw new UnsupportedOperationException("Provide the protobuf message type you want to read."); - } - - @Override - public T readObject(Class cls) throws IOException { - return read(cls); - } - - @Override - @SuppressWarnings("unchecked") - public T readObject(Class cls, Type type) throws IOException { - return readObject(cls); - } - - private String readLine() throws IOException { - String line = reader.readLine(); - if (line == null || line.trim().length() == 0) { - throw new EOFException(); - } - return line; - } - - private T read(Class cls) throws IOException { - if (!ProtobufUtils.isSupported(cls)) { - throw new IllegalArgumentException("This serialization only support google protobuf entity, the class is :" + cls.getName()); - } - - String json = readLine(); - return ProtobufUtils.deserializeJson(json, cls); - } - - @Override - public Throwable readThrowable() throws IOException { - String json = readLine(); - ThrowablePB.ThrowableProto throwableProto = ProtobufUtils.deserializeJson(json, ThrowablePB.ThrowableProto.class); - return ProtobufUtils.convertToException(throwableProto); - } - - /** - * FIXME, only supports transmission of String values. - * - * @return - * @throws IOException - * @throws ClassNotFoundException - */ - @Override - public Map readAttachments() throws IOException, ClassNotFoundException { - String json = readLine(); - Map attachments = ProtobufUtils.deserializeJson(json, MapValue.Map.class).getAttachmentsMap(); - Map genericAttachments = new HashMap<>(); - attachments.forEach((k, v) -> { - genericAttachments.put(k, v); - }); - return genericAttachments; - } - - @Override - public Object readEvent() throws IOException, ClassNotFoundException { - String eventData = readUTF(); - if (eventData.equals(MOCK_HEARTBEAT_EVENT)) { - eventData = HEARTBEAT_EVENT; - } - return eventData; - } -} diff --git a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonObjectOutput.java b/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonObjectOutput.java deleted file mode 100644 index bbcf05485c..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonObjectOutput.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protobuf.support; - -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.protobuf.support.wrapper.MapValue; - -import com.google.protobuf.BoolValue; -import com.google.protobuf.ByteString; -import com.google.protobuf.BytesValue; -import com.google.protobuf.DoubleValue; -import com.google.protobuf.FloatValue; -import com.google.protobuf.Int32Value; -import com.google.protobuf.Int64Value; -import com.google.protobuf.StringValue; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.util.HashMap; -import java.util.Map; - -import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; -import static org.apache.dubbo.common.constants.CommonConstants.MOCK_HEARTBEAT_EVENT; - -/** - * GenericGoogleProtobuf object output implementation - */ -public class GenericProtobufJsonObjectOutput implements ObjectOutput { - - private final PrintWriter writer; - - public GenericProtobufJsonObjectOutput(OutputStream out) { - this.writer = new PrintWriter(new OutputStreamWriter(out)); - } - - @Override - public void writeBool(boolean v) throws IOException { - - writeObject(BoolValue.newBuilder().setValue(v).build()); - } - - @Override - public void writeByte(byte v) throws IOException { - writeObject(Int32Value.newBuilder().setValue((v)).build()); - } - - @Override - public void writeShort(short v) throws IOException { - writeObject(Int32Value.newBuilder().setValue(v).build()); - } - - @Override - public void writeInt(int v) throws IOException { - writeObject(Int32Value.newBuilder().setValue(v).build()); - } - - @Override - public void writeLong(long v) throws IOException { - writeObject(Int64Value.newBuilder().setValue(v).build()); - } - - @Override - public void writeFloat(float v) throws IOException { - writeObject(FloatValue.newBuilder().setValue(v).build()); - } - - @Override - public void writeDouble(double v) throws IOException { - writeObject(DoubleValue.newBuilder().setValue(v).build()); - } - - @Override - public void writeUTF(String v) throws IOException { - writeObject(StringValue.newBuilder().setValue(v).build()); - } - - @Override - public void writeBytes(byte[] b) throws IOException { - writeObject(BytesValue.newBuilder().setValue(ByteString.copyFrom(b)).build()); - } - - @Override - public void writeBytes(byte[] b, int off, int len) throws IOException { - writeObject(BytesValue.newBuilder().setValue(ByteString.copyFrom(b, off, len)).build()); - } - - - @Override - public void writeObject(Object obj) throws IOException { - if (obj == null) { - throw new IllegalArgumentException("This serialization only support google protobuf object, the object is : null"); - } - if (!ProtobufUtils.isSupported(obj.getClass())) { - throw new IllegalArgumentException("This serialization only support google protobuf object, the object class is: " + obj.getClass().getName()); - } - - writer.write(ProtobufUtils.serializeJson(obj)); - writer.println(); - writer.flush(); - } - - @Override - public void writeThrowable(Object th) throws IOException { - if (th instanceof Throwable && !ProtobufUtils.isSupported(th.getClass())) { - th = ProtobufUtils.convertToThrowableProto((Throwable) th); - } - writer.write(ProtobufUtils.serializeJson(th)); - writer.println(); - writer.flush(); - } - - @Override - public void writeEvent(Object data) throws IOException { - if (data == HEARTBEAT_EVENT) { - data = MOCK_HEARTBEAT_EVENT; - } - writeUTF((String) data); - } - - /** - * FIXME, only supports transmission of String values. - * - * @param attachments - * @throws IOException - */ - @Override - public void writeAttachments(Map attachments) throws IOException { - if (attachments == null) { - return; - } - - Map stringAttachments = new HashMap<>(); - attachments.forEach((k, v) -> stringAttachments.put(k, (String) v)); - MapValue.Map proto = MapValue.Map.newBuilder().putAllAttachments(stringAttachments).build(); - writer.write(ProtobufUtils.serializeJson(proto)); - writer.println(); - writer.flush(); - } - - @Override - public void flushBuffer() { - writer.flush(); - } - -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonSerialization.java b/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonSerialization.java deleted file mode 100644 index 0d2fae628c..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufJsonSerialization.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protobuf.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; - -import java.io.InputStream; -import java.io.OutputStream; - -import static org.apache.dubbo.common.serialize.Constants.PROTOBUF_JSON_SERIALIZATION_ID; - -/** - * This serizalization is use for google protobuf generic reference. - * The entity be transported between client and server by json string. - */ -public class GenericProtobufJsonSerialization implements Serialization { - - @Override - public byte getContentTypeId() { - return PROTOBUF_JSON_SERIALIZATION_ID; - } - - @Override - public String getContentType() { - return "text/json"; - } - - @Override - public ObjectOutput serialize(URL url, OutputStream output) { - return new GenericProtobufJsonObjectOutput(output); - } - - @Override - public ObjectInput deserialize(URL url, InputStream input) { - return new GenericProtobufJsonObjectInput(input); - } -} diff --git a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectInput.java b/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectInput.java deleted file mode 100644 index 44005f7a64..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectInput.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protobuf.support; - -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.protobuf.support.wrapper.MapValue; -import org.apache.dubbo.common.serialize.protobuf.support.wrapper.ThrowablePB; - -import com.google.protobuf.BoolValue; -import com.google.protobuf.BytesValue; -import com.google.protobuf.DoubleValue; -import com.google.protobuf.FloatValue; -import com.google.protobuf.Int32Value; -import com.google.protobuf.Int64Value; -import com.google.protobuf.StringValue; - -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.Map; - -import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; -import static org.apache.dubbo.common.constants.CommonConstants.MOCK_HEARTBEAT_EVENT; - -public class GenericProtobufObjectInput implements ObjectInput { - private final InputStream is; - - public GenericProtobufObjectInput(InputStream is) { - this.is = is; - } - - @Override - public boolean readBool() throws IOException { - return read(BoolValue.class).getValue(); - } - - @Override - public byte readByte() throws IOException { - return (byte) read(Int32Value.class).getValue(); - } - - @Override - public short readShort() throws IOException { - return (short) read(Int32Value.class).getValue(); - } - - @Override - public int readInt() throws IOException { - return read(Int32Value.class).getValue(); - } - - @Override - public long readLong() throws IOException { - return read(Int64Value.class).getValue(); - } - - @Override - public float readFloat() throws IOException { - return read(FloatValue.class).getValue(); - } - - @Override - public double readDouble() throws IOException { - return read(DoubleValue.class).getValue(); - } - - @Override - public String readUTF() throws IOException { - return read(StringValue.class).getValue(); - } - - @Override - public byte[] readBytes() throws IOException { - return read(BytesValue.class).getValue().toByteArray(); - } - - /** - * Avoid using readObject, always try to pass the target class type for the data you want to read. - * - * @return - */ - @Override - public Object readObject() { - throw new UnsupportedOperationException("Provide the protobuf message type you want to read."); - } - - @Override - public T readObject(Class cls) throws IOException { - return read(cls); - } - - @Override - public T readObject(Class cls, Type type) throws IOException { - return readObject(cls); - } - - @SuppressWarnings("unchecked") - private T read(Class cls) throws IOException { - if (!ProtobufUtils.isSupported(cls)) { - throw new IllegalArgumentException("This serialization only support google protobuf messages, but the actual input type is :" + cls.getName()); - } - - return ProtobufUtils.deserialize(is, cls); - } - - @Override - public Throwable readThrowable() throws IOException { - ThrowablePB.ThrowableProto throwableProto = ProtobufUtils.deserialize(is, ThrowablePB.ThrowableProto.class); - return ProtobufUtils.convertToException(throwableProto); - } - - @Override - public Object readEvent() throws IOException { - String eventData = readUTF(); - if (eventData.equals(MOCK_HEARTBEAT_EVENT)) { - eventData = HEARTBEAT_EVENT; - } - return eventData; - } - - @Override - public Map readAttachments() throws IOException { - Map stringAttachments = ProtobufUtils.deserialize(is, MapValue.Map.class).getAttachmentsMap(); - Map attachments = new HashMap<>(); - - if (stringAttachments != null) { - stringAttachments.forEach((k, v) -> attachments.put(k, v)); - } - return attachments; - } -} diff --git a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutput.java b/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutput.java deleted file mode 100644 index 619aec6986..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufObjectOutput.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protobuf.support; - -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.protobuf.support.wrapper.MapValue; - -import com.google.protobuf.BoolValue; -import com.google.protobuf.ByteString; -import com.google.protobuf.BytesValue; -import com.google.protobuf.DoubleValue; -import com.google.protobuf.FloatValue; -import com.google.protobuf.Int32Value; -import com.google.protobuf.Int64Value; -import com.google.protobuf.MessageLite; -import com.google.protobuf.StringValue; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.Map; - -import static org.apache.dubbo.common.constants.CommonConstants.HEARTBEAT_EVENT; -import static org.apache.dubbo.common.constants.CommonConstants.MOCK_HEARTBEAT_EVENT; - -/** - * GenericGoogleProtobuf object output implementation - */ -public class GenericProtobufObjectOutput implements ObjectOutput { - - private final OutputStream os; - - public GenericProtobufObjectOutput(OutputStream os) { - this.os = os; - } - - @Override - public void writeBool(boolean v) throws IOException { - - writeObject(BoolValue.newBuilder().setValue(v).build()); - } - - @Override - public void writeByte(byte v) throws IOException { - writeObject(Int32Value.newBuilder().setValue((v)).build()); - } - - @Override - public void writeShort(short v) throws IOException { - writeObject(Int32Value.newBuilder().setValue(v).build()); - } - - @Override - public void writeInt(int v) throws IOException { - writeObject(Int32Value.newBuilder().setValue(v).build()); - } - - @Override - public void writeLong(long v) throws IOException { - writeObject(Int64Value.newBuilder().setValue(v).build()); - } - - @Override - public void writeFloat(float v) throws IOException { - writeObject(FloatValue.newBuilder().setValue(v).build()); - } - - @Override - public void writeDouble(double v) throws IOException { - writeObject(DoubleValue.newBuilder().setValue(v).build()); - } - - @Override - public void writeUTF(String v) throws IOException { - writeObject(StringValue.newBuilder().setValue(v).build()); - } - - @Override - public void writeBytes(byte[] b) throws IOException { - writeObject(BytesValue.newBuilder().setValue(ByteString.copyFrom(b)).build()); - } - - @Override - public void writeBytes(byte[] b, int off, int len) throws IOException { - writeObject(BytesValue.newBuilder().setValue(ByteString.copyFrom(b, off, len)).build()); - } - - @SuppressWarnings("unchecked") - @Override - public void writeObject(Object obj) throws IOException { - /** - * Protobuf does not allow writing of non-protobuf generated messages, including null value. - * Writing of null value from developers should be denied immediately by throwing exception. - */ - if (obj == null) { - throw new IllegalStateException("This serialization only supports google protobuf objects, " + - "please use com.google.protobuf.Empty instead if you want to transmit null values."); - // obj = ProtobufUtils.convertNullToEmpty(); - } - if (!ProtobufUtils.isSupported(obj.getClass())) { - throw new IllegalArgumentException("This serialization only supports google protobuf objects, current object class is: " + obj.getClass().getName()); - } - - ProtobufUtils.serialize(obj, os); - os.flush(); - } - - @Override - public void writeEvent(Object data) throws IOException { - if (data == HEARTBEAT_EVENT) { - data = MOCK_HEARTBEAT_EVENT; - } - writeUTF((String) data); - } - - @Override - public void writeThrowable(Object obj) throws IOException { - if (obj instanceof Throwable && !(obj instanceof MessageLite)) { - obj = ProtobufUtils.convertToThrowableProto((Throwable) obj); - } - ProtobufUtils.serialize(obj, os); - os.flush(); - } - - @Override - public void writeAttachments(Map attachments) throws IOException { - if (attachments == null) { - return; - } - - Map stringAttachments = new HashMap<>(); - attachments.forEach((k, v) -> stringAttachments.put(k, (String) v)); - - ProtobufUtils.serialize(MapValue.Map.newBuilder().putAllAttachments(stringAttachments).build(), os); - os.flush(); - } - - @Override - public void flushBuffer() throws IOException { - os.flush(); - } - -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java b/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java deleted file mode 100644 index 12d2f658ab..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/GenericProtobufSerialization.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protobuf.support; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.serialize.Constants; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; - -import java.io.InputStream; -import java.io.OutputStream; - -/** - *

    - * Currently, the Dubbo protocol / framework data, such as attachments, event data, etc., - * depends on business layer serialization protocol to do serialization before transmitted. - * That's a problem when using Protobuf as business serialization protocol, because Protobuf does not support raw java Object types, - * to solve it, we can use one of the following methods: - * - *

      - *
    • 1. Package these data with Protobuf so that they can be serialized.
    • - *
    • 2. Separate the serialization of Dubbo protocol/framework and the service args (easy to cross-platform, cross-language serialization) to avoid the binding of this part and serialization protocol.
    • - *
    - * - *

    - */ -public class GenericProtobufSerialization implements Serialization { - - @Override - public byte getContentTypeId() { - return Constants.PROTOBUF_SERIALIZATION_ID; - } - - @Override - public String getContentType() { - return "text/json"; - } - - @Override - public ObjectOutput serialize(URL url, OutputStream output) { - return new GenericProtobufObjectOutput(output); - } - - @Override - public ObjectInput deserialize(URL url, InputStream input) { - return new GenericProtobufObjectInput(input); - } -} diff --git a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufUtils.java b/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufUtils.java deleted file mode 100644 index 3bffdff071..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufUtils.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protobuf.support; - -import org.apache.dubbo.common.serialize.protobuf.support.wrapper.MapValue; -import org.apache.dubbo.common.serialize.protobuf.support.wrapper.ThrowablePB.StackTraceElementProto; -import org.apache.dubbo.common.serialize.protobuf.support.wrapper.ThrowablePB.ThrowableProto; - -import com.google.common.base.Strings; -import com.google.protobuf.BoolValue; -import com.google.protobuf.BytesValue; -import com.google.protobuf.CodedInputStream; -import com.google.protobuf.DoubleValue; -import com.google.protobuf.Empty; -import com.google.protobuf.ExtensionRegistryLite; -import com.google.protobuf.FloatValue; -import com.google.protobuf.GeneratedMessageV3.Builder; -import com.google.protobuf.Int32Value; -import com.google.protobuf.Int64Value; -import com.google.protobuf.InvalidProtocolBufferException; -import com.google.protobuf.MessageLite; -import com.google.protobuf.MessageOrBuilder; -import com.google.protobuf.Parser; -import com.google.protobuf.StringValue; -import com.google.protobuf.util.JsonFormat; -import com.google.protobuf.util.JsonFormat.Printer; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Method; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -public class ProtobufUtils { - - static boolean isSupported(Class clazz) { - if (clazz == null) { - return false; - } - - if (MessageLite.class.isAssignableFrom(clazz)) { - return true; - } - return false; - } - - /* Protobuf json */ - - static T deserializeJson(String json, Class requestClass) throws InvalidProtocolBufferException { - Builder builder; - try { - builder = getMessageBuilder(requestClass); - } catch (Exception e) { - throw new IllegalArgumentException("Get google protobuf message builder from " + requestClass.getName() + "failed", e); - } - JsonFormat.parser().merge(json, builder); - return (T) builder.build(); - } - - static String serializeJson(Object value) throws InvalidProtocolBufferException { - Printer printer = JsonFormat.printer().omittingInsignificantWhitespace(); - return printer.print((MessageOrBuilder) value); - } - - private static Builder getMessageBuilder(Class requestType) throws Exception { - Method method = requestType.getMethod("newBuilder"); - return (Builder) method.invoke(null, null); - } - - - /* Protobuf */ - - private static ConcurrentMap, MessageMarshaller> marshallers = - new ConcurrentHashMap<>(); - - private static volatile ExtensionRegistryLite globalRegistry = - ExtensionRegistryLite.getEmptyRegistry(); - - static { - // Built-in types need to be registered in advance - marshaller(MapValue.Map.getDefaultInstance()); - marshaller(Empty.getDefaultInstance()); - marshaller(ThrowableProto.getDefaultInstance()); - marshaller(BoolValue.getDefaultInstance()); - marshaller(Int32Value.getDefaultInstance()); - marshaller(Int64Value.getDefaultInstance()); - marshaller(FloatValue.getDefaultInstance()); - marshaller(DoubleValue.getDefaultInstance()); - marshaller(BytesValue.getDefaultInstance()); - marshaller(StringValue.getDefaultInstance()); - } - - public static void marshaller(T defaultInstance) { - marshallers.put(defaultInstance.getClass(), new MessageMarshaller<>(defaultInstance)); - } - - static void serialize(Object value, OutputStream os) throws IOException { - MessageLite messageLite = (MessageLite) value; - messageLite.writeDelimitedTo(os); - } - - @SuppressWarnings("unchecked") - static T deserialize(InputStream is, Class requestClass) throws InvalidProtocolBufferException { - MessageMarshaller marshaller = marshallers.get(requestClass); - if (marshaller == null) { - throw new IllegalStateException(String.format("Protobuf classes should be registered in advance before " + - "do serialization, class name: %s", requestClass.getName())); - } - return (T) marshaller.parse(is); - } - - public static Empty convertNullToEmpty() { - return Empty.newBuilder().build(); - } - - public static Object convertEmptyToNull(Empty empty) { - return null; - } - - public static ThrowableProto convertToThrowableProto(Throwable throwable) { - final ThrowableProto.Builder builder = ThrowableProto.newBuilder(); - builder.setOriginalClassName(throwable.getClass().getCanonicalName()); - builder.setOriginalMessage(Strings.nullToEmpty(throwable.getMessage())); - - for (StackTraceElement e : throwable.getStackTrace()) { - builder.addStackTrace(toStackTraceElement(e)); - } - - if (throwable.getCause() != null) { - builder.setCause(convertToThrowableProto(throwable.getCause())); - } - return builder.build(); - } - - public static Throwable convertToException(ThrowableProto throwableProto) { - return new ProtobufWrappedException(throwableProto); - } - - private static StackTraceElementProto toStackTraceElement(StackTraceElement element) { - final StackTraceElementProto.Builder builder = - StackTraceElementProto.newBuilder() - .setClassName(element.getClassName()) - .setMethodName(element.getMethodName()) - .setLineNumber(element.getLineNumber()); - if (element.getFileName() != null) { - builder.setFileName(element.getFileName()); - } - return builder.build(); - } - - private static final class MessageMarshaller { - private final Parser parser; - private final T defaultInstance; - - @SuppressWarnings("unchecked") - MessageMarshaller(T defaultInstance) { - this.defaultInstance = defaultInstance; - parser = (Parser) defaultInstance.getParserForType(); - } - - @SuppressWarnings("unchecked") - public Class getMessageClass() { - // Precisely T since protobuf doesn't let messages extend other messages. - return (Class) defaultInstance.getClass(); - } - - public T getMessagePrototype() { - return defaultInstance; - } - - public T parse(InputStream stream) throws InvalidProtocolBufferException { - return parser.parseDelimitedFrom(stream, globalRegistry); -// CodedInputStream cis = CodedInputStream.newInstance(stream); -// // Pre-create the CodedInputStream so that we can remove the size limit restriction -// // when parsing. -// cis.setSizeLimit(Integer.MAX_VALUE); -// return parseFrom(cis); - } - - private T parseFrom(CodedInputStream stream) throws InvalidProtocolBufferException { - T message = parser.parseFrom(stream, globalRegistry); - try { - stream.checkLastTagWas(0); - return message; - } catch (InvalidProtocolBufferException e) { - e.setUnfinishedMessage(message); - throw e; - } - } - } -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufWrappedException.java b/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufWrappedException.java deleted file mode 100644 index 83939a97cb..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/src/main/java/org/apache/dubbo/common/serialize/protobuf/support/ProtobufWrappedException.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protobuf.support; - -import org.apache.dubbo.common.serialize.protobuf.support.wrapper.ThrowablePB; -import org.apache.dubbo.common.serialize.protobuf.support.wrapper.ThrowablePB.ThrowableProto; - -import com.google.common.base.Strings; - -/** - * For protobuf, all server side exceptions should be wrapped using this specific one. - */ -public class ProtobufWrappedException extends RuntimeException { - - private static final long serialVersionUID = -1792808536714102039L; - - private String originalClassName; - private String originalMessage; - - public ProtobufWrappedException(ThrowableProto throwableProto) { - super(throwableProto.getOriginalClassName() + ": " + throwableProto.getOriginalMessage()); - - originalClassName = throwableProto.getOriginalClassName(); - originalMessage = throwableProto.getOriginalMessage(); - - if (throwableProto.getStackTraceCount() > 0) { - setStackTrace(throwableProto.getStackTraceList().stream() - .map(ProtobufWrappedException::toStackTraceElement) - .toArray(StackTraceElement[]::new)); - } - - if (throwableProto.hasCause()) { - initCause(new ProtobufWrappedException(throwableProto.getCause())); - } - } - - public String getOriginalClassName() { - return originalClassName; - } - - public String getOriginalMessage() { - return originalMessage; - } - - private static StackTraceElement toStackTraceElement(ThrowablePB.StackTraceElementProto proto) { - return new StackTraceElement( - proto.getClassName(), - proto.getMethodName(), - Strings.emptyToNull(proto.getFileName()), - proto.getLineNumber()); - } - -} - diff --git a/dubbo-serialization/dubbo-serialization-protobuf/src/main/proto/MapValue.proto b/dubbo-serialization/dubbo-serialization-protobuf/src/main/proto/MapValue.proto deleted file mode 100644 index d421a25a7b..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/src/main/proto/MapValue.proto +++ /dev/null @@ -1,27 +0,0 @@ -// 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. - -// Messages used for transporting debug information between server and client. - -syntax = "proto3"; - -package org.apache.dubbo.common.serialize.protobuf.support.wrapper; - -option java_package = "org.apache.dubbo.common.serialize.protobuf.support.wrapper"; -option java_multiple_files = false; - -message Map{ - map attachments = 1; -} \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protobuf/src/main/proto/ThrowablePB.proto b/dubbo-serialization/dubbo-serialization-protobuf/src/main/proto/ThrowablePB.proto deleted file mode 100644 index f228730fc9..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/src/main/proto/ThrowablePB.proto +++ /dev/null @@ -1,64 +0,0 @@ -// 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. - -// Messages used for transporting debug information between server and client. - -syntax = "proto3"; - -package org.apache.dubbo.common.serialize.protobuf.support.wrapper; - -option java_package = "org.apache.dubbo.common.serialize.protobuf.support.wrapper"; -option java_multiple_files = false; - -// An element in a stack trace, based on the Java type of the same name. -// -// See: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/StackTraceElement.html -message StackTraceElementProto { - // The fully qualified name of the class containing the execution point - // represented by the stack trace element. - string class_name = 1; - - // The name of the method containing the execution point represented by the - // stack trace element - string method_name = 2; - - // The name of the file containing the execution point represented by the - // stack trace element, or null if this information is unavailable. - string file_name = 3; - - // The line number of the source line containing the execution point represented - // by this stack trace element, or a negative number if this information is - // unavailable. - int32 line_number = 4; -} - -// An exception that was thrown by some code, based on the Java type of the same name. -// -// See: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Throwable.html -message ThrowableProto { - // The name of the class of the exception that was actually thrown. Downstream readers - // of this message may or may not have the actual class available to initialize, so - // this is just used to prefix the message of a generic exception type. - string original_class_name = 1; - - // The message of this throwable. Not filled if there is no message. - string original_message = 2; - - // The stack trace of this Throwable. - repeated StackTraceElementProto stack_trace = 3; - - // The cause of this Throwable. Not filled if there is no cause. - ThrowableProto cause = 4; -} diff --git a/dubbo-serialization/dubbo-serialization-protobuf/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization b/dubbo-serialization/dubbo-serialization-protobuf/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization deleted file mode 100644 index b18b8be488..0000000000 --- a/dubbo-serialization/dubbo-serialization-protobuf/src/main/resources/META-INF/dubbo/internal/org.apache.dubbo.common.serialize.Serialization +++ /dev/null @@ -1,2 +0,0 @@ -protobuf-json=org.apache.dubbo.common.serialize.protobuf.support.GenericProtobufJsonSerialization -protobuf=org.apache.dubbo.common.serialize.protobuf.support.GenericProtobufSerialization \ No newline at end of file diff --git a/dubbo-serialization/dubbo-serialization-protostuff/pom.xml b/dubbo-serialization/dubbo-serialization-protostuff/pom.xml deleted file mode 100644 index 1682cbb853..0000000000 --- a/dubbo-serialization/dubbo-serialization-protostuff/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - - 4.0.0 - - org.apache.dubbo - dubbo-serialization - ${revision} - ../pom.xml - - - dubbo-serialization-protostuff - jar - ${project.artifactId} - The protostuff serialization module of dubbo project - - - 1.5.9 - - - - - org.apache.dubbo - dubbo-serialization-api - ${project.parent.version} - - - io.protostuff - protostuff-core - ${protostuff.version} - - - io.protostuff - protostuff-runtime - ${protostuff.version} - - - - diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectInput.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectInput.java deleted file mode 100644 index e8307748de..0000000000 --- a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectInput.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protostuff; - -import io.protostuff.GraphIOUtil; -import io.protostuff.Schema; -import io.protostuff.runtime.RuntimeSchema; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.protostuff.utils.WrapperUtils; - -/** - * Protostuff object input implementation - */ -public class ProtostuffObjectInput implements ObjectInput { - - private DataInputStream dis; - - public ProtostuffObjectInput(InputStream inputStream) { - dis = new DataInputStream(inputStream); - } - - @SuppressWarnings("ResultOfMethodCallIgnored") - @Override - public Object readObject() throws IOException, ClassNotFoundException { - int classNameLength = dis.readInt(); - int bytesLength = dis.readInt(); - - if (classNameLength < 0 || bytesLength < 0) { - throw new IOException(); - } - - byte[] classNameBytes = new byte[classNameLength]; - dis.readFully(classNameBytes, 0, classNameLength); - - byte[] bytes = new byte[bytesLength]; - dis.readFully(bytes, 0, bytesLength); - - String className = new String(classNameBytes); - Class clazz = Class.forName(className); - - Object result; - if (WrapperUtils.needWrapper(clazz)) { - Schema schema = RuntimeSchema.getSchema(Wrapper.class); - Wrapper wrapper = schema.newMessage(); - GraphIOUtil.mergeFrom(bytes, wrapper, schema); - result = wrapper.getData(); - } else { - Schema schema = RuntimeSchema.getSchema(clazz); - result = schema.newMessage(); - GraphIOUtil.mergeFrom(bytes, result, schema); - } - - return result; - } - - @SuppressWarnings("unchecked") - @Override - public T readObject(Class clazz) throws IOException, ClassNotFoundException { - return (T) readObject(); - } - - @Override - public T readObject(Class cls, Type type) throws IOException, ClassNotFoundException { - return readObject(cls); - } - - @Override - public boolean readBool() throws IOException { - return dis.readBoolean(); - } - - @Override - public byte readByte() throws IOException { - return dis.readByte(); - } - - @Override - public short readShort() throws IOException { - return dis.readShort(); - } - - @Override - public int readInt() throws IOException { - return dis.readInt(); - } - - @Override - public long readLong() throws IOException { - return dis.readLong(); - } - - @Override - public float readFloat() throws IOException { - return dis.readFloat(); - } - - @Override - public double readDouble() throws IOException { - return dis.readDouble(); - } - - @Override - public String readUTF() throws IOException { - int length = dis.readInt(); - byte[] bytes = new byte[length]; - dis.read(bytes, 0, length); - return new String(bytes); - } - - @Override - public byte[] readBytes() throws IOException { - int length = dis.readInt(); - byte[] bytes = new byte[length]; - dis.read(bytes, 0, length); - return bytes; - } -} diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutput.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutput.java deleted file mode 100644 index ab94d3ba8d..0000000000 --- a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffObjectOutput.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protostuff; - -import io.protostuff.GraphIOUtil; -import io.protostuff.LinkedBuffer; -import io.protostuff.Schema; -import io.protostuff.runtime.RuntimeSchema; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.protostuff.utils.WrapperUtils; - -/** - * Protostuff object output implementation - */ -public class ProtostuffObjectOutput implements ObjectOutput { - - private LinkedBuffer buffer = LinkedBuffer.allocate(); - private DataOutputStream dos; - - public ProtostuffObjectOutput(OutputStream outputStream) { - dos = new DataOutputStream(outputStream); - } - - @SuppressWarnings("unchecked") - @Override - public void writeObject(Object obj) throws IOException { - - byte[] bytes; - byte[] classNameBytes; - - try { - if (obj == null || WrapperUtils.needWrapper(obj)) { - Schema schema = RuntimeSchema.getSchema(Wrapper.class); - Wrapper wrapper = new Wrapper(obj); - bytes = GraphIOUtil.toByteArray(wrapper, schema, buffer); - classNameBytes = Wrapper.class.getName().getBytes(); - } else { - Schema schema = RuntimeSchema.getSchema(obj.getClass()); - bytes = GraphIOUtil.toByteArray(obj, schema, buffer); - classNameBytes = obj.getClass().getName().getBytes(); - } - } finally { - buffer.clear(); - } - - dos.writeInt(classNameBytes.length); - dos.writeInt(bytes.length); - dos.write(classNameBytes); - dos.write(bytes); - } - - @Override - public void writeBool(boolean v) throws IOException { - dos.writeBoolean(v); - } - - @Override - public void writeByte(byte v) throws IOException { - dos.writeByte(v); - } - - @Override - public void writeShort(short v) throws IOException { - dos.writeShort(v); - } - - @Override - public void writeInt(int v) throws IOException { - dos.writeInt(v); - } - - @Override - public void writeLong(long v) throws IOException { - dos.writeLong(v); - } - - @Override - public void writeFloat(float v) throws IOException { - dos.writeFloat(v); - } - - @Override - public void writeDouble(double v) throws IOException { - dos.writeDouble(v); - } - - @Override - public void writeUTF(String v) throws IOException { - byte[] bytes = v.getBytes(); - dos.writeInt(bytes.length); - dos.write(bytes); - } - - @Override - public void writeBytes(byte[] v) throws IOException { - dos.writeInt(v.length); - dos.write(v); - } - - @Override - public void writeBytes(byte[] v, int off, int len) throws IOException { - dos.writeInt(len); - byte[] bytes = new byte[len]; - System.arraycopy(v, off, bytes, 0, len); - dos.write(bytes); - } - - @Override - public void flushBuffer() throws IOException { - dos.flush(); - } -} diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java deleted file mode 100644 index 5218cef983..0000000000 --- a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/ProtostuffSerialization.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protostuff; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.common.serialize.ObjectInput; -import org.apache.dubbo.common.serialize.ObjectOutput; -import org.apache.dubbo.common.serialize.Serialization; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import static org.apache.dubbo.common.serialize.Constants.PROTOSTUFF_SERIALIZATION_ID; - -/** - * Protostuff serialization implementation - * - *
    - *     e.g. <dubbo:protocol serialization="protostuff" />
    - * 
    - */ -public class ProtostuffSerialization implements Serialization { - @Override - public byte getContentTypeId() { - return PROTOSTUFF_SERIALIZATION_ID; - } - - @Override - public String getContentType() { - return "x-application/protostuff"; - } - - @Override - public ObjectOutput serialize(URL url, OutputStream output) throws IOException { - return new ProtostuffObjectOutput(output); - } - - @Override - public ObjectInput deserialize(URL url, InputStream input) throws IOException { - return new ProtostuffObjectInput(input); - } -} diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/Wrapper.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/Wrapper.java deleted file mode 100644 index 9b56b43fad..0000000000 --- a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/Wrapper.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protostuff; - -/** - * Protostuff can only serialize/deserialize POJOs, for those it can't deal with, use this Wrapper. - */ -public class Wrapper { - private T data; - - Wrapper(T data) { - this.data = data; - } - - Object getData() { - return data; - } -} diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/SqlDateDelegate.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/SqlDateDelegate.java deleted file mode 100644 index a1a7a421ce..0000000000 --- a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/SqlDateDelegate.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protostuff.delegate; - -import io.protostuff.Input; -import io.protostuff.Output; -import io.protostuff.Pipe; -import io.protostuff.WireFormat; -import io.protostuff.runtime.Delegate; - -import java.io.IOException; - -/** - * Custom {@link java.sql.Date} delegate - */ -public class SqlDateDelegate implements Delegate { - @Override - public WireFormat.FieldType getFieldType() { - return WireFormat.FieldType.FIXED64; - } - - @Override - public java.sql.Date readFrom(Input input) throws IOException { - return new java.sql.Date(input.readFixed64()); - } - - @Override - public void writeTo(Output output, int number, java.sql.Date value, boolean repeated) throws IOException { - output.writeFixed64(number, value.getTime(), repeated); - } - - @Override - public void transfer(Pipe pipe, Input input, Output output, int number, boolean repeated) throws IOException { - output.writeFixed64(number, input.readFixed64(), repeated); - } - - @Override - public Class typeClass() { - return java.sql.Date.class; - } -} diff --git a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimeDelegate.java b/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimeDelegate.java deleted file mode 100644 index 6ead01827e..0000000000 --- a/dubbo-serialization/dubbo-serialization-protostuff/src/main/java/org/apache/dubbo/common/serialize/protostuff/delegate/TimeDelegate.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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.apache.dubbo.common.serialize.protostuff.delegate; - -import io.protostuff.Input; -import io.protostuff.Output; -import io.protostuff.Pipe; -import io.protostuff.WireFormat; -import io.protostuff.runtime.Delegate; - -import java.io.IOException; -import java.sql.Time; - -/** - * Custom {@link Time} delegate - */ -public class TimeDelegate implements Delegate