Java Code Examples for com.alibaba.dubbo.rpc.RpcException

The following examples show how to use com.alibaba.dubbo.rpc.RpcException. These examples are extracted from open source projects. 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 Project: brave   Source File: DubboParser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This library is no-longer being released, so it should not have any maintenance on error codes.
 * The error codes here were defined in 2012.
 */
@Nullable static String errorCode(Throwable error) {
  if (error instanceof RpcException) {
    int code = ((RpcException) error).getCode();
    switch (code) {
      case RpcException.UNKNOWN_EXCEPTION:
        return "UNKNOWN_EXCEPTION";
      case RpcException.NETWORK_EXCEPTION:
        return "NETWORK_EXCEPTION";
      case RpcException.TIMEOUT_EXCEPTION:
        return "TIMEOUT_EXCEPTION";
      case RpcException.BIZ_EXCEPTION:
        return "BIZ_EXCEPTION";
      case RpcException.FORBIDDEN_EXCEPTION:
        return "FORBIDDEN_EXCEPTION";
      case RpcException.SERIALIZATION_EXCEPTION:
        return "SERIALIZATION_EXCEPTION";
      default:
        return String.valueOf(code);
    }
  }
  return null;
}
 
Example 2
private void beforeConsumerInvokeForSVC(Invocation invocation, TransactionRequestImpl request,
		TransactionResponseImpl response) {
	TransactionBeanRegistry beanRegistry = TransactionBeanRegistry.getInstance();
	TransactionBeanFactory beanFactory = beanRegistry.getBeanFactory();
	TransactionInterceptor transactionInterceptor = beanFactory.getTransactionInterceptor();
	RemoteCoordinator transactionCoordinator = (RemoteCoordinator) beanFactory.getNativeParticipant();

	Map<String, String> attachments = invocation.getAttachments();
	attachments.put(RemoteCoordinator.class.getName(), transactionCoordinator.getIdentifier());

	transactionInterceptor.beforeSendRequest(request);
	if (request.getTransactionContext() != null) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		HessianOutput output = new HessianOutput(baos);
		try {
			output.writeObject(request.getTransactionContext());
		} catch (IOException ex) {
			logger.error("Error occurred in remote call!", ex);
			throw new RpcException("Error occurred in remote call!", ex);
		}
		String transactionContextContent = ByteUtils.byteArrayToString(baos.toByteArray());
		attachments.put(TransactionContext.class.getName(), transactionContextContent);
	}

}
 
Example 3
private void initializePhysicalInstanceIfNecessary(RemoteAddr remoteAddr) throws RpcException {
	if (remoteAddr != null) {
		RemoteCoordinatorRegistry participantRegistry = RemoteCoordinatorRegistry.getInstance();
		RemoteCoordinator physicalInst = participantRegistry.getPhysicalInstance(remoteAddr);
		if (physicalInst == null) {
			String serverHost = remoteAddr.getServerHost();
			int serverPort = remoteAddr.getServerPort();
			final String target = String.format("%s:%s", serverHost, serverPort).intern();
			synchronized (target) {
				RemoteCoordinator participant = participantRegistry.getPhysicalInstance(remoteAddr);
				if (participant == null) {
					this.processInitPhysicalInstanceIfNecessary(remoteAddr);
				}
			} // end-synchronized (target)
		} // end-if (physicalInst == null)
	}
}
 
Example 4
Source Project: dubbox   Source File: DubboHttpServer.java    License: Apache License 2.0 6 votes vote down vote up
protected void doStart(URL url) {
    // TODO jetty will by default enable keepAlive so the xml config has no effect now
    httpServer = httpBinder.bind(url, new RestHandler());

    ServletContext servletContext = ServletManager.getInstance().getServletContext(url.getPort());
    if (servletContext == null) {
        servletContext = ServletManager.getInstance().getServletContext(ServletManager.EXTERNAL_SERVER_PORT);
    }
    if (servletContext == null) {
        throw new RpcException("No servlet context found. If you are using server='servlet', " +
                "make sure that you've configured " + BootstrapListener.class.getName() + " in web.xml");
    }

    servletContext.setAttribute(ResteasyDeployment.class.getName(), deployment);

    try {
        dispatcher.init(new SimpleServletConfig(servletContext));
    } catch (ServletException e) {
        throw new RpcException(e);
    }
}
 
Example 5
Source Project: dubbox   Source File: ValidationFilter.java    License: Apache License 2.0 6 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    if (validation != null && ! invocation.getMethodName().startsWith("$") 
            && ConfigUtils.isNotEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.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 (Throwable t) {
            throw new RpcException(t.getMessage(), t);
        }
    }
    return invoker.invoke(invocation);
}
 
Example 6
Source Project: dubbox   Source File: FailoverClusterInvokerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test()
public void testNoInvoke() {
    dic = EasyMock.createMock(Directory.class);
    
    EasyMock.expect(dic.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(dic.list(invocation)).andReturn(null).anyTimes();
    EasyMock.expect(dic.getInterface()).andReturn(FailoverClusterInvokerTest.class).anyTimes();
    invocation.setMethodName("method1");
    EasyMock.replay(dic);
    
    invokers.add(invoker1);
    
    
    FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<FailoverClusterInvokerTest>(dic);
    try {
        invoker.invoke(invocation);
        fail();
    } catch (RpcException expected) {
        assertFalse(expected.getCause() instanceof RpcException);
    }
}
 
Example 7
Source Project: dubbo-2.6.5   Source File: ZookeeperRegistry.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<URL> lookup(URL url) {
    if (url == null) {
        throw new IllegalArgumentException("lookup url == null");
    }
    try {
        List<String> providers = new ArrayList<String>();
        for (String path : toCategoriesPath(url)) {
            List<String> children = zkClient.getChildren(path);
            if (children != null) {
                providers.addAll(children);
            }
        }
        return toUrlsWithoutEmpty(url, providers);
    } catch (Throwable e) {
        throw new RpcException("Failed to lookup " + url + " from zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
    }
}
 
Example 8
Source Project: dubbox   Source File: MonitorFilter.java    License: Apache License 2.0 6 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    if (invoker.getUrl().hasParameter(Constants.MONITOR_KEY)) {
        RpcContext context = RpcContext.getContext(); // 提供方必须在invoke()之前获取context信息
        long start = System.currentTimeMillis(); // 记录起始时间戮
        getConcurrent(invoker, invocation).incrementAndGet(); // 并发计数
        try {
            Result result = invoker.invoke(invocation); // 让调用链往下执行
            collect(invoker, invocation, result, context, start, false);
            return result;
        } catch (RpcException e) {
            collect(invoker, invocation, null, context, start, true);
            throw e;
        } finally {
            getConcurrent(invoker, invocation).decrementAndGet(); // 并发计数
        }
    } else {
        return invoker.invoke(invocation);
    }
}
 
Example 9
Source Project: dubbo-2.6.5   Source File: FutureFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public Result invoke(final Invoker<?> invoker, final Invocation invocation) throws RpcException {
        final boolean isAsync = RpcUtils.isAsync(invoker.getUrl(), invocation);

        fireInvokeCallback(invoker, invocation);
        // need to configure if there's return value before the invocation in order to help invoker to judge if it's
        // necessary to return future. 需要在调用之前配置是否有返回值,以便帮助调用程序判断是否需要返回future。
//        com.alibaba.dubbo.rpc.protocol.ProtocolFilterWrapper.com.alibaba.dubbo.rpc.Invoker.invoke()
        Result result = invoker.invoke(invocation);
        if (isAsync) {
            asyncCallback(invoker, invocation);
        } else {
            syncCallback(invoker, invocation, result);
        }
        return result;
    }
 
Example 10
Source Project: brave   Source File: ITTracingFilter_Consumer.java    License: Apache License 2.0 6 votes vote down vote up
/** Shows if you aren't using RpcTracing, the old "dubbo.error_code" works */
@Test public void setsError_onUnimplemented_legacy() {
  ((TracingFilter) ExtensionLoader.getExtensionLoader(Filter.class)
      .getExtension("tracing")).isInit = false;

  ((TracingFilter) ExtensionLoader.getExtensionLoader(Filter.class)
      .getExtension("tracing"))
      .setTracing(tracing);

  assertThatThrownBy(() -> wrongClient.get().sayHello("jorge"))
      .isInstanceOf(RpcException.class);

  MutableSpan span =
      testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, ".*Not found exported service.*");
  assertThat(span.tags())
      .containsEntry("dubbo.error_code", "1");
}
 
Example 11
Source Project: dubbox   Source File: ExceptionFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testRpcException() {
    Logger logger = EasyMock.createMock(Logger.class);
    RpcContext.getContext().setRemoteAddress("127.0.0.1", 1234);
    RpcException exception = new RpcException("TestRpcException");
    logger.error(EasyMock.eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " + DemoService.class.getName() + ", method: sayHello, exception: " + RpcException.class.getName() + ": TestRpcException"), EasyMock.eq(exception));
    ExceptionFilter exceptionFilter = new ExceptionFilter(logger);
    RpcInvocation invocation = new RpcInvocation("sayHello", new Class<?>[]{String.class}, new Object[]{"world"});
    Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class);
    EasyMock.expect(invoker.invoke(EasyMock.eq(invocation))).andThrow(exception);
    
    EasyMock.replay(logger, invoker);
    
    try {
        exceptionFilter.invoke(invoker, invocation);
    } catch (RpcException e) {
        assertEquals("TestRpcException", e.getMessage());
    }
    EasyMock.verify(logger, invoker);
    RpcContext.removeContext();
}
 
Example 12
public Result providerInvoke(Invoker<?> invoker, Invocation invocation) throws RpcException, RemotingException {
	String interfaceClazz = RpcContext.getContext().getUrl().getServiceInterface();

	boolean participantFlag = TransactionParticipant.class.getName().equals(interfaceClazz);
	boolean xaResourceFlag = XAResource.class.getName().equals(interfaceClazz);
	boolean coordinatorFlag = RemoteCoordinator.class.getName().equals(interfaceClazz);

	if (participantFlag == false && xaResourceFlag == false && coordinatorFlag == false) {
		return this.providerInvokeForSVC(invoker, invocation);
	} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_RESOURCE_START)) {
		return this.providerInvokeForKey(invoker, invocation);
	} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_IDENTIFIER)) {
		return this.providerInvokeForKey(invoker, invocation);
	} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_APPLICATION)) {
		return this.providerInvokeForKey(invoker, invocation);
	} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_REMOTEADDR)) {
		return this.providerInvokeForKey(invoker, invocation);
	} else if (StringUtils.equals(invocation.getMethodName(), KEY_XA_GET_REMOTENODE)) {
		return this.providerInvokeForKey(invoker, invocation);
	} else {
		return this.providerInvokeForTCC(invoker, invocation);
	}
}
 
Example 13
Source Project: dubbox   Source File: MockClusterInvokerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMockInvokerFromOverride_Invoke_force_throw(){
	URL url = URL.valueOf("remote://1.2.3.4/"+IHelloService.class.getName())
			.addParameter("getBoolean2.mock","force:throw ")
			.addParameter("invoke_return_error", "true" );
	Invoker<IHelloService> cluster = getClusterInvoker(url);        
	//方法配置了mock
       RpcInvocation invocation = new RpcInvocation();
	invocation.setMethodName("getBoolean2");
	try {
		cluster.invoke(invocation);
		Assert.fail();
	} catch (RpcException e) {
		Assert.assertFalse("not custem exception", e.isBiz());
	}
}
 
Example 14
Source Project: dubbox   Source File: FailoverClusterInvokerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInvokeWithRuntimeException() {
    EasyMock.reset(invoker1);
    EasyMock.expect(invoker1.invoke(invocation)).andThrow(new RuntimeException()).anyTimes();
    EasyMock.expect(invoker1.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker1.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(invoker1.getInterface()).andReturn(FailoverClusterInvokerTest.class).anyTimes();
    EasyMock.replay(invoker1);
    
    EasyMock.reset(invoker2);
    EasyMock.expect(invoker2.invoke(invocation)).andThrow(new RuntimeException()).anyTimes();
    EasyMock.expect(invoker2.isAvailable()).andReturn(true).anyTimes();
    EasyMock.expect(invoker2.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(invoker2.getInterface()).andReturn(FailoverClusterInvokerTest.class).anyTimes();
    EasyMock.replay(invoker2);
    
    FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<FailoverClusterInvokerTest>(dic);
    try {
        invoker.invoke(invocation);
        fail();
    } catch (RpcException expected) {
        assertEquals(0,expected.getCode());
        assertFalse(expected.getCause() instanceof RpcException);
    }
}
 
Example 15
Source Project: dubbo-2.6.5   Source File: FailoverClusterInvokerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test()
public void testInvoke_retryTimes() {
    given(invoker1.invoke(invocation)).willThrow(new RpcException(RpcException.TIMEOUT_EXCEPTION));
    given(invoker1.isAvailable()).willReturn(false);
    given(invoker1.getUrl()).willReturn(url);
    given(invoker1.getInterface()).willReturn(FailoverClusterInvokerTest.class);

    given(invoker2.invoke(invocation)).willThrow(new RpcException());
    given(invoker2.isAvailable()).willReturn(false);
    given(invoker2.getUrl()).willReturn(url);
    given(invoker2.getInterface()).willReturn(FailoverClusterInvokerTest.class);

    FailoverClusterInvoker<FailoverClusterInvokerTest> invoker = new FailoverClusterInvoker<FailoverClusterInvokerTest>(dic);
    try {
        Result ret = invoker.invoke(invocation);
        assertSame(result, ret);
        fail();
    } catch (RpcException expected) {
        assertTrue((expected.isTimeout() || expected.getCode() == 0));
        assertTrue(expected.getMessage().indexOf((retries + 1) + " times") > 0);
    }
}
 
Example 16
Source Project: dubbox   Source File: FailfastClusterInvokerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test()
public void testNoInvoke() {
    dic = EasyMock.createMock(Directory.class);
    
    EasyMock.expect(dic.getUrl()).andReturn(url).anyTimes();
    EasyMock.expect(dic.list(invocation)).andReturn(null).anyTimes();
    EasyMock.expect(dic.getInterface()).andReturn(FailfastClusterInvokerTest.class).anyTimes();
    
    invocation.setMethodName("method1");
    EasyMock.replay(dic);
    
    invokers.add(invoker1);
    
    resetInvoker1ToNoException();
    
    FailfastClusterInvoker<FailfastClusterInvokerTest> invoker = new FailfastClusterInvoker<FailfastClusterInvokerTest>(dic);
    try {
        invoker.invoke(invocation);
        fail();
    } catch (RpcException expected) {
        assertFalse(expected.getCause() instanceof RpcException);
    }
}
 
Example 17
Source Project: dubbox-hystrix   Source File: AbstractProxyProtocol.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> Exporter<T> export(final Invoker<T> invoker) throws RpcException {
       final String uri = serviceKey(invoker.getUrl());
       Exporter<T> exporter = (Exporter<T>) exporterMap.get(uri);
       if (exporter != null) {
       	return exporter;
       }
       final Runnable runnable = doExport(proxyFactory.getProxy(invoker), invoker.getInterface(), invoker.getUrl());
       exporter = new AbstractExporter<T>(invoker) {
           public void unexport() {
               super.unexport();
               exporterMap.remove(uri);
               if (runnable != null) {
                   try {
                       runnable.run();
                   } catch (Throwable t) {
                       logger.warn(t.getMessage(), t);
                   }
               }
           }
       };
       exporterMap.put(uri, exporter);
       return exporter;
   }
 
Example 18
Source Project: dubbox   Source File: ThriftProtocol.java    License: Apache License 2.0 6 votes vote down vote up
private ExchangeServer getServer(URL url) {
    //默认开启server关闭时发送readonly事件
    url = url.addParameterIfAbsent(Constants.CHANNEL_READONLYEVENT_SENT_KEY, Boolean.TRUE.toString());
    String str = url.getParameter(Constants.SERVER_KEY, Constants.DEFAULT_REMOTING_SERVER);

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

    ExchangeServer server;
    try {
        server = Exchangers.bind(url, handler);
    } catch (RemotingException e) {
        throw new RpcException("Fail to start server(url: " + url + ") " + e.getMessage(), e);
    }
    str = url.getParameter(Constants.CLIENT_KEY);
    if (str != null && str.length() > 0) {
        Set<String> supportedTypes = ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions();
        if (!supportedTypes.contains(str)) {
            throw new RpcException("Unsupported client type: " + str);
        }
    }
    return server;
}
 
Example 19
Source Project: dubbox   Source File: AbstractClusterInvoker.java    License: Apache License 2.0 6 votes vote down vote up
public Result invoke(final Invocation invocation) throws RpcException {

        checkWheatherDestoried();

        LoadBalance loadbalance;
        
        List<Invoker<T>> invokers = list(invocation);
        if (invokers != null && invokers.size() > 0) {
            loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl()
                    .getMethodParameter(invocation.getMethodName(),Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE));
        } else {
            loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(Constants.DEFAULT_LOADBALANCE);
        }
        RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
        return doInvoke(invocation, invokers, loadbalance);
    }
 
Example 20
Source Project: dubbo3   Source File: AbstractProxyProtocol.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> Exporter<T> export(final Invoker<T> invoker) throws RpcException {
       final String uri = serviceKey(invoker.getUrl());
       Exporter<T> exporter = (Exporter<T>) exporterMap.get(uri);
       if (exporter != null) {
       	return exporter;
       }
       final Runnable runnable = doExport(proxyFactory.getProxy(invoker), invoker.getInterface(), invoker.getUrl());
       exporter = new AbstractExporter<T>(invoker) {
           public void unexport() {
               super.unexport();
               exporterMap.remove(uri);
               if (runnable != null) {
                   try {
                       runnable.run();
                   } catch (Throwable t) {
                       logger.warn(t.getMessage(), t);
                   }
               }
           }
       };
       exporterMap.put(uri, exporter);
       return exporter;
   }
 
Example 21
Source Project: dubbo-2.6.5   Source File: RmiProtocol.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 22
Source Project: dubbox   Source File: RegistryProtocol.java    License: 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 23
Source Project: dubbox   Source File: HessianProtocol.java    License: Apache License 2.0 6 votes vote down vote up
protected <T> Runnable doExport(T impl, Class<T> type, URL url) throws RpcException {
    String addr = url.getIp() + ":" + url.getPort();
    HttpServer server = serverMap.get(addr);
    if (server == null) {
        server = httpBinder.bind(url, new HessianHandler());
        serverMap.put(addr, server);
    }
    final String path = url.getAbsolutePath();
    HessianSkeleton skeleton = new HessianSkeleton(impl, type);
    skeletonMap.put(path, skeleton);
    return new Runnable() {
        public void run() {
            skeletonMap.remove(path);
        }
    };
}
 
Example 24
Source Project: dubbox   Source File: JsonRpcProtocol.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 25
Source Project: dubbo3   Source File: ExceptionFilterTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testRpcException() {
    Logger logger = EasyMock.createMock(Logger.class);
    RpcContext.getContext().setRemoteAddress("127.0.0.1", 1234);
    RpcException exception = new RpcException("TestRpcException");
    logger.error(EasyMock.eq("Got unchecked and undeclared exception which called by 127.0.0.1. service: " + DemoService.class.getName() + ", method: sayHello, exception: " + RpcException.class.getName() + ": TestRpcException"), EasyMock.eq(exception));
    ExceptionFilter exceptionFilter = new ExceptionFilter(logger);
    RpcInvocation invocation = new RpcInvocation("sayHello", new Class<?>[]{String.class}, new Object[]{"world"});
    Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class);
    EasyMock.expect(invoker.invoke(EasyMock.eq(invocation))).andThrow(exception);
    
    EasyMock.replay(logger, invoker);
    
    try {
        exceptionFilter.invoke(invoker, invocation);
    } catch (RpcException e) {
        assertEquals("TestRpcException", e.getMessage());
    }
    EasyMock.verify(logger, invoker);
    RpcContext.removeContext();
}
 
Example 26
Source Project: dubbox   Source File: MockInvoker.java    License: Apache License 2.0 6 votes vote down vote up
private Throwable getThrowable(String throwstr){
  	Throwable throwable =(Throwable) throwables.get(throwstr);
if (throwable != null ){
	return throwable;
} else {
	Throwable t = null;
	try {
		Class<?> bizException = ReflectUtils.forName(throwstr);
          	Constructor<?> constructor;
		constructor = ReflectUtils.findConstructor(bizException, String.class);
		t = (Throwable) constructor.newInstance(new Object[] {" mocked exception for Service degradation. "});
		if (throwables.size() < 1000) {
			throwables.put(throwstr, t);	
		}
	} catch (Exception e) {
		throw new RpcException("mock throw error :" + throwstr + " argument error.", e);
	}
	return t;
}
  }
 
Example 27
private void processInitRemoteParticipantIfNecessary(String application) {
	RemoteCoordinatorRegistry participantRegistry = RemoteCoordinatorRegistry.getInstance();
	TransactionBeanRegistry beanRegistry = TransactionBeanRegistry.getInstance();

	RemoteCoordinator participant = participantRegistry.getParticipant(application);
	if (participant == null) {
		ApplicationConfig applicationConfig = beanRegistry.getBean(ApplicationConfig.class);
		RegistryConfig registryConfig = beanRegistry.getBean(RegistryConfig.class);
		ProtocolConfig protocolConfig = beanRegistry.getBean(ProtocolConfig.class);

		ReferenceConfig<RemoteCoordinator> referenceConfig = new ReferenceConfig<RemoteCoordinator>();
		referenceConfig.setInterface(RemoteCoordinator.class);
		referenceConfig.setTimeout(15000);
		referenceConfig.setCluster("failfast");
		referenceConfig.setLoadbalance("bytejta");
		referenceConfig.setFilter("bytejta");
		referenceConfig.setGroup(application);
		referenceConfig.setCheck(false);
		referenceConfig.setRetries(-1);
		referenceConfig.setScope(Constants.SCOPE_REMOTE);

		referenceConfig.setApplication(applicationConfig);
		if (registryConfig != null) {
			referenceConfig.setRegistry(registryConfig);
		}
		if (protocolConfig != null) {
			referenceConfig.setProtocol(protocolConfig.getName());
		} // end-if (protocolConfig != null)

		RemoteCoordinator reference = referenceConfig.get();
		if (reference == null) {
			throw new RpcException("Cannot get the application name of the remote application.");
		}

		participantRegistry.putParticipant(application, reference);
	}
}
 
Example 28
Source Project: dubbox   Source File: MockClusterInvoker.java    License: Apache License 2.0 5 votes vote down vote up
public Result invoke(Invocation invocation) throws RpcException {
	Result result = null;
       
       String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), Constants.MOCK_KEY, Boolean.FALSE.toString()).trim(); 
       if (value.length() == 0 || value.equalsIgnoreCase("false")){
       	//no mock
       	result = this.invoker.invoke(invocation);
       } else if (value.startsWith("force")) {
       	if (logger.isWarnEnabled()) {
       		logger.info("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " +  directory.getUrl());
       	}
       	//force:direct mock
       	result = doMockInvoke(invocation, null);
       } else {
       	//fail-mock
       	try {
       		result = this.invoker.invoke(invocation);
       	}catch (RpcException e) {
			if (e.isBiz()) {
				throw e;
			} else {
				if (logger.isWarnEnabled()) {
	        		logger.info("fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " +  directory.getUrl(), e);
	        	}
				result = doMockInvoke(invocation, e);
			}
		}
       }
       return result;
}
 
Example 29
Source Project: dubbox   Source File: RegistryDirectoryTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testforbid(RegistryDirectory registryDirectory) {
    invocation = new RpcInvocation();
    List<URL> serviceUrls = new ArrayList<URL>();
    serviceUrls.add(new URL(Constants.EMPTY_PROTOCOL, Constants.ANYHOST_VALUE, 0, service, Constants.CATEGORY_KEY, Constants.PROVIDERS_CATEGORY));
    registryDirectory.notify(serviceUrls);
    Assert.assertEquals("invokers size=0 ,then the registry directory is not available", false,
                        registryDirectory.isAvailable());
    try {
        registryDirectory.list(invocation);
        fail("forbid must throw RpcException");
    } catch (RpcException e) {
        Assert.assertEquals(RpcException.FORBIDDEN_EXCEPTION, e.getCode());
    }
}
 
Example 30
Source Project: dubbox   Source File: ContextFilter.java    License: Apache License 2.0 5 votes vote down vote up
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Map<String, String> attachments = invocation.getAttachments();
        if (attachments != null) {
            attachments = new HashMap<String, String>(attachments);
            attachments.remove(Constants.PATH_KEY);
            attachments.remove(Constants.GROUP_KEY);
            attachments.remove(Constants.VERSION_KEY);
            attachments.remove(Constants.DUBBO_VERSION_KEY);
            attachments.remove(Constants.TOKEN_KEY);
            attachments.remove(Constants.TIMEOUT_KEY);
        }
        RpcContext.getContext()
                .setInvoker(invoker)
                .setInvocation(invocation)
//                .setAttachments(attachments)  // modified by lishen
                .setLocalAddress(invoker.getUrl().getHost(),
                        invoker.getUrl().getPort());

        // modified by lishen
        if (attachments != null) {
            if (RpcContext.getContext().getAttachments() != null) {
                RpcContext.getContext().getAttachments().putAll(attachments);
            } else {
                RpcContext.getContext().setAttachments(attachments);
            }
        }

        if (invocation instanceof RpcInvocation) {
            ((RpcInvocation)invocation).setInvoker(invoker);
        }
        try {
            return invoker.invoke(invocation);
        } finally {
            RpcContext.removeContext();
        }
    }