com.alibaba.dubbo.common.Constants Java Examples

The following examples show how to use com.alibaba.dubbo.common.Constants. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MonitorFilter.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        if (invoker.getUrl().hasParameter(Constants.MONITOR_KEY)) {
            RpcContext context = RpcContext.getContext(); // provider must fetch context before invoke() gets called
            String remoteHost = context.getRemoteHost();
            long start = System.currentTimeMillis(); // record start timestamp
            getConcurrent(invoker, invocation).incrementAndGet(); // count up
            try {
                Result result = invoker.invoke(invocation); // proceed invocation chain
                collect(invoker, invocation, result, remoteHost, start, false);
                return result;
            } catch (RpcException e) {
                collect(invoker, invocation, null, remoteHost, start, true);
                throw e;
            } finally {
                getConcurrent(invoker, invocation).decrementAndGet(); // count down
            }
        } else {
//            com.alibaba.dubbo.rpc.protocol.AbstractInvoker.invoke
            return invoker.invoke(invocation);
        }
    }
 
Example #2
Source File: ReferenceConfig.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
private static void checkAndConvertImplicitConfig(MethodConfig method, Map<String, String> map, Map<Object, Object> attributes) {
    //check config conflict 异步返回禁用、异步返回调用对象、异常调用对象为空
    if (Boolean.FALSE.equals(method.isReturn()) && (method.getOnreturn() != null || method.getOnthrow() != null)) {
        throw new IllegalStateException("method config error : return attribute must be set true when onreturn or onthrow has been setted.");
    }
    //convert onreturn methodName to Method 覆盖静态上下文中异步调用的方法 onreturn.method
    String onReturnMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_RETURN_METHOD_KEY);
    Object onReturnMethod = attributes.get(onReturnMethodKey);
    if (onReturnMethod instanceof String) {
        attributes.put(onReturnMethodKey, getMethodByName(method.getOnreturn().getClass(), onReturnMethod.toString()));
    }
    //convert onthrow methodName to Method 覆盖静态上下文中异常调用方法 onthrow.method
    String onThrowMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_THROW_METHOD_KEY);
    Object onThrowMethod = attributes.get(onThrowMethodKey);
    if (onThrowMethod instanceof String) {
        attributes.put(onThrowMethodKey, getMethodByName(method.getOnthrow().getClass(), onThrowMethod.toString()));
    }
    //convert oninvoke methodName to Method 覆盖静态上下文中异步调用后执行的方法 oninvoke.method
    String onInvokeMethodKey = StaticContext.getKey(map, method.getName(), Constants.ON_INVOKE_METHOD_KEY);
    Object onInvokeMethod = attributes.get(onInvokeMethodKey);
    if (onInvokeMethod instanceof String) {
        attributes.put(onInvokeMethodKey, getMethodByName(method.getOninvoke().getClass(), onInvokeMethod.toString()));
    }
}
 
Example #3
Source File: InjvmProtocol.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
static Exporter<?> getExporter(Map<String, Exporter<?>> map, URL key) {
    Exporter<?> result = null;

    if (!key.getServiceKey().contains("*")) {
        result = map.get(key.getServiceKey());
    } else {
        if (map != null && !map.isEmpty()) {
            for (Exporter<?> exporter : map.values()) {
                if (UrlUtils.isServiceKeyMatch(key, exporter.getInvoker().getUrl())) {
                    result = exporter;
                    break;
                }
            }
        }
    }

    if (result == null) {
        return null;
    } else if (ProtocolUtils.isGeneric(
            result.getInvoker().getUrl().getParameter(Constants.GENERIC_KEY))) {
        return null;
    } else {
        return result;
    }
}
 
Example #4
Source File: UrlUtils.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public static URL getEmptyUrl(String service, String category) {
    String group = null;
    String version = null;
    int i = service.indexOf('/');
    if (i > 0) {
        group = service.substring(0, i);
        service = service.substring(i + 1);
    }
    i = service.lastIndexOf(':');
    if (i > 0) {
        version = service.substring(i + 1);
        service = service.substring(0, i);
    }
    return URL.valueOf(Constants.EMPTY_PROTOCOL + "://0.0.0.0/" + service + "?" 
                + Constants.CATEGORY_KEY + "=" + category
                + (group == null ? "" : "&" + Constants.GROUP_KEY + "=" + group)
                + (version == null ? "" : "&" + Constants.VERSION_KEY + "=" + version));
}
 
Example #5
Source File: DubboProtocol.java    From dubbox with Apache License 2.0 6 votes vote down vote up
private ExchangeServer createServer(URL url) {
    //默认开启server关闭时发送readonly事件
    url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString());
    //默认开启heartbeat
    url = url.addParameterIfAbsent(Constants.HEARTBEAT_KEY, String.valueOf(Constants.DEFAULT_HEARTBEAT));
    String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER);

    if (str != null && str.length() > 0 && ! ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str))
        throw new RpcException("Unsupported server type: " + str + ", url: " + url);

    url = url.addParameter(Constants.CODEC_KEY, Version.isCompatibleVersion() ? COMPATIBLE_CODEC_NAME : DubboCodec.NAME);
    ExchangeServer server;
    try {
        server = Exchangers.bind(url, requestHandler);
    } catch (RemotingException e) {
        throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e);
    }
    str = url.getParameter(Constants.CLIENT_KEY);
    if (str != null && str.length() > 0) {
        Set<String> supportedTypes = ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions();
        if (!supportedTypes.contains(str)) {
            throw new RpcException("Unsupported client type: " + str);
        }
    }
    return server;
}
 
Example #6
Source File: ExchangeCodecTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testMessageLengthExceedPayloadLimitWhenEncode() throws Exception {
    Request request = new Request(1L);
    request.setData("hello");
    ChannelBuffer encodeBuffer = ChannelBuffers.dynamicBuffer(512);
    AbstractMockChannel channel = getCliendSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4));
    try {
        codec.encode(channel, encodeBuffer, request);
        Assert.fail();
    } catch (IOException e) {
        Assert.assertTrue(e.getMessage().startsWith("Data length too large: " + 6));
    }

    Response response = new Response(1L);
    response.setResult("hello");
    encodeBuffer = ChannelBuffers.dynamicBuffer(512);
    channel = getServerSideChannel(url.addParameter(Constants.PAYLOAD_KEY, 4));
    codec.encode(channel, encodeBuffer, response);
    Assert.assertTrue(channel.getReceivedMessage() instanceof Response);
    Response receiveMessage = (Response) channel.getReceivedMessage();
    Assert.assertEquals(Response.BAD_RESPONSE, receiveMessage.getStatus());
    Assert.assertTrue(receiveMessage.getErrorMessage().contains("Data length too large: "));
}
 
Example #7
Source File: ChanelHandlerTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Test
public void testClient() throws Throwable {
    // read server info from property
    if (PerformanceUtils.getProperty("server", null) == null) {
        logger.warn("Please set -Dserver=127.0.0.1:9911");
        return;
    }
    final String server = System.getProperty("server", "127.0.0.1:9911");
    final String transporter = PerformanceUtils.getProperty(Constants.TRANSPORTER_KEY, Constants.DEFAULT_TRANSPORTER);
    final String serialization = PerformanceUtils.getProperty(Constants.SERIALIZATION_KEY, Constants.DEFAULT_REMOTING_SERIALIZATION);
    final int timeout = PerformanceUtils.getIntProperty(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
    int sleep = PerformanceUtils.getIntProperty("sleep", 60 * 1000 * 60);

    final String url = "exchange://" + server + "?transporter=" + transporter + "&serialization=" + serialization + "&timeout=" + timeout;
    ExchangeClient exchangeClient = initClient(url);
    Thread.sleep(sleep);
    closeClient(exchangeClient);
}
 
Example #8
Source File: ProviderServiceImpl.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public List<String> findAddresses() {
    List<String> ret = new ArrayList<String>();
    
    ConcurrentMap<String, Map<Long, URL>> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY);
    if(null == providerUrls) return ret;
    
    for(Map.Entry<String, Map<Long, URL>> e1 : providerUrls.entrySet()) {
        Map<Long, URL> value = e1.getValue();
        for(Map.Entry<Long, URL> e2 : value.entrySet()) {
            URL u = e2.getValue();
            String app = u.getAddress();
            if(app != null) ret.add(app);
        }
    }
    
    return ret;
}
 
Example #9
Source File: MockClusterInvokerTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test
public void testMockInvokerInvoke_forcemock_defaultreturn(){
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName());
	url = url.addParameter(Constants.MOCK_KEY, "force" );
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
    URL mockUrl = URL.valueOf("mock://localhost/"+IHelloService.class.getName()
			+"?getSomething.mock=return aa&getSomething3xx.mock=return xx&sayHello.mock=return ")
			.addParameters(url.getParameters());
	
	Protocol protocol = new MockProtocol();
	Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.class, mockUrl);
	invokers.add(mInvoker1);
    
    RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("sayHello");
    Result ret = cluster.invoke(invocation);
    Assert.assertEquals(null, ret.getValue());
}
 
Example #10
Source File: ConfigTest.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenericServiceConfig() throws Exception {
    ServiceConfig<GenericService> service = new ServiceConfig<GenericService>();
    service.setApplication(new ApplicationConfig("test"));
    service.setRegistry(new RegistryConfig("mock://localhost"));
    service.setInterface(DemoService.class.getName());
    service.setGeneric(Constants.GENERIC_SERIALIZATION_BEAN);
    service.setRef(new GenericService(){

        public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
            return null;
        }
    });
    try {
        service.export();
        Collection<Registry> collection = MockRegistryFactory.getCachedRegistry();
        MockRegistry registry = (MockRegistry)collection.iterator().next();
        URL url = registry.getRegistered().get(0);
        Assert.assertEquals(Constants.GENERIC_SERIALIZATION_BEAN, url.getParameter(Constants.GENERIC_KEY));
    } finally {
        MockRegistryFactory.cleanCachedRegistry();
        service.unexport();
    }
}
 
Example #11
Source File: ProviderServiceImpl.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
public List<String> findApplications() {
    List<String> ret = new ArrayList<String>();
    ConcurrentMap<String, Map<Long, URL>> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY);
    if(providerUrls == null) return ret;
    
    for(Map.Entry<String, Map<Long, URL>> e1 : providerUrls.entrySet()) {
        Map<Long, URL> value = e1.getValue();
        for(Map.Entry<Long, URL> e2 : value.entrySet()) {
            URL u = e2.getValue();
            String app = u.getParameter(Constants.APPLICATION_KEY);
            if(app != null) ret.add(app);
        }
    }
    
    return ret;
}
 
Example #12
Source File: SyncUtils.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public static Provider url2Provider(Pair<Long, URL> pair) {
	if (pair == null) {
		return null;
	}
	
    Long id = pair.getKey();
    URL url = pair.getValue();

    if (url == null)
        return null;

    Provider p = new Provider();
    p.setId(id);
    p.setService(url.getServiceKey());
    p.setAddress(url.getAddress());
    p.setApplication(url.getParameter(Constants.APPLICATION_KEY));
    p.setUrl(url.toIdentityString());
    p.setParameters(url.toParameterString());

    p.setDynamic(url.getParameter("dynamic", true));
    p.setEnabled(url.getParameter(Constants.ENABLED_KEY, true));
    p.setWeight(url.getParameter(Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT));
    p.setUsername(url.getParameter("owner"));

    return p;
}
 
Example #13
Source File: ProviderServiceImpl.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
public List<String> findMethodsByService(String service) {
    List<String> ret = new ArrayList<String>();

    ConcurrentMap<String, Map<Long, URL>> providerUrls = getRegistryCache().get(Constants.PROVIDERS_CATEGORY);
    if(providerUrls == null || service == null || service.length() == 0) return ret;
    
    Map<Long, URL> providers = providerUrls.get(service);
    if(null == providers || providers.isEmpty()) return ret;
    
    Entry<Long, URL> p = providers.entrySet().iterator().next();
    String value = p.getValue().getParameter("methods");
    if (value == null || value.length() == 0) {
        return ret;
    }
    String[] methods = value.split(ParseUtils.METHOD_SPLIT);
    if (methods == null || methods.length == 0) {
        return ret;
    }
    
    for(String m : methods) {
        ret.add(m);
    }
    return ret;
}
 
Example #14
Source File: ConsistentHashLoadBalance.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
    this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
    this.identityHashCode = System.identityHashCode(invokers);
    URL url = invokers.get(0).getUrl();
    this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes", 160);
    String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, "hash.arguments", "0"));
    argumentIndex = new int[index.length];
    for (int i = 0; i < index.length; i ++) {
        argumentIndex[i] = Integer.parseInt(index[i]);
    }
    for (Invoker<T> invoker : invokers) {
        for (int i = 0; i < replicaNumber / 4; i++) {
            byte[] digest = md5(invoker.getUrl().toFullString() + i);
            for (int h = 0; h < 4; h++) {
                long m = hash(digest, h);
                virtualInvokers.put(m, invoker);
            }
        }
    }
}
 
Example #15
Source File: AbstractConfig.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
protected static void checkMultiExtension(Class<?> type, String property, String value) {
    checkMultiName(property, value);
    if (value != null && value.length() > 0) {
        String[] values = value.split("\\s*[,]+\\s*");
        for (String v : values) {
            if (v.startsWith(Constants.REMOVE_VALUE_PREFIX)) {
                v = v.substring(1);
            }
            if (Constants.DEFAULT_KEY.equals(v)) {
                continue;
            }
            if (!ExtensionLoader.getExtensionLoader(type).hasExtension(v)) {
                throw new IllegalStateException("No such extension " + v + " for " + property + "/" + type.getName());
            }
        }
    }
}
 
Example #16
Source File: DubboRegistryFactory.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public Registry createRegistry(URL url) {
    url = getRegistryURL(url);
    List<URL> urls = new ArrayList<URL>();
    urls.add(url.removeParameter(Constants.BACKUP_KEY));
    String backup = url.getParameter(Constants.BACKUP_KEY);
    if (backup != null && backup.length() > 0) {
        String[] addresses = Constants.COMMA_SPLIT_PATTERN.split(backup);
        for (String address : addresses) {
            urls.add(url.setAddress(address));
        }
    }
    RegistryDirectory<RegistryService> directory = new RegistryDirectory<RegistryService>(RegistryService.class, url.addParameter(Constants.INTERFACE_KEY, RegistryService.class.getName()).addParameterAndEncoded(Constants.REFER_KEY, url.toParameterString()));
    Invoker<RegistryService> registryInvoker = cluster.join(directory);
    RegistryService registryService = proxyFactory.getProxy(registryInvoker);
    DubboRegistry registry = new DubboRegistry(registryInvoker, registryService);
    directory.setRegistry(registry);
    directory.setProtocol(protocol);
    directory.notify(urls);
    directory.subscribe(new URL(Constants.CONSUMER_PROTOCOL, NetUtils.getLocalHost(), 0, RegistryService.class.getName(), url.getParameters()));
    return registry;
}
 
Example #17
Source File: TpsLimitFilterTest.java    From dubbox with Apache License 2.0 6 votes vote down vote up
@Test(expected = RpcException.class)
public void testFail() throws Exception {
    URL url = URL.valueOf("test://test");
    url = url.addParameter(Constants.INTERFACE_KEY,
                           "com.alibaba.dubbo.rpc.file.TpsService");
    url = url.addParameter(Constants.TPS_LIMIT_RATE_KEY, 5);
    Invoker<TpsLimitFilterTest> invoker = new MyInvoker<TpsLimitFilterTest>(url);
    Invocation invocation = new MockInvocation();
    for (int i = 0; i < 10; i++) {
        try {
            filter.invoke(invoker, invocation);
        } catch (Exception e) {
            assertTrue(i >= 5);
            throw e;
        }
    }
}
 
Example #18
Source File: RegistryProtocol.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
       url = url.setProtocol(url.getParameter(Constants.REGISTRY_KEY, Constants.DEFAULT_REGISTRY)).removeParameter(Constants.REGISTRY_KEY);
       Registry registry = registryFactory.getRegistry(url);
       if (RegistryService.class.equals(type)) {
       	return proxyFactory.getInvoker((T) registry, type, url);
       }

       // group="a,b" or group="*"
       Map<String, String> qs = StringUtils.parseQueryString(url.getParameterAndDecoded(Constants.REFER_KEY));
       String group = qs.get(Constants.GROUP_KEY);
       if (group != null && group.length() > 0 ) {
           if ( ( Constants.COMMA_SPLIT_PATTERN.split( group ) ).length > 1
                   || "*".equals( group ) ) {
               return doRefer( getMergeableCluster(), registry, type, url );
           }
       }
       return doRefer(cluster, registry, type, url);
   }
 
Example #19
Source File: NettyServer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    ExecutorService boss = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerBoss", true));
    ExecutorService worker = Executors.newCachedThreadPool(new NamedThreadFactory("NettyServerWorker", true));
    ChannelFactory channelFactory = new NioServerSocketChannelFactory(boss, worker, getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS));
    bootstrap = new ServerBootstrap(channelFactory);
    
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    channels = nettyHandler.getChannels();
    // https://issues.jboss.org/browse/NETTY-365
    // https://issues.jboss.org/browse/NETTY-379
    // final Timer timer = new HashedWheelTimer(new NamedThreadFactory("NettyIdleTimer", true));
    bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
        public ChannelPipeline getPipeline() {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec() ,getUrl(), NettyServer.this);
            ChannelPipeline pipeline = Channels.pipeline();
            /*int idleTimeout = getIdleTimeout();
            if (idleTimeout > 10000) {
                pipeline.addLast("timer", new IdleStateHandler(timer, idleTimeout / 1000, 0, 0));
            }*/
            pipeline.addLast("decoder", adapter.getDecoder());
            pipeline.addLast("encoder", adapter.getEncoder());
            pipeline.addLast("handler", nettyHandler);
            return pipeline;
        }
    });
    // bind
    channel = bootstrap.bind(getBindAddress());
}
 
Example #20
Source File: ConsumerServiceImpl.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
private Map<Long, URL> findConsumerUrlByAddress(String address) {
    Map<String, String> filter = new HashMap<String, String>();
    filter.put(Constants.CATEGORY_KEY, Constants.CONSUMERS_CATEGORY);
    filter.put(SyncUtils.ADDRESS_FILTER_KEY, address);
    
    return SyncUtils.filterFromCategory(getRegistryCache(), filter);
}
 
Example #21
Source File: UrlUtilsTest.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsServiceKeyMatch() throws Exception {
    URL url = URL.valueOf("test://127.0.0.0");
    URL pattern = url.addParameter(Constants.GROUP_KEY, "test")
        .addParameter(Constants.INTERFACE_KEY, "test")
        .addParameter(Constants.VERSION_KEY, "test");
    URL value = pattern;
    assertTrue(UrlUtils.isServiceKeyMatch(pattern, value));

    pattern = pattern.addParameter(Constants.GROUP_KEY, "*");
    assertTrue(UrlUtils.isServiceKeyMatch(pattern, value));

    pattern = pattern.addParameter(Constants.VERSION_KEY, "*");
    assertTrue(UrlUtils.isServiceKeyMatch(pattern, value));
}
 
Example #22
Source File: ExecuteLimitFilter.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    URL url = invoker.getUrl();
    String methodName = invocation.getMethodName();
    int max = url.getMethodParameter(methodName, Constants.EXECUTES_KEY, 0);
    if (max > 0) {
        RpcStatus count = RpcStatus.getStatus(url, invocation.getMethodName());
        if (count.getActive() >= max) {
            throw new RpcException("Failed to invoke method " + invocation.getMethodName() + " in provider " + url + ", cause: The service using threads greater than <dubbo:service executes=\"" + max + "\" /> limited.");
        }
    }
    long begin = System.currentTimeMillis();
    boolean isException = false;
    RpcStatus.beginCount(url, methodName);
    try {
        return invoker.invoke(invocation);
    } catch (Throwable t) {
        isException = true;
        if(t instanceof RuntimeException) {
            throw (RuntimeException) t;
        }
        else {
            throw new RpcException("unexpected exception when ExecuteLimitFilter", t);
        }
    }
    finally {
        RpcStatus.endCount(url, methodName, System.currentTimeMillis() - begin, isException);
    }
}
 
Example #23
Source File: DefaultFuture.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public DefaultFuture(Channel channel, Request request, int timeout){
    this.channel = channel;
    this.request = request;
    this.id = request.getId();
    this.timeout = timeout > 0 ? timeout : channel.getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
    // put into waiting map.
    FUTURES.put(id, this);
    CHANNELS.put(id, channel);
}
 
Example #24
Source File: FutureFilterTest.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
@Test(expected = RuntimeException.class)
public void testSyncCallbackHasException() throws RpcException, Throwable {
    @SuppressWarnings("unchecked")
    Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class).anyTimes();
    RpcResult result = new RpcResult();
    result.setException(new RuntimeException());
    EasyMock.expect(invoker.invoke(invocation)).andReturn(result).anyTimes();
    URL url = URL.valueOf("test://test:11/test?group=dubbo&version=1.1&"+Constants.ON_THROW_METHOD_KEY+"=echo");
    EasyMock.expect(invoker.getUrl()).andReturn(url).anyTimes();
    EasyMock.replay(invoker);
    eventFilter.invoke(invoker, invocation).recreate();
}
 
Example #25
Source File: ProviderServiceImpl.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void disableProvider(Long id) {
    if(id == null) {
        throw new IllegalStateException("no provider id");
    }
    
    Provider oldProvider = findProvider(id);
    if(oldProvider == null) {
        throw new IllegalStateException("Provider was changed!");
    }
    
    if (oldProvider.isDynamic()) {
     //保证disable的override唯一
     if(oldProvider.isEnabled()){
     	Override override = new Override();
     	override.setAddress(oldProvider.getAddress());
     	override.setService(oldProvider.getService());
     	override.setEnabled(true);
     	override.setParams(Constants.DISABLED_KEY+"=true");
     	overrideService.saveOverride(override);
     	return;
     }
     List<Override> oList = overrideService.findByServiceAndAddress(oldProvider.getService(), oldProvider.getAddress());
    
     for(Override o : oList){
     	Map<String, String> params = StringUtils.parseQueryString(o.getParams());
     	if(params.containsKey(Constants.DISABLED_KEY)){
     		if(params.get(Constants.DISABLED_KEY) .equals("false")){
     			overrideService.deleteOverride(o.getId());
     		}
     	}
     }
    } else {
    	oldProvider.setEnabled(false);
    	updateProvider(oldProvider);
    }
    
}
 
Example #26
Source File: AbstractCodec.java    From dubbox with Apache License 2.0 5 votes vote down vote up
protected static void checkPayload(Channel channel, long size) throws IOException {
    int payload = Constants.DEFAULT_PAYLOAD;
    if (channel != null && channel.getUrl() != null) {
        payload = channel.getUrl().getParameter(Constants.PAYLOAD_KEY, Constants.DEFAULT_PAYLOAD);
    }
    if (payload > 0 && size > payload) {
    	IOException e = new IOException("Data length too large: " + size + ", max payload: " + payload + ", channel: " + channel);
    	logger.error(e);
        throw e;
    }
}
 
Example #27
Source File: ZookeeperRegistry.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
private String toServicePath(URL url) {
    String name = url.getServiceInterface();
    if (Constants.ANY_VALUE.equals(name)) {
        return toRootPath();
    }
    return toRootDir() + URL.encode(name);
}
 
Example #28
Source File: HeartbeatHandlerTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeartbeat() throws Exception {
    URL serverURL = URL.valueOf("header://localhost:55555");
    serverURL = serverURL.addParameter(Constants.HEARTBEAT_KEY, 1000);
    TestHeartbeatHandler handler = new TestHeartbeatHandler();
    server = Exchangers.bind(serverURL, handler);
    System.out.println("Server bind successfully");

    client = Exchangers.connect(serverURL);
    Thread.sleep(10000);
    System.err.println("++++++++++++++ disconnect count " + handler.disconnectCount);
    System.err.println("++++++++++++++ connect count " + handler.connectCount);
    Assert.assertTrue(handler.disconnectCount == 0);
    Assert.assertTrue(handler.connectCount == 1);
}
 
Example #29
Source File: MethodConfigTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnthrow() throws Exception {
    MethodConfig method = new MethodConfig();
    method.setOnthrow("on-throw-object");
    assertThat(method.getOnthrow(), equalTo((Object) "on-throw-object"));
    Map<Object, Object> attribute = new HashMap<Object, Object>();
    MethodConfig.appendAttributes(attribute, method);
    assertThat(attribute, hasEntry((Object) Constants.ON_THROW_INSTANCE_KEY, (Object) "on-throw-object"));
    Map<String, String> parameters = new HashMap<String, String>();
    MethodConfig.appendParameters(parameters, method);
    assertThat(parameters.size(), is(0));
}
 
Example #30
Source File: HeaderExchangeClient.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public HeaderExchangeClient(Client client){
    if (client == null) {
        throw new IllegalArgumentException("client == null");
    }
    this.client = client;
    this.channel = new HeaderExchangeChannel(client);
    String dubbo = client.getUrl().getParameter(Constants.DUBBO_VERSION_KEY);
    this.heartbeat = client.getUrl().getParameter( Constants.HEARTBEAT_KEY, dubbo != null && dubbo.startsWith("1.0.") ? Constants.DEFAULT_HEARTBEAT : 0 );
    this.heartbeatTimeout = client.getUrl().getParameter( Constants.HEARTBEAT_TIMEOUT_KEY, heartbeat * 3 );
    if ( heartbeatTimeout < heartbeat * 2 ) {
        throw new IllegalStateException( "heartbeatTimeout < heartbeatInterval * 2" );
    }
    startHeatbeatTimer();
}