org.apache.dubbo.rpc.Protocol

Here are the examples of the java api org.apache.dubbo.rpc.Protocol taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

93 Examples 7

19 Source : StubProxyFactoryWrapper.java
with Apache License 2.0
from boomblog

public void setProtocol(Protocol protocol) {
    this.protocol = protocol;
}

19 Source : ProtocolListenerWrapper.java
with Apache License 2.0
from boomblog

/**
 * ListenerProtocol
 */
public clreplaced ProtocolListenerWrapper implements Protocol {

    private final Protocol protocol;

    public ProtocolListenerWrapper(Protocol protocol) {
        if (protocol == null) {
            throw new IllegalArgumentException("protocol == null");
        }
        this.protocol = protocol;
    }

    @Override
    public int getDefaultPort() {
        return protocol.getDefaultPort();
    }

    @Override
    public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
        if (Constants.REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) {
            return protocol.export(invoker);
        }
        return new ListenerExporterWrapper<T>(protocol.export(invoker), Collections.unmodifiableList(ExtensionLoader.getExtensionLoader(ExporterListener.clreplaced).getActivateExtension(invoker.getUrl(), Constants.EXPORTER_LISTENER_KEY)));
    }

    @Override
    public <T> Invoker<T> refer(Clreplaced<T> type, URL url) throws RpcException {
        if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) {
            return protocol.refer(type, url);
        }
        return new ListenerInvokerWrapper<T>(protocol.refer(type, url), Collections.unmodifiableList(ExtensionLoader.getExtensionLoader(InvokerListener.clreplaced).getActivateExtension(url, Constants.INVOKER_LISTENER_KEY)));
    }

    @Override
    public void destroy() {
        protocol.destroy();
    }
}

19 Source : ProtocolFilterWrapper.java
with Apache License 2.0
from boomblog

/**
 * ListenerProtocol
 */
public clreplaced ProtocolFilterWrapper implements Protocol {

    private final Protocol protocol;

    public ProtocolFilterWrapper(Protocol protocol) {
        if (protocol == null) {
            throw new IllegalArgumentException("protocol == null");
        }
        this.protocol = protocol;
    }

    private static <T> Invoker<T> buildInvokerChain(final Invoker<T> invoker, String key, String group) {
        Invoker<T> last = invoker;
        List<Filter> filters = ExtensionLoader.getExtensionLoader(Filter.clreplaced).getActivateExtension(invoker.getUrl(), key, group);
        if (!filters.isEmpty()) {
            for (int i = filters.size() - 1; i >= 0; i--) {
                final Filter filter = filters.get(i);
                final Invoker<T> next = last;
                last = new Invoker<T>() {

                    @Override
                    public Clreplaced<T> getInterface() {
                        return invoker.getInterface();
                    }

                    @Override
                    public URL getUrl() {
                        return invoker.getUrl();
                    }

                    @Override
                    public boolean isAvailable() {
                        return invoker.isAvailable();
                    }

                    @Override
                    public Result invoke(Invocation invocation) throws RpcException {
                        Result result = filter.invoke(next, invocation);
                        if (result instanceof AsyncRpcResult) {
                            AsyncRpcResult asyncResult = (AsyncRpcResult) result;
                            asyncResult.thenApplyWithContext(r -> filter.onResponse(r, invoker, invocation));
                            return asyncResult;
                        } else {
                            return filter.onResponse(result, invoker, invocation);
                        }
                    }

                    @Override
                    public void destroy() {
                        invoker.destroy();
                    }

                    @Override
                    public String toString() {
                        return invoker.toString();
                    }
                };
            }
        }
        return last;
    }

    @Override
    public int getDefaultPort() {
        return protocol.getDefaultPort();
    }

    @Override
    public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
        if (Constants.REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) {
            return protocol.export(invoker);
        }
        return protocol.export(buildInvokerChain(invoker, Constants.SERVICE_FILTER_KEY, Constants.PROVIDER));
    }

    @Override
    public <T> Invoker<T> refer(Clreplaced<T> type, URL url) throws RpcException {
        if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) {
            return protocol.refer(type, url);
        }
        return buildInvokerChain(protocol.refer(type, url), Constants.REFERENCE_FILTER_KEY, Constants.CONSUMER);
    }

    @Override
    public void destroy() {
        protocol.destroy();
    }
}

19 Source : RegistryProtocolTest.java
with Apache License 2.0
from boomblog

private void destroyRegistryProtocol() {
    Protocol registry = RegistryProtocol.getRegistryProtocol();
    registry.destroy();
}

19 Source : MockProtocol2.java
with Apache License 2.0
from boomblog

public clreplaced MockProtocol2 implements Protocol {

    public static Protocol delegate;

    @Override
    public int getDefaultPort() {
        return delegate.getDefaultPort();
    }

    @Override
    public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
        return delegate.export(invoker);
    }

    @Override
    public <T> Invoker<T> refer(Clreplaced<T> type, URL url) throws RpcException {
        return delegate.refer(type, url);
    }

    @Override
    public void destroy() {
        delegate.destroy();
    }
}

19 Source : RegistryProtocolTest.java
with Apache License 2.0
from apache

private void destroyRegistryProtocol() {
    Protocol registry = getRegistryProtocol();
    registry.destroy();
}

18 Source : WebserviceProtocolTest.java
with Apache License 2.0
from boomblog

/**
 */
public clreplaced WebserviceProtocolTest {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    @Test
    public void testDemoProtocol() throws Exception {
        DemoService service = new DemoServiceImpl();
        protocol.export(proxy.getInvoker(service, DemoService.clreplaced, URL.valueOf("webservice://127.0.0.1:9019/" + DemoService.clreplaced.getName() + "?codec=exchange")));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("webservice://127.0.0.1:9019/" + DemoService.clreplaced.getName() + "?codec=exchange&timeout=3000")));
        replacedertEquals(service.getSize(new String[] { "", "", "" }), 3);
    }

    @Test
    public void testWebserviceProtocol() throws Exception {
        DemoService service = new DemoServiceImpl();
        protocol.export(proxy.getInvoker(service, DemoService.clreplaced, URL.valueOf("webservice://127.0.0.1:9019/" + DemoService.clreplaced.getName())));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("webservice://127.0.0.1:9019/" + DemoService.clreplaced.getName() + "?timeout=3000")));
        replacedertEquals(service.create(1, "kk").getName(), "kk");
        replacedertEquals(service.getSize(null), -1);
        replacedertEquals(service.getSize(new String[] { "", "", "" }), 3);
        Object object = service.invoke("webservice://127.0.0.1:9019/" + DemoService.clreplaced.getName() + "", "invoke");
        System.out.println(object);
        replacedertEquals("webservice://127.0.0.1:9019/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');
        replacedertEquals(32800, service.stringLength(buf.toString()));
    // a method start with $ is illegal in soap
    // // cast to EchoService
    // EchoService echo = proxy.getProxy(protocol.refer(EchoService.clreplaced, URL.valueOf("webservice://127.0.0.1:9010/" + DemoService.clreplaced.getName() + "?client=netty")));
    // replacedertEquals(echo.echo(buf.toString()), buf.toString());
    // replacedertEquals(echo.$echo("test"), "test");
    // replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
    // replacedertEquals(echo.$echo(1234), 1234);
    }
}

18 Source : RmiProtocolTest.java
with Apache License 2.0
from boomblog

public clreplaced RmiProtocolTest {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    /*
    @Test
    public void test_getRemoteClreplaced() throws Exception {
        Clreplaced<NonStdRmiInterface> clazz = RmiProtocol.getRemoteClreplaced(NonStdRmiInterface.clreplaced);
        replacedertEquals(clazz, RmiProtocol.getRemoteClreplaced(NonStdRmiInterface.clreplaced));
    }
    */
    @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.clreplaced, URL.valueOf("rmi://127.0.0.1:9001/TestService")));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("rmi://127.0.0.1:9001/TestService")));
        try {
            try {
                service.throwTimeout();
            } catch (RpcException e) {
                replacedertEquals(true, e.isTimeout());
                replacedertEquals(true, 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.clreplaced, URL.valueOf("rmi://127.0.0.1:9001/TestService")));
            service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("rmi://127.0.0.1:9001/TestService")));
            replacedertEquals(service.getSize(null), -1);
            replacedertEquals(service.getSize(new String[] { "", "", "" }), 3);
            Object result = service.invoke("rmi://127.0.0.1:9001/TestService", "invoke");
            replacedertEquals("rmi://127.0.0.1:9001/TestService:invoke", result);
            rpcExporter.unexport();
        }
        {
            RemoteService remoteService = new RemoteServiceImpl();
            Exporter<?> rpcExporter = protocol.export(proxy.getInvoker(remoteService, RemoteService.clreplaced, URL.valueOf("rmi://127.0.0.1:9002/remoteService")));
            remoteService = proxy.getProxy(protocol.refer(RemoteService.clreplaced, URL.valueOf("rmi://127.0.0.1:9002/remoteService")));
            remoteService.getThreadName();
            for (int i = 0; i < 100; i++) {
                String say = remoteService.sayHello("abcd");
                replacedertEquals("hello abcd@" + RemoteServiceImpl.clreplaced.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.clreplaced, URL.valueOf("rmi://127.0.0.1:9002/TestService")));
        // cast to EchoService
        EchoService echo = proxy.getProxy(protocol.refer(EchoService.clreplaced, URL.valueOf("rmi://127.0.0.1:9002/TestService")));
        replacedertEquals(echo.$echo("test"), "test");
        replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
        replacedertEquals(echo.$echo(1234), 1234);
        rpcExporter.unexport();
        RemoteService remoteService = new RemoteServiceImpl();
        rpcExporter = protocol.export(proxy.getInvoker(remoteService, RemoteService.clreplaced, URL.valueOf("rmi://127.0.0.1:9002/remoteService")));
        // cast to EchoService
        echo = proxy.getProxy(protocol.refer(EchoService.clreplaced, URL.valueOf("rmi://127.0.0.1:9002/remoteService")));
        replacedertEquals(echo.$echo("test"), "test");
        replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
        replacedertEquals(echo.$echo(1234), 1234);
        rpcExporter.unexport();
    }

    public static 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.clreplaced,service);
		RpcUtils.export("dubbo://127.0.0.1:9031/TestService",DemoService.clreplaced,service);
		RpcUtils.export("rmi://127.0.0.1:9032/org.apache.dubbo.rpc.TestService",DemoService.clreplaced,service);
		RpcUtils.export("rmi://127.0.0.1:9033/org.apache.dubbo.rpc.TestService",DemoService.clreplaced,service);

		service = RpcUtils.createProxy(DemoService.clreplaced,
				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",
				});
		replacedertEquals(service.getSize(null), -1);
		replacedertEquals(service.getSize(new String[]{"","",""}), 3);

		// cast to EchoService
		EchoService echo = RpcUtils.createProxy(EchoService.clreplaced,
				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",
		});
		replacedertEquals(echo.$echo("test"), "test");
		replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
		replacedertEquals(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.clreplaced, service);
		protocol.export(proxy.createInvoker("dubbo://127.0.0.1:9041/TestService", DemoService.clreplaced, service);
		protocol.export(proxy.createInvoker("rmi://127.0.0.1:9042/org.apache.dubbo.rpc.TestService", DemoService.clreplaced, service);
		protocol.export(proxy.createInvoker("rmi://127.0.0.1:9043/org.apache.dubbo.rpc.TestService", DemoService.clreplaced, service);

		RpcInvokerGroup group = Proxies.createInvoker(DemoService.clreplaced, 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.clreplaced, group);
		service.echo("test");

		// cast to EchoService
		EchoService echo = proxy.createProxy(protocol.refer(EchoService.clreplaced, group);
		replacedertEquals(echo.$echo("test"), "test");
		replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
		replacedertEquals(echo.$echo(1234), 1234);
	}*/
}

18 Source : RestProtocolTest.java
with Apache License 2.0
from boomblog

/**
 * RestProtocolTest
 */
public clreplaced RestProtocolTest {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    @Test
    public void testRestProtocol() {
        URL url = URL.valueOf("rest://127.0.0.1:5342/rest/say1?version=1.0.0");
        RestServiceImpl server = new RestServiceImpl();
        ProviderModel providerModel = new ProviderModel(url.getServiceKey(), server, RestService.clreplaced);
        ApplicationModel.initProviderModel(url.getServiceKey(), providerModel);
        Exporter<RestService> exporter = protocol.export(proxyFactory.getInvoker(server, RestService.clreplaced, url));
        Invoker<RestService> invoker = protocol.refer(RestService.clreplaced, url);
        replacedertions.replacedertFalse(server.isCalled());
        RestService client = proxyFactory.getProxy(invoker);
        String result = client.sayHello("haha");
        replacedertions.replacedertTrue(server.isCalled());
        replacedertions.replacedertEquals("Hello, haha", result);
        invoker.destroy();
        exporter.unexport();
    }

    @Test
    public void testRestProtocolWithContextPath() {
        RestServiceImpl server = new RestServiceImpl();
        replacedertions.replacedertFalse(server.isCalled());
        URL url = URL.valueOf("rest://127.0.0.1:5341/a/b/c?version=1.0.0");
        ProviderModel providerModel = new ProviderModel(url.getServiceKey(), server, RestService.clreplaced);
        ApplicationModel.initProviderModel(url.getServiceKey(), providerModel);
        Exporter<RestService> exporter = protocol.export(proxyFactory.getInvoker(server, RestService.clreplaced, url));
        url = URL.valueOf("rest://127.0.0.1:5341/a/b/c/?version=1.0.0");
        Invoker<RestService> invoker = protocol.refer(RestService.clreplaced, url);
        RestService client = proxyFactory.getProxy(invoker);
        String result = client.sayHello("haha");
        replacedertions.replacedertTrue(server.isCalled());
        replacedertions.replacedertEquals("Hello, haha", result);
        invoker.destroy();
        exporter.unexport();
    }
}

18 Source : ProtocolUtils.java
with Apache License 2.0
from boomblog

/**
 * TODO Comment of ProtocolUtils
 */
public clreplaced ProtocolUtils {

    public static ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    private static Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    public static <T> T refer(Clreplaced<T> type, String url) {
        return refer(type, URL.valueOf(url));
    }

    public static <T> T refer(Clreplaced<T> type, URL url) {
        return proxy.getProxy(protocol.refer(type, url));
    }

    public static Invoker<?> referInvoker(Clreplaced<?> type, URL url) {
        return (Invoker<?>) protocol.refer(type, url);
    }

    public static <T> Exporter<T> export(T instance, Clreplaced<T> type, String url) {
        return export(instance, type, URL.valueOf(url));
    }

    public static <T> Exporter<T> export(T instance, Clreplaced<T> type, URL url) {
        return protocol.export(proxy.getInvoker(instance, type, url));
    }

    public static void closeAll() {
        DubboProtocol.getDubboProtocol().destroy();
        Collection<ExchangeServer> servers = DubboProtocol.getDubboProtocol().getServers();
        for (ExchangeServer server : servers) {
            server.close();
        }
    }
}

18 Source : EnumBak.java
with Apache License 2.0
from boomblog

public clreplaced EnumBak {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    @Test
    public void testNormal() {
        int port = NetUtils.getAvailablePort();
        URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?proxy=jdk" + "&interface=" + DemoService.clreplaced.getName() + "&timeout=" + Integer.MAX_VALUE);
        DemoService demo = new DemoServiceImpl();
        Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.clreplaced, serviceurl);
        protocol.export(invoker);
        URL consumerurl = serviceurl;
        Invoker<DemoService> reference = protocol.refer(DemoService.clreplaced, consumerurl);
        DemoService demoProxy = (DemoService) proxy.getProxy(reference);
        // System.out.println(demoProxy.getThreadName());
        replacedertions.replacedertEquals((byte) -128, demoProxy.getbyte((byte) -128));
        // invoker.destroy();
        reference.destroy();
    }

    @Disabled
    @Test
    public void testExportService() throws InterruptedException {
        int port = NetUtils.getAvailablePort();
        URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?proxy=jdk&timeout=" + Integer.MAX_VALUE);
        DemoService demo = new DemoServiceImpl();
        Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.clreplaced, serviceurl);
        protocol.export(invoker);
        synchronized (EnumBak.clreplaced) {
            EnumBak.clreplaced.wait();
        }
    // URL consumerurl = serviceurl;
    // Invoker<DemoService> reference = protocol.refer(DemoService.clreplaced, consumerurl);
    // DemoService demoProxy = (DemoService)proxyFactory.createProxy(reference);
    // //        System.out.println(demoProxy.getThreadName());
    // System.out.println("byte:"+demoProxy.getbyte((byte)-128));
    // 
    // invoker.destroy();
    // reference.destroy();
    }

    @Test
    public void testNormalEnum() {
        int port = NetUtils.getAvailablePort();
        URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE);
        DemoService demo = new DemoServiceImpl();
        Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.clreplaced, serviceurl);
        protocol.export(invoker);
        URL consumerurl = serviceurl;
        Invoker<DemoService> reference = protocol.refer(DemoService.clreplaced, consumerurl);
        DemoService demoProxy = (DemoService) proxy.getProxy(reference);
        Type type = demoProxy.enumlength(Type.High);
        System.out.println(type);
        replacedertions.replacedertEquals(Type.High, type);
        invoker.destroy();
        reference.destroy();
    }

    // verify compatibility when 2.0.5 invokes 2.0.3
    @Disabled
    @Test
    public void testEnumCompat() {
        int port = 20880;
        URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE);
        Invoker<DemoService> reference = protocol.refer(DemoService.clreplaced, consumerurl);
        DemoService demoProxy = (DemoService) proxy.getProxy(reference);
        Type type = demoProxy.enumlength(Type.High);
        System.out.println(type);
        replacedertions.replacedertEquals(Type.High, type);
        reference.destroy();
    }

    // verify compatibility when 2.0.5 invokes 2.0.3
    @Disabled
    @Test
    public void testGenricEnumCompat() {
        int port = 20880;
        URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE);
        Invoker<GenericService> reference = protocol.refer(GenericService.clreplaced, consumerurl);
        GenericService demoProxy = (GenericService) proxy.getProxy(reference);
        Object obj = demoProxy.$invoke("enumlength", new String[] { Type[].clreplaced.getName() }, new Object[] { new Type[] { Type.High, Type.High } });
        System.out.println("obj---------->" + obj);
        reference.destroy();
    }

    // verify compatibility when 2.0.5 invokes 2.0.3, enum in custom parameter
    @Disabled
    @Test
    public void testGenricCustomArg() {
        int port = 20880;
        URL consumerurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=2000000");
        Invoker<GenericService> reference = protocol.refer(GenericService.clreplaced, consumerurl);
        GenericService demoProxy = (GenericService) proxy.getProxy(reference);
        Map<String, Object> arg = new HashMap<String, Object>();
        arg.put("type", "High");
        arg.put("name", "hi");
        Object obj = demoProxy.$invoke("get", new String[] { "org.apache.dubbo.rpc.CustomArgument" }, new Object[] { arg });
        System.out.println("obj---------->" + obj);
        reference.destroy();
    }

    @Disabled
    @Test
    public void testGenericExport() throws InterruptedException {
        int port = NetUtils.getAvailablePort();
        port = 20880;
        URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE);
        DemoService demo = new DemoServiceImpl();
        Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.clreplaced, serviceurl);
        protocol.export(invoker);
        // SERVER
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Test
    public void testGenericEnum() throws InterruptedException {
        int port = NetUtils.getAvailablePort();
        URL serviceurl = URL.valueOf("dubbo://127.0.0.1:" + port + "/test?timeout=" + Integer.MAX_VALUE);
        DemoService demo = new DemoServiceImpl();
        Invoker<DemoService> invoker = proxy.getInvoker(demo, DemoService.clreplaced, serviceurl);
        protocol.export(invoker);
        URL consumerurl = serviceurl;
        Invoker<GenericService> reference = protocol.refer(GenericService.clreplaced, consumerurl);
        GenericService demoProxy = (GenericService) proxy.getProxy(reference);
        Object obj = demoProxy.$invoke("enumlength", new String[] { Type[].clreplaced.getName() }, new Object[] { new Type[] { Type.High, Type.High } });
        System.out.println("obj---------->" + obj);
        invoker.destroy();
        reference.destroy();
    }
}

18 Source : RpcFilterTest.java
with Apache License 2.0
from boomblog

public clreplaced RpcFilterTest {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    @AfterEach
    public void after() {
        ProtocolUtils.closeAll();
    }

    @Test
    public void testRpcFilter() throws Exception {
        DemoService service = new DemoServiceImpl();
        URL url = URL.valueOf("dubbo://127.0.0.1:9010/org.apache.dubbo.rpc.DemoService?service.filter=echo");
        protocol.export(proxy.getInvoker(service, DemoService.clreplaced, url));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, url));
        replacedertions.replacedertEquals("123", service.echo("123"));
        // cast to EchoService
        EchoService echo = proxy.getProxy(protocol.refer(EchoService.clreplaced, url));
        replacedertions.replacedertEquals(echo.$echo("test"), "test");
        replacedertions.replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
        replacedertions.replacedertEquals(echo.$echo(1234), 1234);
    }
}

18 Source : MultiThreadTest.java
with Apache License 2.0
from boomblog

public clreplaced MulreplacedhreadTest {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    @AfterEach
    public void after() {
        ProtocolUtils.closeAll();
    }

    @Test
    public void testDubboMulreplacedhreadInvoke() throws Exception {
        Exporter<?> rpcExporter = protocol.export(proxy.getInvoker(new DemoServiceImpl(), DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:20259/TestService")));
        final AtomicInteger counter = new AtomicInteger();
        final DemoService service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:20259/TestService")));
        replacedertions.replacedertEquals(service.getSize(new String[] { "123", "456", "789" }), 3);
        final StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 1024 * 64 + 32; i++) sb.append('A');
        replacedertions.replacedertEquals(sb.toString(), service.echo(sb.toString()));
        ExecutorService exec = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            final int fi = i;
            exec.execute(new Runnable() {

                public void run() {
                    for (int i = 0; i < 30; i++) {
                        System.out.println(fi + ":" + counter.getAndIncrement());
                        replacedertions.replacedertEquals(service.echo(sb.toString()), sb.toString());
                    }
                }
            });
        }
        exec.shutdown();
        exec.awaitTermination(10, TimeUnit.SECONDS);
        rpcExporter.unexport();
    }
}

18 Source : DubboProtocolTest.java
with Apache License 2.0
from boomblog

/**
 * <code>ProxiesTest</code>
 */
public clreplaced DubboProtocolTest {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    @AfterAll
    public static void after() {
        ProtocolUtils.closeAll();
    }

    @Test
    public void testDemoProtocol() throws Exception {
        DemoService service = new DemoServiceImpl();
        protocol.export(proxy.getInvoker(service, DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9020/" + DemoService.clreplaced.getName() + "?codec=exchange")));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9020/" + DemoService.clreplaced.getName() + "?codec=exchange").addParameter("timeout", 3000l)));
        replacedertEquals(service.getSize(new String[] { "", "", "" }), 3);
    }

    @Test
    public void testDubboProtocol() throws Exception {
        DemoService service = new DemoServiceImpl();
        protocol.export(proxy.getInvoker(service, DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.clreplaced.getName())));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.clreplaced.getName()).addParameter("timeout", 3000l)));
        replacedertEquals(service.enumlength(new Type[] {}), Type.Lower);
        replacedertEquals(service.getSize(null), -1);
        replacedertEquals(service.getSize(new String[] { "", "", "" }), 3);
        Map<String, String> map = new HashMap<String, String>();
        map.put("aa", "bb");
        Set<String> set = service.keys(map);
        replacedertEquals(set.size(), 1);
        replacedertEquals(set.iterator().next(), "aa");
        service.invoke("dubbo://127.0.0.1:9010/" + DemoService.clreplaced.getName() + "", "invoke");
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.clreplaced.getName() + "?client=netty").addParameter("timeout", 3000l)));
        // test netty client
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < 1024 * 32 + 32; i++) buf.append('A');
        System.out.println(service.stringLength(buf.toString()));
        // cast to EchoService
        EchoService echo = proxy.getProxy(protocol.refer(EchoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.clreplaced.getName() + "?client=netty").addParameter("timeout", 3000l)));
        replacedertEquals(echo.$echo(buf.toString()), buf.toString());
        replacedertEquals(echo.$echo("test"), "test");
        replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
        replacedertEquals(echo.$echo(1234), 1234);
    }

    @Test
    public void testDubboProtocolWithMina() throws Exception {
        DemoService service = new DemoServiceImpl();
        protocol.export(proxy.getInvoker(service, DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.clreplaced.getName()).addParameter(Constants.SERVER_KEY, "mina")));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.clreplaced.getName()).addParameter(Constants.CLIENT_KEY, "mina").addParameter("timeout", 3000l)));
        for (int i = 0; i < 10; i++) {
            replacedertEquals(service.enumlength(new Type[] {}), Type.Lower);
            replacedertEquals(service.getSize(null), -1);
            replacedertEquals(service.getSize(new String[] { "", "", "" }), 3);
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("aa", "bb");
        for (int i = 0; i < 10; i++) {
            Set<String> set = service.keys(map);
            replacedertEquals(set.size(), 1);
            replacedertEquals(set.iterator().next(), "aa");
            service.invoke("dubbo://127.0.0.1:9010/" + DemoService.clreplaced.getName() + "", "invoke");
        }
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.clreplaced.getName() + "?client=mina").addParameter("timeout", 3000l)));
        // test netty client
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < 1024 * 32 + 32; i++) buf.append('A');
        System.out.println(service.stringLength(buf.toString()));
        // cast to EchoService
        EchoService echo = proxy.getProxy(protocol.refer(EchoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9011/" + DemoService.clreplaced.getName() + "?client=mina").addParameter("timeout", 3000l)));
        for (int i = 0; i < 10; i++) {
            replacedertEquals(echo.$echo(buf.toString()), buf.toString());
            replacedertEquals(echo.$echo("test"), "test");
            replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
            replacedertEquals(echo.$echo(1234), 1234);
        }
    }

    @Test
    public void testDubboProtocolMultiService() throws Exception {
        DemoService service = new DemoServiceImpl();
        protocol.export(proxy.getInvoker(service, DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.clreplaced.getName())));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9010/" + DemoService.clreplaced.getName()).addParameter("timeout", 3000l)));
        RemoteService remote = new RemoteServiceImpl();
        protocol.export(proxy.getInvoker(remote, RemoteService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9010/" + RemoteService.clreplaced.getName())));
        remote = proxy.getProxy(protocol.refer(RemoteService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9010/" + RemoteService.clreplaced.getName()).addParameter("timeout", 3000l)));
        service.sayHello("world");
        // test netty client
        replacedertEquals("world", service.echo("world"));
        replacedertEquals("hello world@" + RemoteServiceImpl.clreplaced.getName(), remote.sayHello("world"));
        EchoService serviceEcho = (EchoService) service;
        replacedertEquals(serviceEcho.$echo("test"), "test");
        EchoService remoteEecho = (EchoService) remote;
        replacedertEquals(remoteEecho.$echo("ok"), "ok");
    }

    @Test
    public void testPerm() throws Exception {
        DemoService service = new DemoServiceImpl();
        protocol.export(proxy.getInvoker(service, DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.clreplaced.getName() + "?codec=exchange")));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.clreplaced.getName() + "?codec=exchange").addParameter("timeout", 3000l)));
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) service.getSize(new String[] { "", "", "" });
        System.out.println("take:" + (System.currentTimeMillis() - start));
    }

    @Test
    public void testNonSerializedParameter() throws Exception {
        DemoService service = new DemoServiceImpl();
        protocol.export(proxy.getInvoker(service, DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.clreplaced.getName() + "?codec=exchange")));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.clreplaced.getName() + "?codec=exchange").addParameter("timeout", 3000l)));
        try {
            service.nonSerializedParameter(new NonSerialized());
            replacedertions.fail();
        } catch (RpcException e) {
            replacedertions.replacedertTrue(e.getMessage().contains("org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable"));
        }
    }

    @Test
    public void testReturnNonSerialized() throws Exception {
        DemoService service = new DemoServiceImpl();
        protocol.export(proxy.getInvoker(service, DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.clreplaced.getName() + "?codec=exchange")));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("dubbo://127.0.0.1:9050/" + DemoService.clreplaced.getName() + "?codec=exchange").addParameter("timeout", 3000l)));
        try {
            service.returnNonSerialized();
            replacedertions.fail();
        } catch (RpcException e) {
            replacedertions.replacedertTrue(e.getMessage().contains("org.apache.dubbo.rpc.protocol.dubbo.support.NonSerialized must implement java.io.Serializable"));
        }
    }
}

18 Source : SimpleRegistryExporter.java
with Apache License 2.0
from boomblog

/**
 * SimpleRegistryExporter
 */
public clreplaced SimpleRegistryExporter {

    private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private static final ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    public synchronized static Exporter<RegistryService> exportIfAbsent(int port) {
        try {
            new ServerSocket(port).close();
            return export(port);
        } catch (IOException e) {
            return null;
        }
    }

    public static Exporter<RegistryService> export(int port) {
        return export(port, new SimpleRegistryService());
    }

    public static Exporter<RegistryService> export(int port, RegistryService registryService) {
        return protocol.export(proxyFactory.getInvoker(registryService, RegistryService.clreplaced, new URL("dubbo", NetUtils.getLocalHost(), port, RegistryService.clreplaced.getName()).setPath(RegistryService.clreplaced.getName()).addParameter(Constants.INTERFACE_KEY, RegistryService.clreplaced.getName()).addParameter(Constants.CLUSTER_STICKY_KEY, "true").addParameter(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "1000").addParameter("ondisconnect", "disconnect").addParameter("subscribe.1.callback", "true").addParameter("unsubscribe.1.callback", "false")));
    }
}

18 Source : RegistryProtocolTest.java
with Apache License 2.0
from boomblog

/**
 * RegistryProtocolTest
 */
public clreplaced RegistryProtocolTest {

    static {
        SimpleRegistryExporter.exportIfAbsent(9090);
    }

    final String service = "org.apache.dubbo.registry.protocol.DemoService: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.clreplaced).getAdaptiveExtension();

    @Test
    public void testDefaultPort() {
        RegistryProtocol registryProtocol = new RegistryProtocol();
        replacedertEquals(9090, registryProtocol.getDefaultPort());
    }

    @Test
    public void testExportUrlNull() {
        replacedertions.replacedertThrows(IllegalArgumentException.clreplaced, () -> {
            RegistryProtocol registryProtocol = new RegistryProtocol();
            registryProtocol.setCluster(new FailfastCluster());
            Protocol dubboProtocol = DubboProtocol.getDubboProtocol();
            registryProtocol.setProtocol(dubboProtocol);
            Invoker<DemoService> invoker = new DubboInvoker<DemoService>(DemoService.clreplaced, registryUrl, new ExchangeClient[] { new MockedClient("10.20.20.20", 2222, true) });
            registryProtocol.export(invoker);
        });
    }

    @Test
    public void testExport() {
        RegistryProtocol registryProtocol = new RegistryProtocol();
        registryProtocol.setCluster(new FailfastCluster());
        registryProtocol.setRegistryFactory(ExtensionLoader.getExtensionLoader(RegistryFactory.clreplaced).getAdaptiveExtension());
        Protocol dubboProtocol = DubboProtocol.getDubboProtocol();
        registryProtocol.setProtocol(dubboProtocol);
        URL newRegistryUrl = registryUrl.addParameter(Constants.EXPORT_KEY, serviceUrl);
        DubboInvoker<DemoService> invoker = new DubboInvoker<DemoService>(DemoService.clreplaced, newRegistryUrl, new ExchangeClient[] { new MockedClient("10.20.20.20", 2222, true) });
        Exporter<DemoService> exporter = registryProtocol.export(invoker);
        Exporter<DemoService> exporter2 = registryProtocol.export(invoker);
        // The same invoker, exporter that multiple exported are different
        replacedertions.replacedertNotSame(exporter, exporter2);
        exporter.unexport();
        exporter2.unexport();
    }

    @Test
    public void testNotifyOverride() throws Exception {
        URL newRegistryUrl = registryUrl.addParameter(Constants.EXPORT_KEY, serviceUrl);
        Invoker<RegistryProtocolTest> invoker = new MockInvoker<RegistryProtocolTest>(RegistryProtocolTest.clreplaced, newRegistryUrl);
        Exporter<?> exporter = protocol.export(invoker);
        RegistryProtocol rprotocol = RegistryProtocol.getRegistryProtocol();
        NotifyListener listener = getListener(rprotocol);
        List<URL> urls = new ArrayList<URL>();
        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);
        replacedertEquals(true, exporter.getInvoker().isAvailable());
        replacedertEquals("100", exporter.getInvoker().getUrl().getParameter("timeout"));
        replacedertEquals("y", exporter.getInvoker().getUrl().getParameter("x"));
        exporter.unexport();
        // int timeout = ConfigUtils.getServerShutdownTimeout();
        // Thread.sleep(timeout + 1000);
        // replacedertEquals(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(Constants.EXPORT_KEY, serviceUrl);
        Invoker<RegistryProtocolTest> invoker = new MockInvoker<RegistryProtocolTest>(RegistryProtocolTest.clreplaced, newRegistryUrl);
        Exporter<?> exporter = protocol.export(invoker);
        RegistryProtocol rprotocol = RegistryProtocol.getRegistryProtocol();
        NotifyListener listener = getListener(rprotocol);
        List<URL> urls = new ArrayList<URL>();
        urls.add(URL.valueOf("override://0.0.0.0/org.apache.dubbo.registry.protocol.HackService?timeout=100"));
        listener.notify(urls);
        replacedertEquals(true, exporter.getInvoker().isAvailable());
        replacedertEquals(null, 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(Constants.EXPORT_KEY, serviceUrl);
        Invoker<RegistryProtocolTest> invoker = new MockInvoker<RegistryProtocolTest>(RegistryProtocolTest.clreplaced, newRegistryUrl);
        Exporter<?> exporter = protocol.export(invoker);
        destroyRegistryProtocol();
        try {
            Thread.sleep(ConfigurationUtils.getServerShutdownTimeout() + 100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        replacedertEquals(false, exporter.getInvoker().isAvailable());
    }

    @Test
    public void testGetParamsToRegistry() {
        RegistryProtocol registryProtocol = new RegistryProtocol();
        String[] additionalParams = new String[] { "key1", "key2" };
        String[] registryParams = registryProtocol.getParamsToRegistry(DEFAULT_REGISTER_PROVIDER_KEYS, additionalParams);
        String[] expectParams = ArrayUtils.addAll(DEFAULT_REGISTER_PROVIDER_KEYS, additionalParams);
        replacedertions.replacedertArrayEquals(expectParams, registryParams);
    }

    private void destroyRegistryProtocol() {
        Protocol registry = RegistryProtocol.getRegistryProtocol();
        registry.destroy();
    }

    private NotifyListener getListener(RegistryProtocol protocol) throws Exception {
        return protocol.getOverrideListeners().values().iterator().next();
    }

    static clreplaced MockInvoker<T> extends AbstractInvoker<T> {

        public MockInvoker(Clreplaced<T> type, URL url) {
            super(type, url);
        }

        @Override
        protected Result doInvoke(Invocation invocation) throws Throwable {
            // do nothing
            return null;
        }
    }

    static clreplaced MockRegistry extends AbstractRegistry {

        public MockRegistry(URL url) {
            super(url);
        }

        @Override
        public boolean isAvailable() {
            return true;
        }
    }
}

18 Source : DubboMonitorFactory.java
with Apache License 2.0
from boomblog

/**
 * DefaultMonitorFactory
 */
public clreplaced DubboMonitorFactory extends AbstractMonitorFactory {

    private Protocol protocol;

    private ProxyFactory proxyFactory;

    public void setProtocol(Protocol protocol) {
        this.protocol = protocol;
    }

    public void setProxyFactory(ProxyFactory proxyFactory) {
        this.proxyFactory = proxyFactory;
    }

    @Override
    protected Monitor createMonitor(URL url) {
        url = url.setProtocol(url.getParameter(Constants.PROTOCOL_KEY, "dubbo"));
        if (StringUtils.isEmpty(url.getPath())) {
            url = url.setPath(MonitorService.clreplaced.getName());
        }
        String filter = url.getParameter(Constants.REFERENCE_FILTER_KEY);
        if (StringUtils.isEmpty(filter)) {
            filter = "";
        } else {
            filter = filter + ",";
        }
        url = url.addParameters(Constants.CLUSTER_KEY, "failsafe", Constants.CHECK_KEY, String.valueOf(false), Constants.REFERENCE_FILTER_KEY, filter + "-monitor");
        Invoker<MonitorService> monitorInvoker = protocol.refer(MonitorService.clreplaced, url);
        MonitorService monitorService = proxyFactory.getProxy(monitorInvoker);
        return new DubboMonitor(monitorInvoker, monitorService);
    }
}

18 Source : MockFilter.java
with Apache License 2.0
from boomblog

/**
 * MockFilter
 */
public clreplaced MockFilter implements Filter {

    private LoadBalance loadBalance;

    private Protocol protocol;

    private MockDao mockDao;

    public MockDao getMockDao() {
        return mockDao;
    }

    public void setMockDao(MockDao mockDao) {
        this.mockDao = mockDao;
    }

    public LoadBalance getLoadBalance() {
        return loadBalance;
    }

    public void setLoadBalance(LoadBalance loadBalance) {
        this.loadBalance = loadBalance;
    }

    public Protocol getProtocol() {
        return protocol;
    }

    public void setProtocol(Protocol protocol) {
        this.protocol = protocol;
    }

    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        return invoker.invoke(invocation);
    }
}

18 Source : SpringExtensionFactoryTest.java
with Apache License 2.0
from boomblog

@Test
public void testGetExtensionBySPI() {
    Protocol protocol = springExtensionFactory.getExtension(Protocol.clreplaced, "protocol");
    replacedertions.replacedertNull(protocol);
}

18 Source : ServiceConfigTest.java
with Apache License 2.0
from boomblog

public clreplaced ServiceConfigTest {

    private Protocol protocolDelegate = Mockito.mock(Protocol.clreplaced);

    private Registry registryDelegate = Mockito.mock(Registry.clreplaced);

    private Exporter exporter = Mockito.mock(Exporter.clreplaced);

    private ServiceConfig<DemoServiceImpl> service = new ServiceConfig<DemoServiceImpl>();

    private ServiceConfig<DemoServiceImpl> service2 = new ServiceConfig<DemoServiceImpl>();

    @BeforeEach
    public void setUp() throws Exception {
        MockProtocol2.delegate = protocolDelegate;
        MockRegistryFactory2.registry = registryDelegate;
        Mockito.when(protocolDelegate.export(Mockito.any(Invoker.clreplaced))).thenReturn(exporter);
        ApplicationConfig app = new ApplicationConfig("app");
        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setName("mockprotocol2");
        ProviderConfig provider = new ProviderConfig();
        provider.setExport(true);
        provider.setProtocol(protocolConfig);
        RegistryConfig registry = new RegistryConfig();
        registry.setProtocol("mockprotocol2");
        registry.setAddress("N/A");
        ArgumentConfig argument = new ArgumentConfig();
        argument.setIndex(0);
        argument.setCallback(false);
        MethodConfig method = new MethodConfig();
        method.setName("echo");
        method.setArguments(Collections.singletonList(argument));
        service.setProvider(provider);
        service.setApplication(app);
        service.setRegistry(registry);
        service.setInterface(DemoService.clreplaced);
        service.setRef(new DemoServiceImpl());
        service.setMethods(Collections.singletonList(method));
        service2.setProvider(provider);
        service2.setApplication(app);
        service2.setRegistry(registry);
        service2.setInterface(DemoService.clreplaced);
        service2.setRef(new DemoServiceImpl());
        service2.setMethods(Collections.singletonList(method));
        service2.setProxy("testproxyfactory");
    }

    @Test
    public void testExport() throws Exception {
        service.export();
        replacedertThat(service.getExportedUrls(), hreplacedize(1));
        URL url = service.toUrl();
        replacedertThat(url.getProtocol(), equalTo("mockprotocol2"));
        replacedertThat(url.getPath(), equalTo(DemoService.clreplaced.getName()));
        replacedertThat(url.getParameters(), hasEntry(Constants.ANYHOST_KEY, "true"));
        replacedertThat(url.getParameters(), hasEntry(Constants.APPLICATION_KEY, "app"));
        replacedertThat(url.getParameters(), hasKey(Constants.BIND_IP_KEY));
        replacedertThat(url.getParameters(), hasKey(Constants.BIND_PORT_KEY));
        replacedertThat(url.getParameters(), hasEntry(Constants.DEFAULT_KEY + "." + Constants.EXPORT_KEY, "true"));
        replacedertThat(url.getParameters(), hasEntry(Constants.EXPORT_KEY, "true"));
        replacedertThat(url.getParameters(), hasEntry("echo.0.callback", "false"));
        replacedertThat(url.getParameters(), hasEntry(Constants.GENERIC_KEY, "false"));
        replacedertThat(url.getParameters(), hasEntry(Constants.INTERFACE_KEY, DemoService.clreplaced.getName()));
        replacedertThat(url.getParameters(), hasKey(Constants.METHODS_KEY));
        replacedertThat(url.getParameters().get(Constants.METHODS_KEY), containsString("echo"));
        replacedertThat(url.getParameters(), hasEntry(Constants.SIDE_KEY, Constants.PROVIDER));
        Mockito.verify(protocolDelegate).export(Mockito.any(Invoker.clreplaced));
    }

    @Test
    public void testProxy() throws Exception {
        service2.export();
        replacedertThat(service2.getExportedUrls(), hreplacedize(1));
        // local injvm and registry protocol, so expected is 2
        replacedertEquals(2, TestProxyFactory.count);
    }

    @Test
    @Disabled("cannot preplaced in travis")
    public void testUnexport() throws Exception {
        System.setProperty(Constants.SHUTDOWN_WAIT_KEY, "0");
        try {
            service.export();
            service.unexport();
            Thread.sleep(1000);
            Mockito.verify(exporter, Mockito.atLeastOnce()).unexport();
        } finally {
            System.clearProperty(Constants.SHUTDOWN_TIMEOUT_KEY);
        }
    }

    @Test
    public void testInterfaceClreplaced() throws Exception {
        ServiceConfig<Greeting> service = new ServiceConfig<Greeting>();
        service.setInterface(Greeting.clreplaced.getName());
        service.setRef(Mockito.mock(Greeting.clreplaced));
        replacedertThat(service.getInterfaceClreplaced() == Greeting.clreplaced, is(true));
        service = new ServiceConfig<Greeting>();
        service.setRef(Mockito.mock(Greeting.clreplaced, withSettings().extraInterfaces(GenericService.clreplaced)));
        replacedertThat(service.getInterfaceClreplaced() == GenericService.clreplaced, is(true));
    }

    @Test
    public void testInterface1() throws Exception {
        replacedertions.replacedertThrows(IllegalStateException.clreplaced, () -> {
            ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
            service.setInterface(DemoServiceImpl.clreplaced);
        });
    }

    @Test
    public void testInterface2() throws Exception {
        ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
        service.setInterface(DemoService.clreplaced);
        replacedertThat(service.getInterface(), equalTo(DemoService.clreplaced.getName()));
    }

    @Test
    public void testProvider() throws Exception {
        ServiceConfig service = new ServiceConfig();
        ProviderConfig provider = new ProviderConfig();
        service.setProvider(provider);
        replacedertThat(service.getProvider(), is(provider));
    }

    @Test
    public void testGeneric1() throws Exception {
        ServiceConfig service = new ServiceConfig();
        service.setGeneric(GENERIC_SERIALIZATION_DEFAULT);
        replacedertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_DEFAULT));
        service.setGeneric(GENERIC_SERIALIZATION_NATIVE_JAVA);
        replacedertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_NATIVE_JAVA));
        service.setGeneric(GENERIC_SERIALIZATION_BEAN);
        replacedertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_BEAN));
    }

    @Test
    public void testGeneric2() throws Exception {
        replacedertions.replacedertThrows(IllegalArgumentException.clreplaced, () -> {
            ServiceConfig service = new ServiceConfig();
            service.setGeneric("illegal");
        });
    }

    @Test
    public void testMock() throws Exception {
        replacedertions.replacedertThrows(IllegalArgumentException.clreplaced, () -> {
            ServiceConfig service = new ServiceConfig();
            service.setMock("true");
        });
    }

    @Test
    public void testMock2() throws Exception {
        replacedertions.replacedertThrows(IllegalArgumentException.clreplaced, () -> {
            ServiceConfig service = new ServiceConfig();
            service.setMock(true);
        });
    }

    @Test
    public void testUniqueServiceName() throws Exception {
        ServiceConfig<Greeting> service = new ServiceConfig<Greeting>();
        service.setGroup("dubbo");
        service.setInterface(Greeting.clreplaced);
        service.setVersion("1.0.0");
        replacedertThat(service.getUniqueServiceName(), equalTo("dubbo/" + Greeting.clreplaced.getName() + ":1.0.0"));
    }
}

18 Source : ServiceConfigTest.java
with Apache License 2.0
from apache

public clreplaced ServiceConfigTest {

    private Protocol protocolDelegate = Mockito.mock(Protocol.clreplaced);

    private Registry registryDelegate = Mockito.mock(Registry.clreplaced);

    private Exporter exporter = Mockito.mock(Exporter.clreplaced);

    private ServiceConfig<DemoServiceImpl> service = new ServiceConfig<DemoServiceImpl>();

    private ServiceConfig<DemoServiceImpl> service2 = new ServiceConfig<DemoServiceImpl>();

    private ServiceConfig<DemoServiceImpl> delayService = new ServiceConfig<DemoServiceImpl>();

    @BeforeEach
    public void setUp() throws Exception {
        MockProtocol2.delegate = protocolDelegate;
        MockRegistryFactory2.registry = registryDelegate;
        Mockito.when(protocolDelegate.export(Mockito.any(Invoker.clreplaced))).thenReturn(exporter);
        ApplicationConfig app = new ApplicationConfig("app");
        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setName("mockprotocol2");
        ProviderConfig provider = new ProviderConfig();
        provider.setExport(true);
        provider.setProtocol(protocolConfig);
        RegistryConfig registry = new RegistryConfig();
        registry.setProtocol("mockprotocol2");
        registry.setAddress("N/A");
        ArgumentConfig argument = new ArgumentConfig();
        argument.setIndex(0);
        argument.setCallback(false);
        MethodConfig method = new MethodConfig();
        method.setName("echo");
        method.setArguments(Collections.singletonList(argument));
        service.setProvider(provider);
        service.setApplication(app);
        service.setRegistry(registry);
        service.setInterface(DemoService.clreplaced);
        service.setRef(new DemoServiceImpl());
        service.setMethods(Collections.singletonList(method));
        service2.setProvider(provider);
        service2.setApplication(app);
        service2.setRegistry(registry);
        service2.setInterface(DemoService.clreplaced);
        service2.setRef(new DemoServiceImpl());
        service2.setMethods(Collections.singletonList(method));
        service2.setProxy("testproxyfactory");
        delayService.setProvider(provider);
        delayService.setApplication(app);
        delayService.setRegistry(registry);
        delayService.setInterface(DemoService.clreplaced);
        delayService.setRef(new DemoServiceImpl());
        delayService.setMethods(Collections.singletonList(method));
        delayService.setDelay(100);
    // ApplicationModel.getConfigManager().clear();
    }

    @AfterEach
    public void tearDown() {
    // ApplicationModel.getConfigManager().clear();
    }

    @Test
    public void testExport() throws Exception {
        service.export();
        replacedertThat(service.getExportedUrls(), hreplacedize(1));
        URL url = service.toUrl();
        replacedertThat(url.getProtocol(), equalTo("mockprotocol2"));
        replacedertThat(url.getPath(), equalTo(DemoService.clreplaced.getName()));
        replacedertThat(url.getParameters(), hasEntry(ANYHOST_KEY, "true"));
        replacedertThat(url.getParameters(), hasEntry(APPLICATION_KEY, "app"));
        replacedertThat(url.getParameters(), hasKey(BIND_IP_KEY));
        replacedertThat(url.getParameters(), hasKey(BIND_PORT_KEY));
        replacedertThat(url.getParameters(), hasEntry(EXPORT_KEY, "true"));
        replacedertThat(url.getParameters(), hasEntry("echo.0.callback", "false"));
        replacedertThat(url.getParameters(), hasEntry(GENERIC_KEY, "false"));
        replacedertThat(url.getParameters(), hasEntry(INTERFACE_KEY, DemoService.clreplaced.getName()));
        replacedertThat(url.getParameters(), hasKey(METHODS_KEY));
        replacedertThat(url.getParameters().get(METHODS_KEY), containsString("echo"));
        replacedertThat(url.getParameters(), hasEntry(SIDE_KEY, PROVIDER));
        Mockito.verify(protocolDelegate).export(Mockito.any(Invoker.clreplaced));
    }

    @Test
    public void testProxy() throws Exception {
        service2.export();
        replacedertThat(service2.getExportedUrls(), hreplacedize(1));
        // local injvm and registry protocol, so expected is 2
        replacedertEquals(2, TestProxyFactory.count);
    }

    @Test
    public void testDelayExport() throws Exception {
        delayService.export();
        replacedertTrue(delayService.getExportedUrls().isEmpty());
        // add 300ms to ensure that the delayService has been exported
        TimeUnit.MILLISECONDS.sleep(delayService.getDelay() + 300);
        replacedertThat(delayService.getExportedUrls(), hreplacedize(1));
    }

    @Test
    @Disabled("cannot preplaced in travis")
    public void testUnexport() throws Exception {
        System.setProperty(SHUTDOWN_WAIT_KEY, "0");
        try {
            service.export();
            service.unexport();
            Thread.sleep(1000);
            Mockito.verify(exporter, Mockito.atLeastOnce()).unexport();
        } finally {
            System.clearProperty(SHUTDOWN_TIMEOUT_KEY);
        }
    }

    @Test
    public void testInterfaceClreplaced() throws Exception {
        ServiceConfig<Greeting> service = new ServiceConfig<Greeting>();
        service.setInterface(Greeting.clreplaced.getName());
        service.setRef(Mockito.mock(Greeting.clreplaced));
        replacedertThat(service.getInterfaceClreplaced() == Greeting.clreplaced, is(true));
        service = new ServiceConfig<Greeting>();
        service.setRef(Mockito.mock(Greeting.clreplaced, withSettings().extraInterfaces(GenericService.clreplaced)));
        replacedertThat(service.getInterfaceClreplaced() == GenericService.clreplaced, is(true));
    }

    @Test
    public void testInterface1() throws Exception {
        replacedertions.replacedertThrows(IllegalStateException.clreplaced, () -> {
            ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
            service.setInterface(DemoServiceImpl.clreplaced);
        });
    }

    @Test
    public void testInterface2() throws Exception {
        ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
        service.setInterface(DemoService.clreplaced);
        replacedertThat(service.getInterface(), equalTo(DemoService.clreplaced.getName()));
    }

    @Test
    public void testProvider() throws Exception {
        ServiceConfig service = new ServiceConfig();
        ProviderConfig provider = new ProviderConfig();
        service.setProvider(provider);
        replacedertThat(service.getProvider(), is(provider));
    }

    @Test
    public void testGeneric1() throws Exception {
        ServiceConfig service = new ServiceConfig();
        service.setGeneric(GENERIC_SERIALIZATION_DEFAULT);
        replacedertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_DEFAULT));
        service.setGeneric(GENERIC_SERIALIZATION_NATIVE_JAVA);
        replacedertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_NATIVE_JAVA));
        service.setGeneric(GENERIC_SERIALIZATION_BEAN);
        replacedertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_BEAN));
    }

    @Test
    public void testGeneric2() throws Exception {
        replacedertions.replacedertThrows(IllegalArgumentException.clreplaced, () -> {
            ServiceConfig service = new ServiceConfig();
            service.setGeneric("illegal");
        });
    }

    // @Test
    // public void testMock() throws Exception {
    // replacedertions.replacedertThrows(IllegalArgumentException.clreplaced, () -> {
    // ServiceConfig service = new ServiceConfig();
    // service.setMock("true");
    // });
    // }
    // 
    // @Test
    // public void testMock2() throws Exception {
    // replacedertions.replacedertThrows(IllegalArgumentException.clreplaced, () -> {
    // ServiceConfig service = new ServiceConfig();
    // service.setMock(true);
    // });
    // }
    @Test
    public void testApplicationInUrl() {
        service.export();
        replacedertions.replacedertNotNull(service.toUrl().getParameter(APPLICATION_KEY));
        replacedertions.replacedertEquals("app", service.toUrl().getParameter(APPLICATION_KEY));
    }
}

18 Source : WebserviceProtocolTest.java
with Apache License 2.0
from apache

/**
 */
public clreplaced WebserviceProtocolTest {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    @Test
    public void testDemoProtocol() throws Exception {
        DemoService service = new DemoServiceImpl();
        int port = NetUtils.getAvailablePort();
        Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(service, DemoService.clreplaced, URL.valueOf("webservice://127.0.0.1:" + port + "/" + DemoService.clreplaced.getName() + "?codec=exchange")));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("webservice://127.0.0.1:" + port + "/" + DemoService.clreplaced.getName() + "?codec=exchange&timeout=3000")));
        replacedertEquals(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.clreplaced, URL.valueOf("webservice://127.0.0.1:" + port + "/" + DemoService.clreplaced.getName())));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("webservice://127.0.0.1:" + port + "/" + DemoService.clreplaced.getName() + "?timeout=3000")));
        replacedertEquals(service.create(1, "kk").getName(), "kk");
        replacedertEquals(service.getSize(null), -1);
        replacedertEquals(service.getSize(new String[] { "", "", "" }), 3);
        Object object = service.invoke("webservice://127.0.0.1:" + port + "/" + DemoService.clreplaced.getName() + "", "invoke");
        System.out.println(object);
        replacedertEquals("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');
        replacedertEquals(32800, service.stringLength(buf.toString()));
    // a method start with $ is illegal in soap
    // // cast to EchoService
    // EchoService echo = proxy.getProxy(protocol.refer(EchoService.clreplaced, URL.valueOf("webservice://127.0.0.1:9010/" + DemoService.clreplaced.getName() + "?client=netty")));
    // replacedertEquals(echo.echo(buf.toString()), buf.toString());
    // replacedertEquals(echo.$echo("test"), "test");
    // replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
    // replacedertEquals(echo.$echo(1234), 1234);
    }
}

18 Source : RmiProtocolTest.java
with Apache License 2.0
from apache

public clreplaced RmiProtocolTest {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    int availablePort = NetUtils.getAvailablePort();

    /*
    @Test
    public void test_getRemoteClreplaced() throws Exception {
        Clreplaced<NonStdRmiInterface> clazz = RmiProtocol.getRemoteClreplaced(NonStdRmiInterface.clreplaced);
        replacedertEquals(clazz, RmiProtocol.getRemoteClreplaced(NonStdRmiInterface.clreplaced));
    }
    */
    @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.clreplaced, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService")));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService")));
        try {
            try {
                service.throwTimeout();
            } catch (RpcException e) {
                replacedertTrue(e.isTimeout());
                replacedertTrue(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.clreplaced, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService")));
            service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService")));
            replacedertEquals(service.getSize(null), -1);
            replacedertEquals(service.getSize(new String[] { "", "", "" }), 3);
            Object result = service.invoke("rmi://127.0.0.1:" + availablePort + "/TestService", "invoke");
            replacedertEquals("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.clreplaced, URL.valueOf("rmi://127.0.0.1:" + port + "/remoteService")));
            remoteService = proxy.getProxy(protocol.refer(RemoteService.clreplaced, URL.valueOf("rmi://127.0.0.1:" + port + "/remoteService")));
            remoteService.getThreadName();
            for (int i = 0; i < 100; i++) {
                String say = remoteService.sayHello("abcd");
                replacedertEquals("hello abcd@" + RemoteServiceImpl.clreplaced.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.clreplaced, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService")));
        // cast to EchoService
        EchoService echo = proxy.getProxy(protocol.refer(EchoService.clreplaced, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/TestService")));
        replacedertEquals(echo.$echo("test"), "test");
        replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
        replacedertEquals(echo.$echo(1234), 1234);
        rpcExporter.unexport();
        RemoteService remoteService = new RemoteServiceImpl();
        rpcExporter = protocol.export(proxy.getInvoker(remoteService, RemoteService.clreplaced, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/remoteService")));
        // cast to EchoService
        echo = proxy.getProxy(protocol.refer(EchoService.clreplaced, URL.valueOf("rmi://127.0.0.1:" + availablePort + "/remoteService")));
        replacedertEquals(echo.$echo("test"), "test");
        replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
        replacedertEquals(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.clreplaced.getName() + "?release=2.7.0");
        Exporter<DemoService> exporter = protocol.export(proxy.getInvoker(service, DemoService.clreplaced, url));
        Invoker<GenericService> invoker = protocol.refer(GenericService.clreplaced, url);
        GenericService client = proxy.getProxy(invoker, true);
        String result = (String) client.$invoke("sayHi", new String[] { "java.lang.String" }, new Object[] { "haha" });
        replacedertions.replacedertEquals("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.clreplaced, url));
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, url));
        replacedertEquals(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.clreplaced,service);
		RpcUtils.export("dubbo://127.0.0.1:9031/TestService",DemoService.clreplaced,service);
		RpcUtils.export("rmi://127.0.0.1:9032/org.apache.dubbo.rpc.TestService",DemoService.clreplaced,service);
		RpcUtils.export("rmi://127.0.0.1:9033/org.apache.dubbo.rpc.TestService",DemoService.clreplaced,service);

		service = RpcUtils.createProxy(DemoService.clreplaced,
				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",
				});
		replacedertEquals(service.getSize(null), -1);
		replacedertEquals(service.getSize(new String[]{"","",""}), 3);

		// cast to EchoService
		EchoService echo = RpcUtils.createProxy(EchoService.clreplaced,
				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",
		});
		replacedertEquals(echo.$echo("test"), "test");
		replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
		replacedertEquals(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.clreplaced, service);
		protocol.export(proxy.createInvoker("dubbo://127.0.0.1:9041/TestService", DemoService.clreplaced, service);
		protocol.export(proxy.createInvoker("rmi://127.0.0.1:9042/org.apache.dubbo.rpc.TestService", DemoService.clreplaced, service);
		protocol.export(proxy.createInvoker("rmi://127.0.0.1:9043/org.apache.dubbo.rpc.TestService", DemoService.clreplaced, service);

		RpcInvokerGroup group = Proxies.createInvoker(DemoService.clreplaced, 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.clreplaced, group);
		service.echo("test");

		// cast to EchoService
		EchoService echo = proxy.createProxy(protocol.refer(EchoService.clreplaced, group);
		replacedertEquals(echo.$echo("test"), "test");
		replacedertEquals(echo.$echo("abcdefg"), "abcdefg");
		replacedertEquals(echo.$echo(1234), 1234);
	}*/
}

18 Source : SimpleRegistryExporter.java
with Apache License 2.0
from apache

/**
 * SimpleRegistryExporter
 */
public clreplaced SimpleRegistryExporter {

    private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private static final ProxyFactory PROXY_FACTORY = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    public synchronized static Exporter<RegistryService> exportIfAbsent(int port) {
        try {
            new ServerSocket(port).close();
            return export(port);
        } catch (IOException e) {
            return null;
        }
    }

    public static Exporter<RegistryService> export(int port) {
        return export(port, new SimpleRegistryService());
    }

    public static Exporter<RegistryService> export(int port, RegistryService registryService) {
        return protocol.export(PROXY_FACTORY.getInvoker(registryService, RegistryService.clreplaced, new URLBuilder(DUBBO_PROTOCOL, NetUtils.getLocalHost(), port, RegistryService.clreplaced.getName()).setPath(RegistryService.clreplaced.getName()).addParameter(INTERFACE_KEY, RegistryService.clreplaced.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.clreplaced);
        repository.registerProvider(url.getServiceKey(), registryService, serviceDescriptor, null, null);
    }
}

18 Source : RegistryProtocolTest.java
with Apache License 2.0
from apache

/**
 * RegistryProtocolTest
 */
public clreplaced RegistryProtocolTest {

    static {
        SimpleRegistryExporter.exportIfAbsent(9090);
    }

    final String service = DemoService.clreplaced.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.clreplaced).getAdaptiveExtension();

    public static RegistryProtocol getRegistryProtocol() {
        return RegistryProtocol.getRegistryProtocol();
    }

    @BeforeEach
    public void setUp() {
        ApplicationModel.setApplication("RegistryProtocolTest");
        ApplicationModel.getServiceRepository().registerService(RegistryService.clreplaced);
    }

    @Test
    public void testDefaultPort() {
        RegistryProtocol registryProtocol = getRegistryProtocol();
        replacedertEquals(9090, registryProtocol.getDefaultPort());
    }

    @Test
    public void testExportUrlNull() {
        replacedertions.replacedertThrows(IllegalArgumentException.clreplaced, () -> {
            RegistryProtocol registryProtocol = getRegistryProtocol();
            registryProtocol.setCluster(new FailfastCluster());
            Protocol dubboProtocol = DubboProtocol.getDubboProtocol();
            registryProtocol.setProtocol(dubboProtocol);
            Invoker<DemoService> invoker = new DubboInvoker<DemoService>(DemoService.clreplaced, 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.clreplaced).getAdaptiveExtension());
        Protocol dubboProtocol = DubboProtocol.getDubboProtocol();
        registryProtocol.setProtocol(dubboProtocol);
        URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl);
        DubboInvoker<DemoService> invoker = new DubboInvoker<DemoService>(DemoService.clreplaced, newRegistryUrl, new ExchangeClient[] { new MockedClient("10.20.20.20", 2222, true) });
        Exporter<DemoService> exporter = registryProtocol.export(invoker);
        Exporter<DemoService> exporter2 = registryProtocol.export(invoker);
        // The same invoker, exporter that multiple exported are different
        replacedertions.replacedertNotSame(exporter, exporter2);
        exporter.unexport();
        exporter2.unexport();
    }

    // @Test
    // public void testNotifyOverride() throws Exception {
    // URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl);
    // Invoker<RegistryProtocolTest> invoker = new MockInvoker<RegistryProtocolTest>(RegistryProtocolTest.clreplaced, newRegistryUrl);
    // 
    // ServiceDescriptor descriptor = ApplicationModel.getServiceRepository().registerService(DemoService.clreplaced);
    // ApplicationModel.getServiceRepository().registerProvider(service, new DemoServiceImpl(), descriptor, null, null);
    // 
    // Exporter<?> exporter = protocol.export(invoker);
    // RegistryProtocol rprotocol = getRegistryProtocol();
    // NotifyListener listener = getListener(rprotocol);
    // List<URL> urls = new ArrayList<URL>();
    // 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);
    // 
    // replacedertTrue(exporter.getInvoker().isAvailable());
    // replacedertEquals("100", exporter.getInvoker().getUrl().getParameter("timeout"));
    // replacedertEquals("y", exporter.getInvoker().getUrl().getParameter("x"));
    // 
    // exporter.unexport();
    // //        int timeout = ConfigUtils.getServerShutdownTimeout();
    // //        Thread.sleep(timeout + 1000);
    // //        replacedertEquals(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<RegistryProtocolTest> invoker = new MockInvoker<RegistryProtocolTest>(RegistryProtocolTest.clreplaced, newRegistryUrl);
        ServiceDescriptor descriptor = ApplicationModel.getServiceRepository().registerService(DemoService.clreplaced);
        ApplicationModel.getServiceRepository().registerProvider(service, new DemoServiceImpl(), descriptor, null, null);
        Exporter<?> exporter = protocol.export(invoker);
        RegistryProtocol rprotocol = getRegistryProtocol();
        NotifyListener listener = getListener(rprotocol);
        List<URL> urls = new ArrayList<URL>();
        urls.add(URL.valueOf("override://0.0.0.0/org.apache.dubbo.registry.protocol.HackService?timeout=100"));
        listener.notify(urls);
        replacedertTrue(exporter.getInvoker().isAvailable());
        replacedertNull(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<RegistryProtocolTest> invoker = new MockInvoker<RegistryProtocolTest>(RegistryProtocolTest.clreplaced, newRegistryUrl);
        Exporter<?> exporter = protocol.export(invoker);
        destroyRegistryProtocol();
        try {
            Thread.sleep(ConfigurationUtils.getServerShutdownTimeout() + 100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        replacedertFalse(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);
        replacedertions.replacedertArrayEquals(expectParams, registryParams);
    }

    private void destroyRegistryProtocol() {
        Protocol registry = getRegistryProtocol();
        registry.destroy();
    }

    private NotifyListener getListener(RegistryProtocol protocol) throws Exception {
        return protocol.getOverrideListeners().values().iterator().next();
    }

    static clreplaced MockInvoker<T> extends AbstractInvoker<T> {

        public MockInvoker(Clreplaced<T> type, URL url) {
            super(type, url);
        }

        @Override
        protected Result doInvoke(Invocation invocation) throws Throwable {
            // do nothing
            return null;
        }
    }

    static clreplaced MockRegistry extends AbstractRegistry {

        public MockRegistry(URL url) {
            super(url);
        }

        @Override
        public boolean isAvailable() {
            return true;
        }
    }
}

17 Source : RestProtocolTest.java
with Apache License 2.0
from boomblog

public clreplaced RestProtocolTest {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getExtension("rest");

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    private final int availablePort = NetUtils.getAvailablePort();

    private final URL exportUrl = URL.valueOf("rest://127.0.0.1:" + availablePort + "/rest");

    @AfterEach
    public void tearDown() {
        protocol.destroy();
    }

    @Test
    public void testExport() {
        IDemoService server = new DemoService();
        ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.clreplaced);
        ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel);
        RpcContext.getContext().setAttachment("timeout", "200");
        Exporter<IDemoService> exporter = protocol.export(proxy.getInvoker(server, IDemoService.clreplaced, exportUrl));
        IDemoService demoService = this.proxy.getProxy(protocol.refer(IDemoService.clreplaced, exportUrl));
        Integer echoString = demoService.hello(1, 2);
        replacedertThat(echoString, is(3));
        exporter.unexport();
    }

    @Test
    public void testNettyServer() {
        IDemoService server = new DemoService();
        ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.clreplaced);
        ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel);
        URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty");
        Exporter<IDemoService> exporter = protocol.export(proxy.getInvoker(new DemoService(), IDemoService.clreplaced, nettyUrl));
        IDemoService demoService = this.proxy.getProxy(protocol.refer(IDemoService.clreplaced, nettyUrl));
        Integer echoString = demoService.hello(10, 10);
        replacedertThat(echoString, is(20));
        exporter.unexport();
    }

    @Test
    public void testServletWithoutWebConfig() {
        replacedertions.replacedertThrows(RpcException.clreplaced, () -> {
            IDemoService server = new DemoService();
            ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.clreplaced);
            ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel);
            URL servletUrl = exportUrl.addParameter(Constants.SERVER_KEY, "servlet");
            protocol.export(proxy.getInvoker(server, IDemoService.clreplaced, servletUrl));
        });
    }

    @Test
    public void testErrorHandler() {
        replacedertions.replacedertThrows(RpcException.clreplaced, () -> {
            IDemoService server = new DemoService();
            ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.clreplaced);
            ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel);
            URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty");
            Exporter<IDemoService> exporter = protocol.export(proxy.getInvoker(server, IDemoService.clreplaced, nettyUrl));
            IDemoService demoService = this.proxy.getProxy(protocol.refer(IDemoService.clreplaced, nettyUrl));
            demoService.error();
        });
    }

    @Test
    public void testInvoke() {
        IDemoService server = new DemoService();
        ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.clreplaced);
        ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel);
        Exporter<IDemoService> exporter = protocol.export(proxy.getInvoker(server, IDemoService.clreplaced, exportUrl));
        RpcInvocation rpcInvocation = new RpcInvocation("hello", new Clreplaced[] { Integer.clreplaced, Integer.clreplaced }, new Integer[] { 2, 3 });
        Result result = exporter.getInvoker().invoke(rpcInvocation);
        replacedertThat(result.getValue(), CoreMatchers.<Object>is(5));
    }

    @Test
    public void testFilter() {
        IDemoService server = new DemoService();
        ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.clreplaced);
        ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel);
        URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty").addParameter(Constants.EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.support.LoggingFilter");
        Exporter<IDemoService> exporter = protocol.export(proxy.getInvoker(server, IDemoService.clreplaced, nettyUrl));
        IDemoService demoService = this.proxy.getProxy(protocol.refer(IDemoService.clreplaced, nettyUrl));
        Integer result = demoService.hello(1, 2);
        replacedertThat(result, is(3));
        exporter.unexport();
    }

    @Test
    public void testRpcContextFilter() {
        IDemoService server = new DemoService();
        ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.clreplaced);
        ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel);
        // use RpcContextFilter
        URL nettyUrl = exportUrl.addParameter(Constants.SERVER_KEY, "netty").addParameter(Constants.EXTENSION_KEY, "org.apache.dubbo.rpc.protocol.rest.RpcContextFilter");
        Exporter<IDemoService> exporter = protocol.export(proxy.getInvoker(server, IDemoService.clreplaced, nettyUrl));
        IDemoService demoService = this.proxy.getProxy(protocol.refer(IDemoService.clreplaced, nettyUrl));
        String value = null;
        // put a null value into attachment.
        RpcContext.getContext().setAttachment("key", value);
        Integer result = demoService.hello(1, 2);
        replacedertThat(result, is(3));
        exporter.unexport();
    }

    @Test
    public void testRegFail() {
        replacedertions.replacedertThrows(RuntimeException.clreplaced, () -> {
            IDemoService server = new DemoService();
            ProviderModel providerModel = new ProviderModel(exportUrl.getServiceKey(), server, IDemoService.clreplaced);
            ApplicationModel.initProviderModel(exportUrl.getServiceKey(), providerModel);
            URL nettyUrl = exportUrl.addParameter(Constants.EXTENSION_KEY, "com.not.existing.Filter");
            protocol.export(proxy.getInvoker(server, IDemoService.clreplaced, nettyUrl));
        });
    }

    @Test
    public void testDefaultPort() {
        replacedertThat(protocol.getDefaultPort(), is(80));
    }
}

17 Source : InjvmProtocolTest.java
with Apache License 2.0
from boomblog

/**
 * <code>ProxiesTest</code>
 */
public clreplaced InjvmProtocolTest {

    static {
        InjvmProtocol injvm = InjvmProtocol.getInjvmProtocol();
    }

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    private List<Exporter<?>> exporters = new ArrayList<Exporter<?>>();

    @AfterEach
    public void after() throws Exception {
        for (Exporter<?> exporter : exporters) {
            exporter.unexport();
        }
        exporters.clear();
    }

    @Test
    public void testLocalProtocol() throws Exception {
        DemoService service = new DemoServiceImpl();
        Invoker<?> invoker = proxy.getInvoker(service, DemoService.clreplaced, URL.valueOf("injvm://127.0.0.1/TestService").addParameter(Constants.INTERFACE_KEY, DemoService.clreplaced.getName()));
        replacedertTrue(invoker.isAvailable());
        Exporter<?> exporter = protocol.export(invoker);
        exporters.add(exporter);
        service = proxy.getProxy(protocol.refer(DemoService.clreplaced, URL.valueOf("injvm://127.0.0.1/TestService").addParameter(Constants.INTERFACE_KEY, DemoService.clreplaced.getName())));
        replacedertEquals(service.getSize(new String[] { "", "", "" }), 3);
        service.invoke("injvm://127.0.0.1/TestService", "invoke");
        InjvmInvoker injvmInvoker = new InjvmInvoker(DemoService.clreplaced, URL.valueOf("injvm://127.0.0.1/TestService"), null, new HashMap<String, Exporter<?>>());
        replacedertFalse(injvmInvoker.isAvailable());
    }

    @Test
    public void testIsInjvmRefer() throws Exception {
        DemoService service = new DemoServiceImpl();
        URL url = URL.valueOf("injvm://127.0.0.1/TestService").addParameter(Constants.INTERFACE_KEY, DemoService.clreplaced.getName());
        Exporter<?> exporter = protocol.export(proxy.getInvoker(service, DemoService.clreplaced, url));
        exporters.add(exporter);
        url = url.setProtocol("dubbo");
        replacedertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url));
        url = url.addParameter(Constants.GROUP_KEY, "*").addParameter(Constants.VERSION_KEY, "*");
        replacedertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url));
        url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(Constants.SCOPE_KEY, Constants.SCOPE_LOCAL);
        replacedertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url));
        url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(Constants.LOCAL_PROTOCOL, true);
        replacedertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url));
        url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(Constants.SCOPE_KEY, Constants.SCOPE_REMOTE);
        replacedertFalse(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url));
        url = URL.valueOf("fake://127.0.0.1/TestService").addParameter(Constants.GENERIC_KEY, true);
        replacedertFalse(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url));
    }
}

17 Source : StubProxyFactoryWrapper.java
with Apache License 2.0
from boomblog

/**
 * StubProxyFactoryWrapper
 */
public clreplaced StubProxyFactoryWrapper implements ProxyFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(StubProxyFactoryWrapper.clreplaced);

    private final ProxyFactory proxyFactory;

    private Protocol protocol;

    public StubProxyFactoryWrapper(ProxyFactory proxyFactory) {
        this.proxyFactory = proxyFactory;
    }

    public void setProtocol(Protocol protocol) {
        this.protocol = protocol;
    }

    @Override
    public <T> T getProxy(Invoker<T> invoker, boolean generic) throws RpcException {
        return proxyFactory.getProxy(invoker, generic);
    }

    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public <T> T getProxy(Invoker<T> invoker) throws RpcException {
        T proxy = proxyFactory.getProxy(invoker);
        if (GenericService.clreplaced != invoker.getInterface()) {
            String stub = invoker.getUrl().getParameter(Constants.STUB_KEY, invoker.getUrl().getParameter(Constants.LOCAL_KEY));
            if (ConfigUtils.isNotEmpty(stub)) {
                Clreplaced<?> serviceType = invoker.getInterface();
                if (ConfigUtils.isDefault(stub)) {
                    if (invoker.getUrl().hasParameter(Constants.STUB_KEY)) {
                        stub = serviceType.getName() + "Stub";
                    } else {
                        stub = serviceType.getName() + "Local";
                    }
                }
                try {
                    Clreplaced<?> stubClreplaced = ReflectUtils.forName(stub);
                    if (!serviceType.isreplacedignableFrom(stubClreplaced)) {
                        throw new IllegalStateException("The stub implementation clreplaced " + stubClreplaced.getName() + " not implement interface " + serviceType.getName());
                    }
                    try {
                        Constructor<?> constructor = ReflectUtils.findConstructor(stubClreplaced, serviceType);
                        proxy = (T) constructor.newInstance(new Object[] { proxy });
                        // export stub service
                        URL url = invoker.getUrl();
                        if (url.getParameter(Constants.STUB_EVENT_KEY, Constants.DEFAULT_STUB_EVENT)) {
                            url = url.addParameter(Constants.STUB_EVENT_METHODS_KEY, StringUtils.join(Wrapper.getWrapper(proxy.getClreplaced()).getDeclaredMethodNames(), ","));
                            url = url.addParameter(Constants.IS_SERVER_KEY, Boolean.FALSE.toString());
                            try {
                                export(proxy, (Clreplaced) invoker.getInterface(), url);
                            } catch (Exception e) {
                                LOGGER.error("export a stub service error.", e);
                            }
                        }
                    } catch (NoSuchMethodException e) {
                        throw new IllegalStateException("No such constructor \"public " + stubClreplaced.getSimpleName() + "(" + serviceType.getName() + ")\" in stub implementation clreplaced " + stubClreplaced.getName(), e);
                    }
                } catch (Throwable t) {
                    LOGGER.error("Failed to create stub implementation clreplaced " + stub + " in consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", cause: " + t.getMessage(), t);
                // ignore
                }
            }
        }
        return proxy;
    }

    @Override
    public <T> Invoker<T> getInvoker(T proxy, Clreplaced<T> type, URL url) throws RpcException {
        return proxyFactory.getInvoker(proxy, type, url);
    }

    private <T> Exporter<T> export(T instance, Clreplaced<T> type, URL url) {
        return protocol.export(proxyFactory.getInvoker(instance, type, url));
    }
}

17 Source : DubboRegistryFactory.java
with Apache License 2.0
from boomblog

/**
 * DubboRegistryFactory
 */
public clreplaced DubboRegistryFactory extends AbstractRegistryFactory {

    private Protocol protocol;

    private ProxyFactory proxyFactory;

    private Cluster cluster;

    private static URL getRegistryURL(URL url) {
        return url.setPath(RegistryService.clreplaced.getName()).removeParameter(Constants.EXPORT_KEY).removeParameter(Constants.REFER_KEY).addParameter(Constants.INTERFACE_KEY, RegistryService.clreplaced.getName()).addParameter(Constants.CLUSTER_STICKY_KEY, "true").addParameter(Constants.LAZY_CONNECT_KEY, "true").addParameter(Constants.RECONNECT_KEY, "false").addParameterIfAbsent(Constants.TIMEOUT_KEY, "10000").addParameterIfAbsent(Constants.CALLBACK_INSTANCES_LIMIT_KEY, "10000").addParameterIfAbsent(Constants.CONNECT_TIMEOUT_KEY, "10000").addParameter(Constants.METHODS_KEY, StringUtils.join(new HashSet<>(Arrays.asList(Wrapper.getWrapper(RegistryService.clreplaced).getDeclaredMethodNames())), ",")).addParameter("subscribe.1.callback", "true").addParameter("unsubscribe.1.callback", "false");
    }

    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<URL> urls = new ArrayList<>();
        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.clreplaced, url.addParameter(Constants.INTERFACE_KEY, RegistryService.clreplaced.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.setRouterChain(RouterChain.buildChain(url));
        directory.notify(urls);
        directory.subscribe(new URL(Constants.CONSUMER_PROTOCOL, NetUtils.getLocalHost(), 0, RegistryService.clreplaced.getName(), url.getParameters()));
        return registry;
    }
}

17 Source : QosProtocolWrapper.java
with Apache License 2.0
from boomblog

public clreplaced QosProtocolWrapper implements Protocol {

    private final Logger logger = LoggerFactory.getLogger(QosProtocolWrapper.clreplaced);

    private static AtomicBoolean hreplacedtarted = new AtomicBoolean(false);

    private Protocol protocol;

    public QosProtocolWrapper(Protocol protocol) {
        if (protocol == null) {
            throw new IllegalArgumentException("protocol == null");
        }
        this.protocol = protocol;
    }

    @Override
    public int getDefaultPort() {
        return protocol.getDefaultPort();
    }

    @Override
    public <T> Exporter<T> export(Invoker<T> invoker) throws RpcException {
        if (Constants.REGISTRY_PROTOCOL.equals(invoker.getUrl().getProtocol())) {
            startQosServer(invoker.getUrl());
            return protocol.export(invoker);
        }
        return protocol.export(invoker);
    }

    @Override
    public <T> Invoker<T> refer(Clreplaced<T> type, URL url) throws RpcException {
        if (Constants.REGISTRY_PROTOCOL.equals(url.getProtocol())) {
            startQosServer(url);
            return protocol.refer(type, url);
        }
        return protocol.refer(type, url);
    }

    @Override
    public void destroy() {
        protocol.destroy();
        stopServer();
    }

    private void startQosServer(URL url) {
        try {
            boolean qosEnable = url.getParameter(QOS_ENABLE, true);
            if (!qosEnable) {
                logger.info("qos won't be started because it is disabled. " + "Please check dubbo.application.qos.enable is configured either in system property, " + "dubbo.properties or XML/spring-boot configuration.");
                return;
            }
            if (!hreplacedtarted.compareAndSet(false, true)) {
                return;
            }
            int port = url.getParameter(QOS_PORT, QosConstants.DEFAULT_PORT);
            boolean acceptForeignIp = Boolean.parseBoolean(url.getParameter(ACCEPT_FOREIGN_IP, "false"));
            Server server = Server.getInstance();
            server.setPort(port);
            server.setAcceptForeignIp(acceptForeignIp);
            server.start();
        } catch (Throwable throwable) {
            logger.warn("Fail to start qos server: ", throwable);
        }
    }

    /*package*/
    void stopServer() {
        if (hreplacedtarted.compareAndSet(true, false)) {
            Server server = Server.getInstance();
            server.stop();
        }
    }
}

17 Source : MockClusterInvokerTest.java
with Apache License 2.0
from boomblog

/**
 * Test if mock policy works fine: fail-mock
 */
@Test
public void testMockInvokerInvoke_normal() {
    URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.clreplaced.getName());
    url = url.addParameter(Constants.MOCK_KEY, "fail");
    Invoker<IHelloService> cluster = getClusterInvoker(url);
    URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.clreplaced.getName() + "?getSomething.mock=return aa");
    Protocol protocol = new MockProtocol();
    Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.clreplaced, mockUrl);
    invokers.add(mInvoker1);
    // Configured with mock
    RpcInvocation invocation = new RpcInvocation();
    invocation.setMethodName("getSomething");
    Result ret = cluster.invoke(invocation);
    replacedertions.replacedertEquals("something", ret.getValue());
    // If no mock was configured, return null directly
    invocation = new RpcInvocation();
    invocation.setMethodName("sayHello");
    ret = cluster.invoke(invocation);
    replacedertions.replacedertEquals(null, ret.getValue());
}

17 Source : MockClusterInvokerTest.java
with Apache License 2.0
from boomblog

@Test
public void testMockInvokerInvoke_forcemock_defaultreturn() {
    URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.clreplaced.getName());
    url = url.addParameter(Constants.MOCK_KEY, "force");
    Invoker<IHelloService> cluster = getClusterInvoker(url);
    URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.clreplaced.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.clreplaced, mockUrl);
    invokers.add(mInvoker1);
    RpcInvocation invocation = new RpcInvocation();
    invocation.setMethodName("sayHello");
    Result ret = cluster.invoke(invocation);
    replacedertions.replacedertEquals(null, ret.getValue());
}

17 Source : MockClusterInvokerTest.java
with Apache License 2.0
from boomblog

/**
 * Test if mock policy works fine: force-mock
 */
@Test
public void testMockInvokerInvoke_forcemock() {
    URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.clreplaced.getName());
    url = url.addParameter(Constants.MOCK_KEY, "force:return null");
    URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.clreplaced.getName() + "?getSomething.mock=return aa&getSomething3xx.mock=return xx").addParameters(url.getParameters());
    Protocol protocol = new MockProtocol();
    Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.clreplaced, mockUrl);
    Invoker<IHelloService> cluster = getClusterInvokerMock(url, mInvoker1);
    // Configured with mock
    RpcInvocation invocation = new RpcInvocation();
    invocation.setMethodName("getSomething");
    Result ret = cluster.invoke(invocation);
    replacedertions.replacedertEquals("aa", ret.getValue());
    // If no mock was configured, return null directly
    invocation = new RpcInvocation();
    invocation.setMethodName("getSomething2");
    ret = cluster.invoke(invocation);
    replacedertions.replacedertEquals(null, ret.getValue());
    // If no mock was configured, return null directly
    invocation = new RpcInvocation();
    invocation.setMethodName("sayHello");
    ret = cluster.invoke(invocation);
    replacedertions.replacedertEquals(null, ret.getValue());
}

17 Source : DubboRegistryFactory.java
with Apache License 2.0
from apache

/**
 * DubboRegistryFactory
 */
public clreplaced DubboRegistryFactory extends AbstractRegistryFactory {

    private Protocol protocol;

    private ProxyFactory proxyFactory;

    private Cluster cluster;

    private static URL getRegistryURL(URL url) {
        return URLBuilder.from(url).setPath(RegistryService.clreplaced.getName()).removeParameter(EXPORT_KEY).removeParameter(REFER_KEY).addParameter(INTERFACE_KEY, RegistryService.clreplaced.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.clreplaced).getDeclaredMethodNames())), ",")).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<URL> 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<RegistryService> directory = new RegistryDirectory<>(RegistryService.clreplaced, url.addParameter(INTERFACE_KEY, RegistryService.clreplaced.getName()).addParameterAndEncoded(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.setRouterChain(RouterChain.buildChain(url));
        directory.notify(urls);
        directory.subscribe(new URL(CONSUMER_PROTOCOL, NetUtils.getLocalHost(), 0, RegistryService.clreplaced.getName(), url.getParameters()));
        return registry;
    }
}

16 Source : AbstractTest.java
with Apache License 2.0
from boomblog

public abstract clreplaced 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.clreplaced).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.clreplaced, new $__DemoStub.Processor(getServiceImpl()));
        return result;
    }

    protected Clreplaced<?> getInterface() {
        return Demo.clreplaced;
    }

    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();
    }
}

16 Source : RedisProtocolTest.java
with Apache License 2.0
from boomblog

public clreplaced RedisProtocolTest {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).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 preplacedword = "123456";
            this.redisServer = RedisServer.builder().port(redisPort).setting("requirepreplaced " + preplacedword).build();
            this.registryUrl = URL.valueOf("redis://username:" + preplacedword + "@localhost:" + redisPort + "?db.index=0");
        } else {
            this.redisServer = RedisServer.builder().port(redisPort).build();
            this.registryUrl = URL.valueOf("redis://localhost:" + redisPort);
        }
        this.redisServer.start();
    }

    @AfterEach
    public void tearDown() {
        this.redisServer.stop();
    }

    @Test
    public void testReferClreplaced() {
        Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl);
        Clreplaced<IDemoService> serviceClreplaced = refer.getInterface();
        replacedertThat(serviceClreplaced.getName(), is("org.apache.dubbo.rpc.protocol.redis.IDemoService"));
    }

    @Test
    public void testInvocation() {
        Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
        IDemoService demoService = this.proxy.getProxy(refer);
        String value = demoService.get("key");
        replacedertThat(value, is(nullValue()));
        demoService.set("key", "newValue");
        value = demoService.get("key");
        replacedertThat(value, is("newValue"));
        demoService.delete("key");
        value = demoService.get("key");
        replacedertThat(value, is(nullValue()));
        refer.destroy();
    }

    @Test
    public void testUnsupportedMethod() {
        replacedertions.replacedertThrows(RpcException.clreplaced, () -> {
            Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl);
            IDemoService demoService = this.proxy.getProxy(refer);
            demoService.unsupported(null);
        });
    }

    @Test
    public void testWrongParameters() {
        replacedertions.replacedertThrows(RpcException.clreplaced, () -> {
            Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl);
            IDemoService demoService = this.proxy.getProxy(refer);
            demoService.set("key", "value", "wrongValue");
        });
    }

    @Test
    public void testWrongRedis() {
        replacedertions.replacedertThrows(RpcException.clreplaced, () -> {
            Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, URL.valueOf("redis://localhost:1"));
            IDemoService demoService = this.proxy.getProxy(refer);
            demoService.get("key");
        });
    }

    @Test
    public void testExport() {
        replacedertions.replacedertThrows(UnsupportedOperationException.clreplaced, () -> protocol.export(protocol.refer(IDemoService.clreplaced, registryUrl)));
    }

    @Test
    public void testAuthRedis() {
        // default db.index=0
        Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
        IDemoService demoService = this.proxy.getProxy(refer);
        String value = demoService.get("key");
        replacedertThat(value, is(nullValue()));
        demoService.set("key", "newValue");
        value = demoService.get("key");
        replacedertThat(value, is("newValue"));
        demoService.delete("key");
        value = demoService.get("key");
        replacedertThat(value, is(nullValue()));
        refer.destroy();
        // change db.index=1
        String preplacedword = "123456";
        int database = 1;
        this.registryUrl = this.registryUrl.setPreplacedword(preplacedword).addParameter("db.index", database);
        refer = protocol.refer(IDemoService.clreplaced, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
        demoService = this.proxy.getProxy(refer);
        demoService.set("key", "newValue");
        value = demoService.get("key");
        replacedertThat(value, is("newValue"));
        // jedis gets the result comparison
        JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), "localhost", registryUrl.getPort(), 2000, preplacedword, database, (String) null);
        Jedis jedis = null;
        try {
            jedis = pool.getResource();
            byte[] valueByte = jedis.get("key".getBytes());
            Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.clreplaced).getExtension(this.registryUrl.getParameter(Constants.SERIALIZATION_KEY, "java"));
            ObjectInput oin = serialization.deserialize(this.registryUrl, new ByteArrayInputStream(valueByte));
            String actual = (String) oin.readObject();
            replacedertThat(value, is(actual));
        } catch (Exception e) {
            replacedertions.fail("jedis gets the result comparison is error!");
        } finally {
            if (jedis != null) {
                jedis.close();
            }
            pool.destroy();
        }
        demoService.delete("key");
        value = demoService.get("key");
        replacedertThat(value, is(nullValue()));
        refer.destroy();
    }

    @Test
    public void testWrongAuthRedis() {
        String preplacedword = "1234567";
        this.registryUrl = this.registryUrl.setPreplacedword(preplacedword);
        Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
        IDemoService demoService = this.proxy.getProxy(refer);
        try {
            String value = demoService.get("key");
            replacedertThat(value, is(nullValue()));
        } catch (RpcException e) {
            if (e.getCause() instanceof JedisConnectionException && e.getCause().getCause() instanceof JedisDataException) {
                replacedertions.replacedertEquals("ERR invalid preplacedword", e.getCause().getCause().getMessage());
            } else {
                replacedertions.fail("no invalid preplacedword exception!");
            }
        }
        refer.destroy();
    }
}

16 Source : RegistryProtocolTest.java
with Apache License 2.0
from boomblog

@Test
public void testExport() {
    RegistryProtocol registryProtocol = new RegistryProtocol();
    registryProtocol.setCluster(new FailfastCluster());
    registryProtocol.setRegistryFactory(ExtensionLoader.getExtensionLoader(RegistryFactory.clreplaced).getAdaptiveExtension());
    Protocol dubboProtocol = DubboProtocol.getDubboProtocol();
    registryProtocol.setProtocol(dubboProtocol);
    URL newRegistryUrl = registryUrl.addParameter(Constants.EXPORT_KEY, serviceUrl);
    DubboInvoker<DemoService> invoker = new DubboInvoker<DemoService>(DemoService.clreplaced, newRegistryUrl, new ExchangeClient[] { new MockedClient("10.20.20.20", 2222, true) });
    Exporter<DemoService> exporter = registryProtocol.export(invoker);
    Exporter<DemoService> exporter2 = registryProtocol.export(invoker);
    // The same invoker, exporter that multiple exported are different
    replacedertions.replacedertNotSame(exporter, exporter2);
    exporter.unexport();
    exporter2.unexport();
}

16 Source : QosProtocolWrapperTest.java
with Apache License 2.0
from boomblog

public clreplaced QosProtocolWrapperTest {

    private URL url = Mockito.mock(URL.clreplaced);

    private Invoker invoker = mock(Invoker.clreplaced);

    private Protocol protocol = mock(Protocol.clreplaced);

    private QosProtocolWrapper wrapper = new QosProtocolWrapper(protocol);

    private Server server = Server.getInstance();

    @BeforeEach
    public void setUp() throws Exception {
        when(url.getParameter(Constants.QOS_ENABLE, true)).thenReturn(true);
        when(url.getParameter(Constants.QOS_PORT, 22222)).thenReturn(12345);
        when(url.getParameter(Constants.ACCEPT_FOREIGN_IP, true)).thenReturn(false);
        when(invoker.getUrl()).thenReturn(url);
        when(url.getProtocol()).thenReturn(Constants.REGISTRY_PROTOCOL);
    }

    @AfterEach
    public void tearDown() throws Exception {
        if (server.isStarted()) {
            server.stop();
        }
    }

    @Test
    public void testExport() throws Exception {
        wrapper.export(invoker);
        replacedertThat(server.isStarted(), is(true));
        replacedertThat(server.getPort(), is(12345));
        replacedertThat(server.isAcceptForeignIp(), is(false));
        verify(protocol).export(invoker);
    }

    @Test
    public void testRefer() throws Exception {
        wrapper.refer(BaseCommand.clreplaced, url);
        replacedertThat(server.isStarted(), is(true));
        replacedertThat(server.getPort(), is(12345));
        replacedertThat(server.isAcceptForeignIp(), is(false));
        verify(protocol).refer(BaseCommand.clreplaced, url);
    }
}

16 Source : ProtocolConfigTest.java
with Apache License 2.0
from boomblog

@Test
public void testDestroy() throws Exception {
    Protocol protocol = Mockito.mock(Protocol.clreplaced);
    MockProtocol2.delegate = protocol;
    ProtocolConfig protocolConfig = new ProtocolConfig();
    protocolConfig.setName("mockprotocol2");
    protocolConfig.destroy();
    Mockito.verify(protocol).destroy();
}

16 Source : MockClusterInvokerTest.java
with Apache License 2.0
from boomblog

/**
 * Test if mock policy works fine: fail-mock
 */
@Test
public void testMockInvokerInvoke_failmock() {
    URL url = URL.valueOf("remote://1.2.3.4/" + IHelloService.clreplaced.getName()).addParameter(Constants.MOCK_KEY, "fail:return null").addParameter("invoke_return_error", "true");
    URL mockUrl = URL.valueOf("mock://localhost/" + IHelloService.clreplaced.getName() + "?getSomething.mock=return aa").addParameters(url.getParameters());
    Protocol protocol = new MockProtocol();
    Invoker<IHelloService> mInvoker1 = protocol.refer(IHelloService.clreplaced, mockUrl);
    Invoker<IHelloService> cluster = getClusterInvokerMock(url, mInvoker1);
    // Configured with mock
    RpcInvocation invocation = new RpcInvocation();
    invocation.setMethodName("getSomething");
    Result ret = cluster.invoke(invocation);
    replacedertions.replacedertEquals("aa", ret.getValue());
    // If no mock was configured, return null directly
    invocation = new RpcInvocation();
    invocation.setMethodName("getSomething2");
    ret = cluster.invoke(invocation);
    replacedertions.replacedertEquals(null, ret.getValue());
    // If no mock was configured, return null directly
    invocation = new RpcInvocation();
    invocation.setMethodName("sayHello");
    ret = cluster.invoke(invocation);
    replacedertions.replacedertEquals(null, ret.getValue());
}

16 Source : RedisProtocolTest.java
with Apache License 2.0
from apache

public clreplaced RedisProtocolTest {

    private Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    private ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).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 preplacedword = "123456";
            RedisServerBuilder builder = RedisServer.builder().port(redisPort).setting("requirepreplaced " + preplacedword);
            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:" + preplacedword + "@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 testReferClreplaced() {
        Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl);
        Clreplaced<IDemoService> serviceClreplaced = refer.getInterface();
        replacedertThat(serviceClreplaced.getName(), is("org.apache.dubbo.rpc.protocol.redis.IDemoService"));
    }

    @Test
    public void testInvocation() {
        Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
        IDemoService demoService = this.proxy.getProxy(refer);
        String value = demoService.get("key");
        replacedertThat(value, is(nullValue()));
        demoService.set("key", "newValue");
        value = demoService.get("key");
        replacedertThat(value, is("newValue"));
        demoService.delete("key");
        value = demoService.get("key");
        replacedertThat(value, is(nullValue()));
        refer.destroy();
    }

    @Test
    public void testUnsupportedMethod() {
        replacedertions.replacedertThrows(RpcException.clreplaced, () -> {
            Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl);
            IDemoService demoService = this.proxy.getProxy(refer);
            demoService.unsupported(null);
        });
    }

    @Test
    public void testWrongParameters() {
        replacedertions.replacedertThrows(RpcException.clreplaced, () -> {
            Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl);
            IDemoService demoService = this.proxy.getProxy(refer);
            demoService.set("key", "value", "wrongValue");
        });
    }

    @Test
    public void testWrongRedis() {
        replacedertions.replacedertThrows(RpcException.clreplaced, () -> {
            Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, URL.valueOf("redis://localhost:1"));
            IDemoService demoService = this.proxy.getProxy(refer);
            demoService.get("key");
        });
    }

    @Test
    public void testExport() {
        replacedertions.replacedertThrows(UnsupportedOperationException.clreplaced, () -> protocol.export(protocol.refer(IDemoService.clreplaced, registryUrl)));
    }

    @Test
    public void testAuthRedis() {
        // default db.index=0
        Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
        IDemoService demoService = this.proxy.getProxy(refer);
        String value = demoService.get("key");
        replacedertThat(value, is(nullValue()));
        demoService.set("key", "newValue");
        value = demoService.get("key");
        replacedertThat(value, is("newValue"));
        demoService.delete("key");
        value = demoService.get("key");
        replacedertThat(value, is(nullValue()));
        refer.destroy();
        // change db.index=1
        String preplacedword = "123456";
        int database = 1;
        this.registryUrl = this.registryUrl.setPreplacedword(preplacedword).addParameter("db.index", database);
        refer = protocol.refer(IDemoService.clreplaced, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
        demoService = this.proxy.getProxy(refer);
        demoService.set("key", "newValue");
        value = demoService.get("key");
        replacedertThat(value, is("newValue"));
        // jedis gets the result comparison
        JedisPool pool = new JedisPool(new GenericObjectPoolConfig(), "localhost", registryUrl.getPort(), 2000, preplacedword, database, (String) null);
        try (Jedis jedis = pool.getResource()) {
            byte[] valueByte = jedis.get("key".getBytes());
            Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.clreplaced).getExtension(this.registryUrl.getParameter(Constants.SERIALIZATION_KEY, "java"));
            ObjectInput oin = serialization.deserialize(this.registryUrl, new ByteArrayInputStream(valueByte));
            String actual = (String) oin.readObject();
            replacedertThat(value, is(actual));
        } catch (Exception e) {
            replacedertions.fail("jedis gets the result comparison is error!");
        } finally {
            pool.destroy();
        }
        demoService.delete("key");
        value = demoService.get("key");
        replacedertThat(value, is(nullValue()));
        refer.destroy();
    }

    @Test
    public void testWrongAuthRedis() {
        String preplacedword = "1234567";
        this.registryUrl = this.registryUrl.setPreplacedword(preplacedword);
        Invoker<IDemoService> refer = protocol.refer(IDemoService.clreplaced, registryUrl.addParameter("max.idle", 10).addParameter("max.active", 20));
        IDemoService demoService = this.proxy.getProxy(refer);
        try {
            String value = demoService.get("key");
            replacedertThat(value, is(nullValue()));
        } catch (RpcException e) {
            if (e.getCause() instanceof JedisConnectionException && e.getCause().getCause() instanceof JedisDataException) {
                replacedertions.replacedertEquals("ERR invalid preplacedword", e.getCause().getCause().getMessage());
            } else {
                replacedertions.fail("no invalid preplacedword exception!");
            }
        }
        refer.destroy();
    }
}

16 Source : RegistryProtocolTest.java
with Apache License 2.0
from apache

@Test
public void testExport() {
    RegistryProtocol registryProtocol = getRegistryProtocol();
    registryProtocol.setCluster(new FailfastCluster());
    registryProtocol.setRegistryFactory(ExtensionLoader.getExtensionLoader(RegistryFactory.clreplaced).getAdaptiveExtension());
    Protocol dubboProtocol = DubboProtocol.getDubboProtocol();
    registryProtocol.setProtocol(dubboProtocol);
    URL newRegistryUrl = registryUrl.addParameter(EXPORT_KEY, serviceUrl);
    DubboInvoker<DemoService> invoker = new DubboInvoker<DemoService>(DemoService.clreplaced, newRegistryUrl, new ExchangeClient[] { new MockedClient("10.20.20.20", 2222, true) });
    Exporter<DemoService> exporter = registryProtocol.export(invoker);
    Exporter<DemoService> exporter2 = registryProtocol.export(invoker);
    // The same invoker, exporter that multiple exported are different
    replacedertions.replacedertNotSame(exporter, exporter2);
    exporter.unexport();
    exporter2.unexport();
}

15 Source : RegistryProtocolTest.java
with Apache License 2.0
from boomblog

@Test
public void testExportUrlNull() {
    replacedertions.replacedertThrows(IllegalArgumentException.clreplaced, () -> {
        RegistryProtocol registryProtocol = new RegistryProtocol();
        registryProtocol.setCluster(new FailfastCluster());
        Protocol dubboProtocol = DubboProtocol.getDubboProtocol();
        registryProtocol.setProtocol(dubboProtocol);
        Invoker<DemoService> invoker = new DubboInvoker<DemoService>(DemoService.clreplaced, registryUrl, new ExchangeClient[] { new MockedClient("10.20.20.20", 2222, true) });
        registryProtocol.export(invoker);
    });
}

15 Source : RegistryDirectoryTest.java
with Apache License 2.0
from boomblog

@SuppressWarnings({ "rawtypes", "unchecked" })
public clreplaced RegistryDirectoryTest {

    private static boolean isScriptUnsupported = new ScriptEngineManager().getEngineByName("javascript") == null;

    RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.clreplaced).getAdaptiveExtension();

    Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    String service = DemoService.clreplaced.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.clreplaced);

    @BeforeEach
    public void setUp() {
    }

    private RegistryDirectory getRegistryDirectory(URL url) {
        RegistryDirectory registryDirectory = new RegistryDirectory(URL.clreplaced, url);
        registryDirectory.setProtocol(protocol);
        registryDirectory.setRegistry(registry);
        registryDirectory.setRouterChain(RouterChain.buildChain(url));
        registryDirectory.subscribe(url);
        // asert empty
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(0, invokers.size());
        replacedertions.replacedertEquals(false, 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.clreplaced, 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(Constants.REFER_KEY, "foo=bar");
        RegistryDirectory reg = getRegistryDirectory(url);
        Field field = reg.getClreplaced().getDeclaredField("queryMap");
        field.setAccessible(true);
        Map<String, String> queryMap = (Map<String, String>) field.get(reg);
        replacedertions.replacedertEquals("bar", queryMap.get("foo"));
        replacedertions.replacedertEquals(url.clearParameters().addParameter("foo", "bar"), reg.getUrl());
    }

    @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);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        replacedertions.replacedertTrue(LogUtil.checkNoError(), "notify no invoker urls ,should not error");
        LogUtil.stop();
        test_Notified2invokers(registryDirectory);
    }

    @Test
    public void testNotified_WithError() {
        RegistryDirectory registryDirectory = getRegistryDirectory();
        List<URL> serviceUrls = new ArrayList<URL>();
        // ignore error log
        URL badurl = URL.valueOf("notsupported://127.0.0.1/" + service);
        serviceUrls.add(badurl);
        serviceUrls.add(SERVICEURL);
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
    }

    @Test
    public void testNotified_WithDuplicateUrls() {
        List<URL> serviceUrls = new ArrayList<URL>();
        // ignore error log
        serviceUrls.add(SERVICEURL);
        serviceUrls.add(SERVICEURL);
        RegistryDirectory registryDirectory = getRegistryDirectory();
        registryDirectory.notify(serviceUrls);
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
    }

    // forbid
    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);
        replacedertions.replacedertEquals(false, registryDirectory.isAvailable(), "invokers size=0 ,then the registry directory is not available");
        try {
            registryDirectory.list(invocation);
            fail("forbid must throw RpcException");
        } catch (RpcException e) {
            replacedertions.replacedertEquals(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<URL> serviceUrls = new ArrayList<URL>();
        URL Dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true");
        serviceUrls.add(Dubbo1URL.addParameter("methods", "getXXX"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        invocation = new RpcInvocation();
        List<Invoker<DemoService>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        invocation.setMethodName("getXXX");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        replacedertions.replacedertEquals(DemoService.clreplaced.getName(), invokers.get(0).getUrl().getPath());
    }

    // notify one invoker
    private void test_Notified_only_routers(RegistryDirectory registryDirectory) {
        List<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(URL.valueOf("empty://127.0.0.1/?category=routers"));
        registryDirectory.notify(serviceUrls);
    }

    // notify one invoker
    private void test_Notified1invokers(RegistryDirectory registryDirectory) {
        List<URL> serviceUrls = new ArrayList<URL>();
        // .addParameter("refer.autodestroy", "true")
        serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1").addParameter(Constants.APPLICATION_KEY, "mockApplicationName"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        invocation = new RpcInvocation();
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        invocation.setMethodName("getXXX");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        invocation.setMethodName("getXXX1");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        invocation.setMethodName("getXXX2");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
    }

    // 2 invokers===================================
    private void test_Notified2invokers(RegistryDirectory registryDirectory) {
        List<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1"));
        serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2"));
        serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        invocation = new RpcInvocation();
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        invocation.setMethodName("getXXX");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        invocation.setMethodName("getXXX1");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
    }

    // 3 invoker notifications===================================
    private void test_Notified3invokers(RegistryDirectory registryDirectory) {
        List<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1"));
        serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2"));
        serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1,getXXX2,getXXX3"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        invocation = new RpcInvocation();
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(3, invokers.size());
        invocation.setMethodName("getXXX");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(3, invokers.size());
        invocation.setMethodName("getXXX1");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(3, invokers.size());
        invocation.setMethodName("getXXX2");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(3, invokers.size());
        invocation.setMethodName("getXXX3");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(3, invokers.size());
    }

    @Test
    public void testParametersMerge() {
        RegistryDirectory registryDirectory = getRegistryDirectory();
        URL regurl = noMeaningUrl.addParameter("test", "reg").addParameterAndEncoded(Constants.REFER_KEY, "key=query&" + Constants.LOADBALANCE_KEY + "=" + LeastActiveLoadBalance.NAME);
        RegistryDirectory<RegistryDirectoryTest> registryDirectory2 = new RegistryDirectory(RegistryDirectoryTest.clreplaced, regurl);
        registryDirectory2.setProtocol(protocol);
        List<URL> serviceUrls = new ArrayList<URL>();
        // 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();
            replacedertions.replacedertEquals(null, 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();
            replacedertions.replacedertEquals("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();
            replacedertions.replacedertEquals("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();
            replacedertions.replacedertEquals(false, url.getParameter(Constants.CHECK_KEY, false));
        }
        {
            serviceUrls.clear();
            serviceUrls.add(SERVICEURL.addParameter(Constants.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();
            replacedertions.replacedertEquals(LeastActiveLoadBalance.NAME, url.getMethodParameter("get", Constants.LOADBALANCE_KEY));
        }
        // test geturl
        {
            replacedertions.replacedertEquals(null, registryDirectory2.getUrl().getParameter("mock"));
            serviceUrls.clear();
            serviceUrls.add(SERVICEURL.addParameter(Constants.MOCK_KEY, "true"));
            registryDirectory2.notify(serviceUrls);
            replacedertions.replacedertEquals("true", registryDirectory2.getUrl().getParameter("mock"));
        }
    }

    /**
     * When destroying, RegistryDirectory should: 1. be disconnected from Registry 2. destroy all invokers
     */
    @Test
    public void testDestroy() {
        RegistryDirectory registryDirectory = getRegistryDirectory();
        List<URL> serviceUrls = new ArrayList<URL>();
        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<Invoker> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        replacedertions.replacedertEquals(true, invokers.get(0).isAvailable());
        registryDirectory.destroy();
        replacedertions.replacedertEquals(false, registryDirectory.isAvailable());
        replacedertions.replacedertEquals(false, invokers.get(0).isAvailable());
        registryDirectory.destroy();
        List<Invoker<RegistryDirectoryTest>> cachedInvokers = registryDirectory.getInvokers();
        Map<String, Invoker<RegistryDirectoryTest>> urlInvokerMap = registryDirectory.getUrlInvokerMap();
        replacedertions.replacedertTrue(cachedInvokers == null);
        replacedertions.replacedertEquals(0, urlInvokerMap.size());
        // List<U> urls = mockRegistry.getSubscribedUrls();
        RpcInvocation inv = new RpcInvocation();
        try {
            registryDirectory.list(inv);
            fail();
        } catch (RpcException e) {
            replacedertions.replacedertTrue(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();
        replacedertions.replacedertEquals(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<URL> serviceUrls = new ArrayList<URL>();
        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(Constants.$INVOKE, new Clreplaced[] { String.clreplaced, String[].clreplaced, Object[].clreplaced }, new Object[] { "getXXX1", "", new Object[] {} });
        List<Invoker> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
    // replacedertions.replacedertEquals(
    // serviceURL.setPath(service).addParameters("check", "false", "interface", DemoService.clreplaced.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<URL> serviceUrls = new ArrayList<URL>();
        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(Constants.$INVOKE, new Clreplaced[] { String.clreplaced, String[].clreplaced, Object[].clreplaced }, new Object[] { "getXXX1", new String[] { "Enum" }, new Object[] { Param.MORGAN } });
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
    }

    /**
     * Empty notify cause forbidden, non-empty notify cancels forbidden state
     */
    @Test
    public void testEmptyNotifyCauseForbidden() {
        RegistryDirectory registryDirectory = getRegistryDirectory();
        List invokers = null;
        List<URL> serviceUrls = new ArrayList<URL>();
        registryDirectory.notify(serviceUrls);
        RpcInvocation inv = new RpcInvocation();
        try {
            invokers = registryDirectory.list(inv);
        } catch (RpcException e) {
            replacedertions.replacedertEquals(RpcException.FORBIDDEN_EXCEPTION, e.getCode());
            replacedertions.replacedertEquals(false, 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);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        replacedertions.replacedertEquals(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(Constants.ROUTE_PROTOCOL + "://127.0.0.1:9096/");
        URL routerurl2 = URL.valueOf(Constants.ROUTE_PROTOCOL + "://127.0.0.1:9097/");
        List<URL> serviceUrls = new ArrayList<URL>();
        // without ROUTER_KEY, the first router should not be created.
        serviceUrls.add(routerurl.addParameter(Constants.CATEGORY_KEY, Constants.ROUTERS_CATEGORY).addParameter(Constants.TYPE_KEY, "javascript").addParameter(Constants.ROUTER_KEY, "notsupported").addParameter(Constants.RULE_KEY, "function test1(){}"));
        serviceUrls.add(routerurl2.addParameter(Constants.CATEGORY_KEY, Constants.ROUTERS_CATEGORY).addParameter(Constants.TYPE_KEY, "javascript").addParameter(Constants.ROUTER_KEY, ScriptRouterFactory.NAME).addParameter(Constants.RULE_KEY, "function test1(){}"));
    // FIXME
    /*registryDirectory.notify(serviceUrls);
        RouterChain routerChain = registryDirectory.getRouterChain();
        //default invocation selector
        replacedertions.replacedertEquals(1 + 1, routers.size());
        replacedertions.replacedertTrue(ScriptRouter.clreplaced == routers.get(1).getClreplaced() || ScriptRouter.clreplaced == routers.get(0).getClreplaced());

        registryDirectory.notify(new ArrayList<URL>());
        routers = registryDirectory.getRouters();
        replacedertions.replacedertEquals(1 + 1, routers.size());
        replacedertions.replacedertTrue(ScriptRouter.clreplaced == routers.get(1).getClreplaced() || ScriptRouter.clreplaced == routers.get(0).getClreplaced());

        serviceUrls.clear();
        serviceUrls.add(routerurl.addParameter(Constants.ROUTER_KEY, Constants.ROUTER_TYPE_CLEAR));
        registryDirectory.notify(serviceUrls);
        routers = registryDirectory.getRouters();
        replacedertions.replacedertEquals(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<URL> overrideUrls = new ArrayList<URL>();
        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.
        replacedertions.replacedertEquals(false, registryDirectory.isAvailable());
        // After pushing two provider, the directory state is restored to true
        List<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(SERVICEURL.addParameter("timeout", "1000"));
        serviceUrls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        // Start validation of parameter values
        invocation = new RpcInvocation();
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        replacedertions.replacedertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority");
        replacedertions.replacedertEquals("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<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(SERVICEURL.addParameter("timeout", "1000"));
        serviceUrls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        List<URL> overrideUrls = new ArrayList<URL>();
        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<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        replacedertions.replacedertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority");
        replacedertions.replacedertEquals("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<URL> durls = new ArrayList<URL>();
        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);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        // Start validation of parameter values
        invocation = new RpcInvocation();
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        replacedertions.replacedertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority");
        replacedertions.replacedertEquals("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<URL> durls = new ArrayList<URL>();
        // One is the same, one is different
        durls.add(SERVICEURL.addParameter("timeout", "1"));
        durls.add(SERVICEURL2.addParameter("timeout", "1").addParameter("connections", "5"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        Invoker<?> a1Invoker = invokers.get(0);
        Invoker<?> b1Invoker = invokers.get(1);
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5"));
        registryDirectory.notify(durls);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        Invoker<?> a2Invoker = invokers.get(0);
        Invoker<?> b2Invoker = invokers.get(1);
        // The parameters are different and must be rereferenced.
        replacedertions.replacedertTrue(a1Invoker == a2Invoker, "object should not same");
        // The parameters can not be rereferenced
        replacedertions.replacedertFalse(b1Invoker == b2Invoker, "object should same");
    }

    /**
     * Test override rules for a certain provider
     */
    @Test
    public void testNofityOverrideUrls_Provider() {
        RegistryDirectory registryDirectory = getRegistryDirectory();
        invocation = new RpcInvocation();
        List<URL> durls = new ArrayList<URL>();
        // One is the same, one is different
        durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1").addParameter(Constants.SIDE_KEY, Constants.CONSUMER_SIDE));
        durls.add(SERVICEURL2.setHost("10.20.30.141").addParameter("timeout", "2").addParameter(Constants.SIDE_KEY, Constants.CONSUMER_SIDE));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        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<Invoker<?>> invokers = registryDirectory.list(invocation);
        URL aUrl = invokers.get(0).getUrl();
        URL bUrl = invokers.get(1).getUrl();
        replacedertions.replacedertEquals(aUrl.getHost().equals("10.20.30.140") ? "3" : "4", aUrl.getParameter("timeout"));
        replacedertions.replacedertEquals(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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1"));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://0.0.0.0?timeout=1000"));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://0.0.0.0?timeout=3"));
        durls.add(URL.valueOf("override://0.0.0.0"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        Invoker<?> aInvoker = invokers.get(0);
        // Need to be restored to the original providerUrl
        replacedertions.replacedertEquals("1", 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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1"));
        registryDirectory.notify(durls);
        replacedertions.replacedertEquals(null, registryDirectory.getUrl().getParameter("mock"));
        // override
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://0.0.0.0?timeout=1000&mock=fail"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        Invoker<?> aInvoker = invokers.get(0);
        replacedertions.replacedertEquals("1000", aInvoker.getUrl().getParameter("timeout"));
        replacedertions.replacedertEquals("fail", registryDirectory.getUrl().getParameter("mock"));
        // override clean
        durls = new ArrayList<URL>();
        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
        replacedertions.replacedertEquals("1", aInvoker.getUrl().getParameter("timeout"));
        replacedertions.replacedertEquals(null, registryDirectory.getUrl().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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1"));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        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<Invoker<?>> invokers = registryDirectory.list(invocation);
        Invoker<?> aInvoker = invokers.get(0);
        replacedertions.replacedertEquals("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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140"));
        durls.add(SERVICEURL.setHost("10.20.30.141"));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://0.0.0.0?" + Constants.ENABLED_KEY + "=false"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        // All service providers can not be disabled through override.
        replacedertions.replacedertEquals(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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140"));
        durls.add(SERVICEURL.setHost("10.20.30.141"));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://10.20.30.140:9091?" + Constants.DISABLED_KEY + "=true"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        replacedertions.replacedertEquals("10.20.30.141", invokers.get(0).getUrl().getHost());
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("empty://0.0.0.0?" + Constants.DISABLED_KEY + "=true&" + Constants.CATEGORY_KEY + "=" + Constants.CONFIGURATORS_CATEGORY));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers2 = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140"));
        durls.add(SERVICEURL.setHost("10.20.30.141"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers2 = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers2.size());
        replacedertions.replacedertEquals("10.20.30.140", invokers2.get(0).getUrl().getHost());
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("empty://0.0.0.0?" + Constants.DISABLED_KEY + "=true&" + Constants.CATEGORY_KEY + "=" + Constants.CONFIGURATORS_CATEGORY));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers3 = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140").addParameter(Constants.ENABLED_KEY, "false"));
        durls.add(SERVICEURL.setHost("10.20.30.141"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        replacedertions.replacedertEquals("10.20.30.141", invokers.get(0).getUrl().getHost());
        // Enabled by override rule
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://10.20.30.140:9091?" + Constants.DISABLED_KEY + "=false"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers2 = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers2.size());
    }

    @Test
    public void testNotifyRouterUrls_Clean() {
        if (isScriptUnsupported)
            return;
        RegistryDirectory registryDirectory = getRegistryDirectory();
        URL routerurl = URL.valueOf(Constants.ROUTE_PROTOCOL + "://127.0.0.1:9096/").addParameter(Constants.ROUTER_KEY, "javascript").addParameter(Constants.RULE_KEY, "function test1(){}").addParameter(Constants.ROUTER_KEY, // FIX
        "script");
        // BAD
        List<URL> serviceUrls = new ArrayList<URL>();
        // without ROUTER_KEY, the first router should not be created.
        serviceUrls.add(routerurl);
        registryDirectory.notify(serviceUrls);
    // FIXME
    /* List routers = registryDirectory.getRouters();
        replacedertions.replacedertEquals(1 + 1, routers.size());

        serviceUrls.clear();
        serviceUrls.add(routerurl.addParameter(Constants.ROUTER_KEY, Constants.ROUTER_TYPE_CLEAR));
        registryDirectory.notify(serviceUrls);
        routers = registryDirectory.getRouters();
        replacedertions.replacedertEquals(0 + 1, routers.size());*/
    }

    /**
     * Test mock provider distribution
     */
    @Test
    public void testNotify_MockProviderOnly() {
        RegistryDirectory registryDirectory = getRegistryDirectory();
        List<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1"));
        serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2"));
        serviceUrls.add(SERVICEURL.setProtocol(Constants.MOCK_PROTOCOL));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertEquals(true, registryDirectory.isAvailable());
        invocation = new RpcInvocation();
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        RpcInvocation mockinvocation = new RpcInvocation();
        mockinvocation.setAttachment(Constants.INVOCATION_NEED_MOCK, "true");
        invokers = registryDirectory.list(mockinvocation);
        replacedertions.replacedertEquals(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<URL> serviceUrls = new ArrayList<URL>();
        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<Invoker<DemoService>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(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(Constants.REFER_KEY, "interface=" + service + "&protocol=dubbo");
        RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl);
        List<URL> serviceUrls = new ArrayList<URL>();
        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<Invoker<DemoService>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(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(Constants.REFER_KEY, "interface=" + service + "&protocol=dubbo,injvm");
        RegistryDirectory registryDirectory = getRegistryDirectory(errorPathUrl);
        List<URL> serviceUrls = new ArrayList<URL>();
        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<Invoker<DemoService>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
    }

    @Test
    public void test_Notified_withGroupFilter() {
        URL directoryUrl = noMeaningUrl.addParameterAndEncoded(Constants.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<URL> providers = new ArrayList<>();
        providers.add(provider1);
        providers.add(provider2);
        directory.notify(providers);
        invocation = new RpcInvocation();
        invocation.setMethodName("getXXX");
        List<Invoker<DemoService>> invokers = directory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        replacedertions.replacedertTrue(invokers.get(0) instanceof MockClusterInvoker);
        replacedertions.replacedertTrue(invokers.get(1) instanceof MockClusterInvoker);
        directoryUrl = noMeaningUrl.addParameterAndEncoded(Constants.REFER_KEY, "interface" + service + "&group=group1");
        directory = this.getRegistryDirectory(directoryUrl);
        directory.notify(providers);
        invokers = directory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        replacedertions.replacedertFalse(invokers.get(0) instanceof MockClusterInvoker);
        replacedertions.replacedertFalse(invokers.get(1) instanceof MockClusterInvoker);
    }

    enum Param {

        MORGAN
    }

    private static interface DemoService {
    }

    private static clreplaced 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<URL> 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.");
            }
        }
    }
}

15 Source : ServiceConfig.java
with Apache License 2.0
from boomblog

/**
 * ServiceConfig
 *
 * @export
 */
public clreplaced ServiceConfig<T> extends AbstractServiceConfig {

    private static final long serialVersionUID = 3033787999037024738L;

    /**
     * The {@link Protocol} implementation with adaptive functionality,it will be different in different scenarios.
     * A particular {@link Protocol} implementation is determined by the protocol attribute in the {@link URL}.
     * For example:
     *
     * <li>when the url is registry://224.5.6.7:1234/org.apache.dubbo.registry.RegistryService?application=dubbo-sample,
     * then the protocol is <b>RegistryProtocol</b></li>
     *
     * <li>when the url is dubbo://224.5.6.7:1234/org.apache.dubbo.config.api.DemoService?application=dubbo-sample, then
     * the protocol is <b>DubboProtocol</b></li>
     * <p>
     * Actually,when the {@link ExtensionLoader} init the {@link Protocol} instants,it will automatically wraps two
     * layers, and eventually will get a <b>ProtocolFilterWrapper</b> or <b>ProtocolListenerWrapper</b>
     */
    private static final Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    /**
     * A {@link ProxyFactory} implementation that will generate a exported service proxy,the JavreplacedistProxyFactory is its
     * default implementation
     */
    private static final ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();

    /**
     * A random port cache, the different protocols who has no port specified have different random port
     */
    private static final Map<String, Integer> RANDOM_PORT_MAP = new HashMap<String, Integer>();

    /**
     * A delayed exposure service timer
     */
    private static final ScheduledExecutorService delayExportExecutor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("DubboServiceDelayExporter", true));

    /**
     * The urls of the services exported
     */
    private final List<URL> urls = new ArrayList<URL>();

    /**
     * The exported services
     */
    private final List<Exporter<?>> exporters = new ArrayList<Exporter<?>>();

    /**
     * The interface name of the exported service
     */
    private String interfaceName;

    /**
     * The interface clreplaced of the exported service
     */
    private Clreplaced<?> interfaceClreplaced;

    /**
     * The reference of the interface implementation
     */
    private T ref;

    /**
     * The service name
     */
    private String path;

    /**
     * The method configuration
     */
    private List<MethodConfig> methods;

    /**
     * The provider configuration
     */
    private ProviderConfig provider;

    /**
     * The providerIds
     */
    private String providerIds;

    /**
     * Whether the provider has been exported
     */
    private transient volatile boolean exported;

    /**
     * The flag whether a service has unexported ,if the method unexported is invoked, the value is true
     */
    private transient volatile boolean unexported;

    /**
     * whether it is a GenericService
     */
    private volatile String generic;

    public ServiceConfig() {
    }

    public ServiceConfig(Service service) {
        appendAnnotation(Service.clreplaced, service);
    }

    @Deprecated
    private static List<ProtocolConfig> convertProviderToProtocol(List<ProviderConfig> providers) {
        if (CollectionUtils.isEmpty(providers)) {
            return null;
        }
        List<ProtocolConfig> protocols = new ArrayList<ProtocolConfig>(providers.size());
        for (ProviderConfig provider : providers) {
            protocols.add(convertProviderToProtocol(provider));
        }
        return protocols;
    }

    @Deprecated
    private static List<ProviderConfig> convertProtocolToProvider(List<ProtocolConfig> protocols) {
        if (CollectionUtils.isEmpty(protocols)) {
            return null;
        }
        List<ProviderConfig> providers = new ArrayList<ProviderConfig>(protocols.size());
        for (ProtocolConfig provider : protocols) {
            providers.add(convertProtocolToProvider(provider));
        }
        return providers;
    }

    @Deprecated
    private static ProtocolConfig convertProviderToProtocol(ProviderConfig provider) {
        ProtocolConfig protocol = new ProtocolConfig();
        protocol.setName(provider.getProtocol().getName());
        protocol.setServer(provider.getServer());
        protocol.setClient(provider.getClient());
        protocol.setCodec(provider.getCodec());
        protocol.setHost(provider.getHost());
        protocol.setPort(provider.getPort());
        protocol.setPath(provider.getPath());
        protocol.setPayload(provider.getPayload());
        protocol.setThreads(provider.getThreads());
        protocol.setParameters(provider.getParameters());
        return protocol;
    }

    @Deprecated
    private static ProviderConfig convertProtocolToProvider(ProtocolConfig protocol) {
        ProviderConfig provider = new ProviderConfig();
        provider.setProtocol(protocol);
        provider.setServer(protocol.getServer());
        provider.setClient(protocol.getClient());
        provider.setCodec(protocol.getCodec());
        provider.setHost(protocol.getHost());
        provider.setPort(protocol.getPort());
        provider.setPath(protocol.getPath());
        provider.setPayload(protocol.getPayload());
        provider.setThreads(protocol.getThreads());
        provider.setParameters(protocol.getParameters());
        return provider;
    }

    private static Integer getRandomPort(String protocol) {
        protocol = protocol.toLowerCase();
        return RANDOM_PORT_MAP.getOrDefault(protocol, Integer.MIN_VALUE);
    }

    private static void putRandomPort(String protocol, Integer port) {
        protocol = protocol.toLowerCase();
        if (!RANDOM_PORT_MAP.containsKey(protocol)) {
            RANDOM_PORT_MAP.put(protocol, port);
            logger.warn("Use random available port(" + port + ") for protocol " + protocol);
        }
    }

    public URL toUrl() {
        return urls.isEmpty() ? null : urls.iterator().next();
    }

    public List<URL> toUrls() {
        return urls;
    }

    @Parameter(excluded = true)
    public boolean isExported() {
        return exported;
    }

    @Parameter(excluded = true)
    public boolean isUnexported() {
        return unexported;
    }

    public void checkAndUpdateSubConfigs() {
        checkDefault();
        if (provider != null) {
            inheritIfAbsentFromProvider();
        }
        if (module != null) {
            inheritIfAbsentFromModule();
        }
        if (application != null) {
            inheritIfAbsentFromApplication();
        }
        checkApplication();
        checkRegistry();
        checkProtocol();
        this.refresh();
        checkMetadataReport();
        checkRegistryDataConfig();
        if (StringUtils.isEmpty(interfaceName)) {
            throw new IllegalStateException("<dubbo:service interface=\"\" /> interface not allow null!");
        }
        if (ref instanceof GenericService) {
            interfaceClreplaced = GenericService.clreplaced;
            if (StringUtils.isEmpty(generic)) {
                generic = Boolean.TRUE.toString();
            }
        } else {
            try {
                interfaceClreplaced = Clreplaced.forName(interfaceName, true, Thread.currentThread().getContextClreplacedLoader());
            } catch (ClreplacedNotFoundException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
            checkInterfaceAndMethods(interfaceClreplaced, methods);
            checkRef();
            generic = Boolean.FALSE.toString();
        }
        if (local != null) {
            if ("true".equals(local)) {
                local = interfaceName + "Local";
            }
            Clreplaced<?> localClreplaced;
            try {
                localClreplaced = ClreplacedHelper.forNameWithThreadContextClreplacedLoader(local);
            } catch (ClreplacedNotFoundException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
            if (!interfaceClreplaced.isreplacedignableFrom(localClreplaced)) {
                throw new IllegalStateException("The local implementation clreplaced " + localClreplaced.getName() + " not implement interface " + interfaceName);
            }
        }
        if (stub != null) {
            if ("true".equals(stub)) {
                stub = interfaceName + "Stub";
            }
            Clreplaced<?> stubClreplaced;
            try {
                stubClreplaced = ClreplacedHelper.forNameWithThreadContextClreplacedLoader(stub);
            } catch (ClreplacedNotFoundException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
            if (!interfaceClreplaced.isreplacedignableFrom(stubClreplaced)) {
                throw new IllegalStateException("The stub implementation clreplaced " + stubClreplaced.getName() + " not implement interface " + interfaceName);
            }
        }
        checkStubAndLocal(interfaceClreplaced);
        checkMock(interfaceClreplaced);
    }

    public synchronized void export() {
        // 加载并更新配置信息到Bean对象中,并检查
        checkAndUpdateSubConfigs();
        if (provider != null) {
            if (export == null) {
                export = provider.getExport();
            }
            if (delay == null) {
                delay = provider.getDelay();
            }
        }
        if (export != null && !export) {
            return;
        }
        if (delay != null && delay > 0) {
            delayExportExecutor.schedule(this::doExport, delay, TimeUnit.MILLISECONDS);
        } else {
            doExport();
        }
    }

    protected synchronized void doExport() {
        if (unexported) {
            throw new IllegalStateException("The service " + interfaceClreplaced.getName() + " has already unexported!");
        }
        if (exported) {
            return;
        }
        exported = true;
        if (StringUtils.isEmpty(path)) {
            path = interfaceName;
        }
        // 服务名= group:servicename:version
        ProviderModel providerModel = new ProviderModel(getUniqueServiceName(), ref, interfaceClreplaced);
        // ApplicationModel当前这个应用有哪些服务提供,消费了哪些服务
        ApplicationModel.initProviderModel(getUniqueServiceName(), providerModel);
        doExportUrls();
    }

    private void checkRef() {
        // reference should not be null, and is the implementation of the given interface
        if (ref == null) {
            throw new IllegalStateException("ref not allow null!");
        }
        if (!interfaceClreplaced.isInstance(ref)) {
            throw new IllegalStateException("The clreplaced " + ref.getClreplaced().getName() + " unimplemented interface " + interfaceClreplaced + "!");
        }
    }

    public synchronized void unexport() {
        if (!exported) {
            return;
        }
        if (unexported) {
            return;
        }
        if (!exporters.isEmpty()) {
            for (Exporter<?> exporter : exporters) {
                try {
                    exporter.unexport();
                } catch (Throwable t) {
                    logger.warn("Unexpected error occured when unexport " + exporter, t);
                }
            }
            exporters.clear();
        }
        unexported = true;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void doExportUrls() {
        // 将服务的不同协议注册到各个注册中心上
        List<URL> registryURLs = loadRegistries(true);
        for (ProtocolConfig protocolConfig : protocols) {
            doExportUrlsFor1Protocol(protocolConfig, registryURLs);
        }
    }

    private void doExportUrlsFor1Protocol(ProtocolConfig protocolConfig, List<URL> registryURLs) {
        String name = protocolConfig.getName();
        if (StringUtils.isEmpty(name)) {
            name = Constants.DUBBO;
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put(Constants.SIDE_KEY, Constants.PROVIDER_SIDE);
        appendRuntimeParameters(map);
        // 不同层级的配置覆盖...
        appendParameters(map, application);
        appendParameters(map, module);
        appendParameters(map, provider, Constants.DEFAULT_KEY);
        appendParameters(map, protocolConfig);
        appendParameters(map, this);
        if (CollectionUtils.isNotEmpty(methods)) {
            for (MethodConfig method : methods) {
                appendParameters(map, method, method.getName());
                String retryKey = method.getName() + ".retry";
                if (map.containsKey(retryKey)) {
                    String retryValue = map.remove(retryKey);
                    if ("false".equals(retryValue)) {
                        map.put(method.getName() + ".retries", "0");
                    }
                }
                List<ArgumentConfig> arguments = method.getArguments();
                if (CollectionUtils.isNotEmpty(arguments)) {
                    for (ArgumentConfig argument : arguments) {
                        // convert argument type
                        if (argument.getType() != null && argument.getType().length() > 0) {
                            Method[] methods = interfaceClreplaced.getMethods();
                            // visit all methods
                            if (methods != null && methods.length > 0) {
                                for (int i = 0; i < methods.length; i++) {
                                    String methodName = methods[i].getName();
                                    // target the method, and get its signature
                                    if (methodName.equals(method.getName())) {
                                        Clreplaced<?>[] argtypes = methods[i].getParameterTypes();
                                        // one callback in the method
                                        if (argument.getIndex() != -1) {
                                            if (argtypes[argument.getIndex()].getName().equals(argument.getType())) {
                                                appendParameters(map, argument, method.getName() + "." + argument.getIndex());
                                            } else {
                                                throw new IllegalArgumentException("Argument config error : the index attribute and type attribute not match :index :" + argument.getIndex() + ", type:" + argument.getType());
                                            }
                                        } else {
                                            // multiple callbacks in the method
                                            for (int j = 0; j < argtypes.length; j++) {
                                                Clreplaced<?> argclazz = argtypes[j];
                                                if (argclazz.getName().equals(argument.getType())) {
                                                    appendParameters(map, argument, method.getName() + "." + j);
                                                    if (argument.getIndex() != -1 && argument.getIndex() != j) {
                                                        throw new IllegalArgumentException("Argument config error : the index attribute and type attribute not match :index :" + argument.getIndex() + ", type:" + argument.getType());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else if (argument.getIndex() != -1) {
                            appendParameters(map, argument, method.getName() + "." + argument.getIndex());
                        } else {
                            throw new IllegalArgumentException("Argument config must set index or type attribute.eg: <dubbo:argument index='0' .../> or <dubbo:argument type=xxx .../>");
                        }
                    }
                }
            }
        // end of methods for
        }
        if (ProtocolUtils.isGeneric(generic)) {
            map.put(Constants.GENERIC_KEY, generic);
            map.put(Constants.METHODS_KEY, Constants.ANY_VALUE);
        } else {
            String revision = Version.getVersion(interfaceClreplaced, version);
            if (revision != null && revision.length() > 0) {
                map.put("revision", revision);
            }
            String[] methods = Wrapper.getWrapper(interfaceClreplaced).getMethodNames();
            if (methods.length == 0) {
                logger.warn("No method found in service interface " + interfaceClreplaced.getName());
                map.put(Constants.METHODS_KEY, Constants.ANY_VALUE);
            } else {
                map.put(Constants.METHODS_KEY, StringUtils.join(new HashSet<String>(Arrays.asList(methods)), ","));
            }
        }
        if (!ConfigUtils.isEmpty(token)) {
            if (ConfigUtils.isDefault(token)) {
                map.put(Constants.TOKEN_KEY, UUID.randomUUID().toString());
            } else {
                map.put(Constants.TOKEN_KEY, token);
            }
        }
        if (Constants.LOCAL_PROTOCOL.equals(protocolConfig.getName())) {
            protocolConfig.setRegister(false);
            map.put("notify", "false");
        }
        // export service
        String contextPath = protocolConfig.getContextpath();
        if (StringUtils.isEmpty(contextPath) && provider != null) {
            contextPath = provider.getContextpath();
        }
        String host = this.findConfigedHosts(protocolConfig, registryURLs, map);
        Integer port = this.findConfigedPorts(protocolConfig, name, map);
        // 代表一个服务
        URL url = new URL(name, host, port, (StringUtils.isEmpty(contextPath) ? "" : contextPath + "/") + path, map);
        if (ExtensionLoader.getExtensionLoader(ConfiguratorFactory.clreplaced).hasExtension(url.getProtocol())) {
            url = ExtensionLoader.getExtensionLoader(ConfiguratorFactory.clreplaced).getExtension(url.getProtocol()).getConfigurator(url).configure(url);
        }
        String scope = url.getParameter(Constants.SCOPE_KEY);
        // don't export when none is configured
        if (!Constants.SCOPE_NONE.equalsIgnoreCase(scope)) {
            // export to local if the config is not remote (export to remote only when config is remote)
            if (!Constants.SCOPE_REMOTE.equalsIgnoreCase(scope)) {
                exportLocal(url);
            }
            // export to remote if the config is not local (export to local only when config is local)
            if (!Constants.SCOPE_LOCAL.equalsIgnoreCase(scope)) {
                if (logger.isInfoEnabled()) {
                    logger.info("Export dubbo service " + interfaceClreplaced.getName() + " to url " + url);
                }
                if (CollectionUtils.isNotEmpty(registryURLs)) {
                    for (URL registryURL : registryURLs) {
                        // 注册中心的地址
                        url = url.addParameterIfAbsent(Constants.DYNAMIC_KEY, registryURL.getParameter(Constants.DYNAMIC_KEY));
                        URL monitorUrl = loadMonitor(registryURL);
                        if (monitorUrl != null) {
                            url = url.addParameterAndEncoded(Constants.MONITOR_KEY, monitorUrl.toFullString());
                        }
                        if (logger.isInfoEnabled()) {
                            logger.info("Register dubbo service " + interfaceClreplaced.getName() + " url " + url + " to registry " + registryURL);
                        }
                        // For providers, this is used to enable custom proxy to generate invoker
                        String proxy = url.getParameter(Constants.PROXY_KEY);
                        if (StringUtils.isNotEmpty(proxy)) {
                            registryURL = registryURL.addParameter(Constants.PROXY_KEY, proxy);
                        }
                        Invoker<?> invoker = proxyFactory.getInvoker(ref, (Clreplaced) interfaceClreplaced, registryURL.addParameterAndEncoded(Constants.EXPORT_KEY, url.toFullString()));
                        DelegateProviderMetaDataInvoker wrapperInvoker = new DelegateProviderMetaDataInvoker(invoker, this);
                        // Dubbo是协议,注册是协议,配置覆盖也是协议
                        // 入口,服务注册以及服务暴露
                        Exporter<?> exporter = protocol.export(wrapperInvoker);
                        exporters.add(exporter);
                    }
                } else {
                    Invoker<?> invoker = proxyFactory.getInvoker(ref, (Clreplaced) interfaceClreplaced, url);
                    DelegateProviderMetaDataInvoker wrapperInvoker = new DelegateProviderMetaDataInvoker(invoker, this);
                    Exporter<?> exporter = protocol.export(wrapperInvoker);
                    exporters.add(exporter);
                }
                /**
                 * @since 2.7.0
                 * ServiceData Store
                 */
                MetadataReportService metadataReportService = null;
                if ((metadataReportService = getMetadataReportService()) != null) {
                    metadataReportService.publishProvider(url);
                }
            }
        }
        this.urls.add(url);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void exportLocal(URL url) {
        if (!Constants.LOCAL_PROTOCOL.equalsIgnoreCase(url.getProtocol())) {
            URL local = URL.valueOf(url.toFullString()).setProtocol(Constants.LOCAL_PROTOCOL).setHost(LOCALHOST_VALUE).setPort(0);
            Exporter<?> exporter = protocol.export(proxyFactory.getInvoker(ref, (Clreplaced) interfaceClreplaced, local));
            exporters.add(exporter);
            logger.info("Export dubbo service " + interfaceClreplaced.getName() + " to local registry");
        }
    }

    private void inheritIfAbsentFromProvider() {
        if (application == null) {
            application = provider.getApplication();
        }
        if (module == null) {
            module = provider.getModule();
        }
        if (registries == null) {
            registries = provider.getRegistries();
        }
        if (monitor == null) {
            monitor = provider.getMonitor();
        }
        if (protocols == null) {
            protocols = provider.getProtocols();
        }
    }

    private void inheritIfAbsentFromModule() {
        if (registries == null) {
            registries = module.getRegistries();
        }
        if (monitor == null) {
            monitor = module.getMonitor();
        }
    }

    private void inheritIfAbsentFromApplication() {
        if (registries == null) {
            registries = application.getRegistries();
        }
        if (monitor == null) {
            monitor = application.getMonitor();
        }
    }

    protected Clreplaced getServiceClreplaced(T ref) {
        return ref.getClreplaced();
    }

    /**
     * Register & bind IP address for service provider, can be configured separately.
     * Configuration priority: environment variables -> java system properties -> host property in config file ->
     * /etc/hosts -> default network address -> first available network address
     *
     * @param protocolConfig
     * @param registryURLs
     * @param map
     * @return
     */
    private String findConfigedHosts(ProtocolConfig protocolConfig, List<URL> registryURLs, Map<String, String> map) {
        boolean anyhost = false;
        String hostToBind = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_BIND);
        if (hostToBind != null && hostToBind.length() > 0 && isInvalidLocalHost(hostToBind)) {
            throw new IllegalArgumentException("Specified invalid bind ip from property:" + Constants.DUBBO_IP_TO_BIND + ", value:" + hostToBind);
        }
        // if bind ip is not found in environment, keep looking up
        if (StringUtils.isEmpty(hostToBind)) {
            hostToBind = protocolConfig.getHost();
            if (provider != null && StringUtils.isEmpty(hostToBind)) {
                hostToBind = provider.getHost();
            }
            if (isInvalidLocalHost(hostToBind)) {
                anyhost = true;
                try {
                    hostToBind = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException e) {
                    logger.warn(e.getMessage(), e);
                }
                if (isInvalidLocalHost(hostToBind)) {
                    if (CollectionUtils.isNotEmpty(registryURLs)) {
                        for (URL registryURL : registryURLs) {
                            if (Constants.MULTICAST.equalsIgnoreCase(registryURL.getParameter("registry"))) {
                                // skip multicast registry since we cannot connect to it via Socket
                                continue;
                            }
                            try {
                                Socket socket = new Socket();
                                try {
                                    SocketAddress addr = new InetSocketAddress(registryURL.getHost(), registryURL.getPort());
                                    socket.connect(addr, 1000);
                                    hostToBind = socket.getLocalAddress().getHostAddress();
                                    break;
                                } finally {
                                    try {
                                        socket.close();
                                    } catch (Throwable e) {
                                    }
                                }
                            } catch (Exception e) {
                                logger.warn(e.getMessage(), e);
                            }
                        }
                    }
                    if (isInvalidLocalHost(hostToBind)) {
                        hostToBind = getLocalHost();
                    }
                }
            }
        }
        map.put(Constants.BIND_IP_KEY, hostToBind);
        // registry ip is not used for bind ip by default
        String hostToRegistry = getValueFromConfig(protocolConfig, Constants.DUBBO_IP_TO_REGISTRY);
        if (hostToRegistry != null && hostToRegistry.length() > 0 && isInvalidLocalHost(hostToRegistry)) {
            throw new IllegalArgumentException("Specified invalid registry ip from property:" + Constants.DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry);
        } else if (StringUtils.isEmpty(hostToRegistry)) {
            // bind ip is used as registry ip by default
            hostToRegistry = hostToBind;
        }
        map.put(Constants.ANYHOST_KEY, String.valueOf(anyhost));
        return hostToRegistry;
    }

    /**
     * Register port and bind port for the provider, can be configured separately
     * Configuration priority: environment variable -> java system properties -> port property in protocol config file
     * -> protocol default port
     *
     * @param protocolConfig
     * @param name
     * @return
     */
    private Integer findConfigedPorts(ProtocolConfig protocolConfig, String name, Map<String, String> map) {
        Integer portToBind = null;
        // parse bind port from environment
        String port = getValueFromConfig(protocolConfig, Constants.DUBBO_PORT_TO_BIND);
        portToBind = parsePort(port);
        // if there's no bind port found from environment, keep looking up.
        if (portToBind == null) {
            portToBind = protocolConfig.getPort();
            if (provider != null && (portToBind == null || portToBind == 0)) {
                portToBind = provider.getPort();
            }
            final int defaultPort = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getExtension(name).getDefaultPort();
            if (portToBind == null || portToBind == 0) {
                portToBind = defaultPort;
            }
            if (portToBind == null || portToBind <= 0) {
                portToBind = getRandomPort(name);
                if (portToBind == null || portToBind < 0) {
                    portToBind = getAvailablePort(defaultPort);
                    putRandomPort(name, portToBind);
                }
            }
        }
        // save bind port, used as url's key later
        map.put(Constants.BIND_PORT_KEY, String.valueOf(portToBind));
        // registry port, not used as bind port by default
        String portToRegistryStr = getValueFromConfig(protocolConfig, Constants.DUBBO_PORT_TO_REGISTRY);
        Integer portToRegistry = parsePort(portToRegistryStr);
        if (portToRegistry == null) {
            portToRegistry = portToBind;
        }
        return portToRegistry;
    }

    private Integer parsePort(String configPort) {
        Integer port = null;
        if (configPort != null && configPort.length() > 0) {
            try {
                Integer intPort = Integer.parseInt(configPort);
                if (isInvalidPort(intPort)) {
                    throw new IllegalArgumentException("Specified invalid port from env value:" + configPort);
                }
                port = intPort;
            } catch (Exception e) {
                throw new IllegalArgumentException("Specified invalid port from env value:" + configPort);
            }
        }
        return port;
    }

    private String getValueFromConfig(ProtocolConfig protocolConfig, String key) {
        String protocolPrefix = protocolConfig.getName().toUpperCase() + "_";
        String port = ConfigUtils.getSystemProperty(protocolPrefix + key);
        if (StringUtils.isEmpty(port)) {
            port = ConfigUtils.getSystemProperty(key);
        }
        return port;
    }

    private void checkDefault() {
        if (provider == null) {
            provider = new ProviderConfig();
        }
        // 根据配置刷新provider
        provider.refresh();
    }

    private void checkProtocol() {
        if (CollectionUtils.isEmpty(protocols) && provider != null) {
            setProtocols(provider.getProtocols());
        }
        convertProtocolIdsToProtocols();
        for (ProtocolConfig protocolConfig : protocols) {
            if (StringUtils.isEmpty(protocolConfig.getName())) {
                protocolConfig.setName(Constants.DUBBO_VERSION_KEY);
            }
            protocolConfig.refresh();
            if (StringUtils.isNotEmpty(protocolConfig.getId())) {
                protocolConfig.setPrefix("dubbo.protocols.");
                protocolConfig.refresh();
            }
        }
    }

    private void convertProtocolIdsToProtocols() {
        if (StringUtils.isEmpty(protocolIds) && CollectionUtils.isEmpty(protocols)) {
            List<String> configedProtocols = new ArrayList<>();
            configedProtocols.addAll(getSubProperties(Environment.getInstance().getExternalConfigurationMap(), Constants.PROTOCOLS_SUFFIX));
            configedProtocols.addAll(getSubProperties(Environment.getInstance().getAppExternalConfigurationMap(), Constants.PROTOCOLS_SUFFIX));
            protocolIds = String.join(",", configedProtocols);
        }
        if (StringUtils.isEmpty(protocolIds)) {
            if (CollectionUtils.isEmpty(protocols)) {
                protocols = new ArrayList<>();
                protocols.add(new ProtocolConfig());
            }
        } else {
            String[] arr = Constants.COMMA_SPLIT_PATTERN.split(protocolIds);
            if (CollectionUtils.isEmpty(protocols)) {
                protocols = new ArrayList<>();
            }
            Arrays.stream(arr).forEach(id -> {
                if (protocols.stream().noneMatch(prot -> prot.getId().equals(id))) {
                    ProtocolConfig protocolConfig = new ProtocolConfig();
                    protocolConfig.setId(id);
                    protocols.add(protocolConfig);
                }
            });
            if (protocols.size() > arr.length) {
                throw new IllegalStateException("Too much protocols found, the protocols comply to this service are :" + protocolIds + " but got " + protocols.size() + " registries!");
            }
        }
    }

    public Clreplaced<?> getInterfaceClreplaced() {
        if (interfaceClreplaced != null) {
            return interfaceClreplaced;
        }
        if (ref instanceof GenericService) {
            return GenericService.clreplaced;
        }
        try {
            if (interfaceName != null && interfaceName.length() > 0) {
                this.interfaceClreplaced = Clreplaced.forName(interfaceName, true, Thread.currentThread().getContextClreplacedLoader());
            }
        } catch (ClreplacedNotFoundException t) {
            throw new IllegalStateException(t.getMessage(), t);
        }
        return interfaceClreplaced;
    }

    /**
     * @param interfaceClreplaced
     * @see #setInterface(Clreplaced)
     * @deprecated
     */
    public void setInterfaceClreplaced(Clreplaced<?> interfaceClreplaced) {
        setInterface(interfaceClreplaced);
    }

    public String getInterface() {
        return interfaceName;
    }

    public void setInterface(Clreplaced<?> interfaceClreplaced) {
        if (interfaceClreplaced != null && !interfaceClreplaced.isInterface()) {
            throw new IllegalStateException("The interface clreplaced " + interfaceClreplaced + " is not a interface!");
        }
        this.interfaceClreplaced = interfaceClreplaced;
        setInterface(interfaceClreplaced == null ? null : interfaceClreplaced.getName());
    }

    public void setInterface(String interfaceName) {
        this.interfaceName = interfaceName;
        if (StringUtils.isEmpty(id)) {
            id = interfaceName;
        }
    }

    public T getRef() {
        return ref;
    }

    public void setRef(T ref) {
        this.ref = ref;
    }

    @Parameter(excluded = true)
    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        checkPathName(Constants.PATH_KEY, path);
        this.path = path;
    }

    public List<MethodConfig> getMethods() {
        return methods;
    }

    // ======== Deprecated ========
    @SuppressWarnings("unchecked")
    public void setMethods(List<? extends MethodConfig> methods) {
        this.methods = (List<MethodConfig>) methods;
    }

    public ProviderConfig getProvider() {
        return provider;
    }

    public void setProvider(ProviderConfig provider) {
        this.provider = provider;
    }

    @Parameter(excluded = true)
    public String getProviderIds() {
        return providerIds;
    }

    public void setProviderIds(String providerIds) {
        this.providerIds = providerIds;
    }

    public String getGeneric() {
        return generic;
    }

    public void setGeneric(String generic) {
        if (StringUtils.isEmpty(generic)) {
            return;
        }
        if (ProtocolUtils.isGeneric(generic)) {
            this.generic = generic;
        } else {
            throw new IllegalArgumentException("Unsupported generic type " + generic);
        }
    }

    @Override
    public void setMock(Boolean mock) {
        throw new IllegalArgumentException("mock doesn't support on provider side");
    }

    @Override
    public void setMock(String mock) {
        throw new IllegalArgumentException("mock doesn't support on provider side");
    }

    public List<URL> getExportedUrls() {
        return urls;
    }

    /**
     * @deprecated Replace to getProtocols()
     */
    @Deprecated
    public List<ProviderConfig> getProviders() {
        return convertProtocolToProvider(protocols);
    }

    /**
     * @deprecated Replace to setProtocols()
     */
    @Deprecated
    public void setProviders(List<ProviderConfig> providers) {
        this.protocols = convertProviderToProtocol(providers);
    }

    @Parameter(excluded = true)
    public String getUniqueServiceName() {
        StringBuilder buf = new StringBuilder();
        if (group != null && group.length() > 0) {
            buf.append(group).append("/");
        }
        buf.append(StringUtils.isNotEmpty(path) ? path : interfaceName);
        if (version != null && version.length() > 0) {
            buf.append(":").append(version);
        }
        return buf.toString();
    }

    @Override
    @Parameter(excluded = true)
    public String getPrefix() {
        return Constants.DUBBO + ".service." + interfaceName;
    }
}

15 Source : RegistryProtocolTest.java
with Apache License 2.0
from apache

@Test
public void testExportUrlNull() {
    replacedertions.replacedertThrows(IllegalArgumentException.clreplaced, () -> {
        RegistryProtocol registryProtocol = getRegistryProtocol();
        registryProtocol.setCluster(new FailfastCluster());
        Protocol dubboProtocol = DubboProtocol.getDubboProtocol();
        registryProtocol.setProtocol(dubboProtocol);
        Invoker<DemoService> invoker = new DubboInvoker<DemoService>(DemoService.clreplaced, registryUrl, new ExchangeClient[] { new MockedClient("10.20.20.20", 2222, true) });
        registryProtocol.export(invoker);
    });
}

15 Source : RegistryDirectoryTest.java
with Apache License 2.0
from apache

@SuppressWarnings({ "rawtypes", "unchecked" })
public clreplaced RegistryDirectoryTest {

    private static boolean isScriptUnsupported = new ScriptEngineManager().getEngineByName("javascript") == null;

    RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.clreplaced).getAdaptiveExtension();

    Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();

    String service = DemoService.clreplaced.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.clreplaced);

    @BeforeEach
    public void setUp() {
        ApplicationModel.setApplication("RegistryDirectoryTest");
    }

    private RegistryDirectory getRegistryDirectory(URL url) {
        RegistryDirectory registryDirectory = new RegistryDirectory(URL.clreplaced, url);
        registryDirectory.setProtocol(protocol);
        registryDirectory.setRegistry(registry);
        registryDirectory.setRouterChain(RouterChain.buildChain(url));
        registryDirectory.subscribe(url);
        // asert empty
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(0, invokers.size());
        replacedertions.replacedertFalse(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.clreplaced, 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.getClreplaced().getDeclaredField("queryMap");
        field.setAccessible(true);
        Map<String, String> queryMap = (Map<String, String>) field.get(reg);
        replacedertions.replacedertEquals("bar", queryMap.get("foo"));
        replacedertions.replacedertEquals(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);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        replacedertions.replacedertTrue(LogUtil.checkNoError(), "notify no invoker urls ,should not error");
        LogUtil.stop();
        test_Notified2invokers(registryDirectory);
    }

    @Test
    public void testNotified_WithError() {
        RegistryDirectory registryDirectory = getRegistryDirectory();
        List<URL> serviceUrls = new ArrayList<URL>();
        // ignore error log
        URL badurl = URL.valueOf("notsupported://127.0.0.1/" + service);
        serviceUrls.add(badurl);
        serviceUrls.add(SERVICEURL);
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
    }

    @Test
    public void testNotified_WithDuplicateUrls() {
        List<URL> serviceUrls = new ArrayList<URL>();
        // ignore error log
        serviceUrls.add(SERVICEURL);
        serviceUrls.add(SERVICEURL);
        RegistryDirectory registryDirectory = getRegistryDirectory();
        registryDirectory.notify(serviceUrls);
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
    }

    // forbid
    private void testforbid(RegistryDirectory registryDirectory) {
        invocation = new RpcInvocation();
        List<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(new URL(EMPTY_PROTOCOL, ANYHOST_VALUE, 0, service, CATEGORY_KEY, PROVIDERS_CATEGORY));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertFalse(registryDirectory.isAvailable(), "invokers size=0 ,then the registry directory is not available");
        try {
            registryDirectory.list(invocation);
            fail("forbid must throw RpcException");
        } catch (RpcException e) {
            replacedertions.replacedertEquals(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<URL> serviceUrls = new ArrayList<URL>();
        URL Dubbo1URL = URL.valueOf("dubbo://127.0.0.1:9098?lazy=true");
        serviceUrls.add(Dubbo1URL.addParameter("methods", "getXXX"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        invocation = new RpcInvocation();
        List<Invoker<DemoService>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        invocation.setMethodName("getXXX");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        replacedertions.replacedertEquals(DemoService.clreplaced.getName(), invokers.get(0).getUrl().getPath());
    }

    // notify one invoker
    private void test_Notified_only_routers(RegistryDirectory registryDirectory) {
        List<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(URL.valueOf("empty://127.0.0.1/?category=routers"));
        registryDirectory.notify(serviceUrls);
    }

    // notify one invoker
    private void test_Notified1invokers(RegistryDirectory registryDirectory) {
        List<URL> serviceUrls = new ArrayList<URL>();
        // .addParameter("refer.autodestroy", "true")
        serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1").addParameter(APPLICATION_KEY, "mockApplicationName"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        invocation = new RpcInvocation();
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        invocation.setMethodName("getXXX");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        invocation.setMethodName("getXXX1");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        invocation.setMethodName("getXXX2");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
    }

    // 2 invokers===================================
    private void test_Notified2invokers(RegistryDirectory registryDirectory) {
        List<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1"));
        serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2"));
        serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        invocation = new RpcInvocation();
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        invocation.setMethodName("getXXX");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        invocation.setMethodName("getXXX1");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
    }

    // 3 invoker notifications===================================
    private void test_Notified3invokers(RegistryDirectory registryDirectory) {
        List<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1"));
        serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2"));
        serviceUrls.add(SERVICEURL3.addParameter("methods", "getXXX1,getXXX2,getXXX3"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        invocation = new RpcInvocation();
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(3, invokers.size());
        invocation.setMethodName("getXXX");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(3, invokers.size());
        invocation.setMethodName("getXXX1");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(3, invokers.size());
        invocation.setMethodName("getXXX2");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(3, invokers.size());
        invocation.setMethodName("getXXX3");
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(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<RegistryDirectoryTest> registryDirectory2 = new RegistryDirectory(RegistryDirectoryTest.clreplaced, regurl);
        registryDirectory2.setProtocol(protocol);
        List<URL> serviceUrls = new ArrayList<URL>();
        // 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();
            replacedertions.replacedertNull(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();
            replacedertions.replacedertEquals("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();
            replacedertions.replacedertEquals("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();
            replacedertions.replacedertFalse(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();
            replacedertions.replacedertEquals(LeastActiveLoadBalance.NAME, url.getMethodParameter("get", LOADBALANCE_KEY));
        }
        // test geturl
        {
            replacedertions.replacedertNull(registryDirectory2.getUrl().getParameter("mock"));
            serviceUrls.clear();
            serviceUrls.add(SERVICEURL.addParameter(MOCK_KEY, "true"));
            registryDirectory2.notify(serviceUrls);
            replacedertions.replacedertEquals("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<URL> serviceUrls = new ArrayList<URL>();
        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<Invoker> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        replacedertions.replacedertTrue(invokers.get(0).isAvailable());
        registryDirectory.destroy();
        replacedertions.replacedertFalse(registryDirectory.isAvailable());
        replacedertions.replacedertFalse(invokers.get(0).isAvailable());
        registryDirectory.destroy();
        List<Invoker<RegistryDirectoryTest>> cachedInvokers = registryDirectory.getInvokers();
        Map<String, Invoker<RegistryDirectoryTest>> urlInvokerMap = registryDirectory.getUrlInvokerMap();
        replacedertions.replacedertNull(cachedInvokers);
        replacedertions.replacedertEquals(0, urlInvokerMap.size());
        // List<U> urls = mockRegistry.getSubscribedUrls();
        RpcInvocation inv = new RpcInvocation();
        try {
            registryDirectory.list(inv);
            fail();
        } catch (RpcException e) {
            replacedertions.replacedertTrue(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();
        replacedertions.replacedertEquals(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<URL> serviceUrls = new ArrayList<URL>();
        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.clreplaced.getName(), new Clreplaced[] { String.clreplaced, String[].clreplaced, Object[].clreplaced }, new Object[] { "getXXX1", "", new Object[] {} });
        List<Invoker> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
    // replacedertions.replacedertEquals(
    // serviceURL.setPath(service).addParameters("check", "false", "interface", DemoService.clreplaced.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<URL> serviceUrls = new ArrayList<URL>();
        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.clreplaced.getName(), new Clreplaced[] { String.clreplaced, String[].clreplaced, Object[].clreplaced }, new Object[] { "getXXX1", new String[] { "Enum" }, new Object[] { Param.MORGAN } });
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
    }

    /**
     * Empty notify cause forbidden, non-empty notify cancels forbidden state
     */
    @Test
    public void testEmptyNotifyCauseForbidden() {
        RegistryDirectory registryDirectory = getRegistryDirectory();
        List invokers = null;
        List<URL> serviceUrls = new ArrayList<URL>();
        registryDirectory.notify(serviceUrls);
        RpcInvocation inv = new RpcInvocation();
        try {
            invokers = registryDirectory.list(inv);
        } catch (RpcException e) {
            replacedertions.replacedertEquals(RpcException.FORBIDDEN_EXCEPTION, e.getCode());
            replacedertions.replacedertFalse(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);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        replacedertions.replacedertEquals(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<URL> serviceUrls = new ArrayList<URL>();
        // 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
        replacedertions.replacedertEquals(1 + 1, routers.size());
        replacedertions.replacedertTrue(ScriptRouter.clreplaced == routers.get(1).getClreplaced() || ScriptRouter.clreplaced == routers.get(0).getClreplaced());

        registryDirectory.notify(new ArrayList<URL>());
        routers = registryDirectory.getRouters();
        replacedertions.replacedertEquals(1 + 1, routers.size());
        replacedertions.replacedertTrue(ScriptRouter.clreplaced == routers.get(1).getClreplaced() || ScriptRouter.clreplaced == routers.get(0).getClreplaced());

        serviceUrls.clear();
        serviceUrls.add(routerurl.addParameter(Constants.ROUTER_KEY, Constants.ROUTER_TYPE_CLEAR));
        registryDirectory.notify(serviceUrls);
        routers = registryDirectory.getRouters();
        replacedertions.replacedertEquals(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<URL> overrideUrls = new ArrayList<URL>();
        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.
        replacedertions.replacedertFalse(registryDirectory.isAvailable());
        // After pushing two provider, the directory state is restored to true
        List<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(SERVICEURL.addParameter("timeout", "1000"));
        serviceUrls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        // Start validation of parameter values
        invocation = new RpcInvocation();
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        replacedertions.replacedertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority");
        replacedertions.replacedertEquals("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<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(SERVICEURL.addParameter("timeout", "1000"));
        serviceUrls.add(SERVICEURL2.addParameter("timeout", "1000").addParameter("connections", "10"));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        List<URL> overrideUrls = new ArrayList<URL>();
        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<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        replacedertions.replacedertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority");
        replacedertions.replacedertEquals("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<URL> durls = new ArrayList<URL>();
        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);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        // Start validation of parameter values
        invocation = new RpcInvocation();
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        replacedertions.replacedertEquals("1", invokers.get(0).getUrl().getParameter("timeout"), "override rute must be first priority");
        replacedertions.replacedertEquals("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<URL> durls = new ArrayList<URL>();
        // One is the same, one is different
        durls.add(SERVICEURL.addParameter("timeout", "1"));
        durls.add(SERVICEURL2.addParameter("timeout", "1").addParameter("connections", "5"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        Map<String, Invoker<?>> 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<URL>();
        durls.add(URL.valueOf("override://0.0.0.0?timeout=1&connections=5"));
        registryDirectory.notify(durls);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        Map<String, Invoker<?>> 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.
        replacedertions.replacedertNotSame(map.get(SERVICEURL.getAddress()), map2.get(SERVICEURL.getAddress()), "object should not same");
        // The parameters can not be rereferenced
        replacedertions.replacedertSame(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<URL> durls = new ArrayList<URL>();
        // One is the same, one is different
        durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1").addParameter(SIDE_KEY, CONSUMER_SIDE));
        durls.add(SERVICEURL2.setHost("10.20.30.141").addParameter("timeout", "2").addParameter(SIDE_KEY, CONSUMER_SIDE));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        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<Invoker<?>> invokers = registryDirectory.list(invocation);
        URL aUrl = invokers.get(0).getUrl();
        URL bUrl = invokers.get(1).getUrl();
        replacedertions.replacedertEquals(aUrl.getHost().equals("10.20.30.140") ? "3" : "4", aUrl.getParameter("timeout"));
        replacedertions.replacedertEquals(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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1"));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://0.0.0.0?timeout=1000"));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://0.0.0.0?timeout=3"));
        durls.add(URL.valueOf("override://0.0.0.0"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        Invoker<?> aInvoker = invokers.get(0);
        // Need to be restored to the original providerUrl
        replacedertions.replacedertEquals("1", 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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1"));
        registryDirectory.notify(durls);
        replacedertions.replacedertNull(registryDirectory.getConsumerUrl().getParameter("mock"));
        // override
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://0.0.0.0?timeout=1000&mock=fail"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        Invoker<?> aInvoker = invokers.get(0);
        replacedertions.replacedertEquals("1000", aInvoker.getUrl().getParameter("timeout"));
        replacedertions.replacedertEquals("fail", registryDirectory.getConsumerUrl().getParameter("mock"));
        // override clean
        durls = new ArrayList<URL>();
        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
        replacedertions.replacedertEquals("1", aInvoker.getUrl().getParameter("timeout"));
        replacedertions.replacedertNull(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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140").addParameter("timeout", "1"));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        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<Invoker<?>> invokers = registryDirectory.list(invocation);
        Invoker<?> aInvoker = invokers.get(0);
        replacedertions.replacedertEquals("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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140"));
        durls.add(SERVICEURL.setHost("10.20.30.141"));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://0.0.0.0?" + ENABLED_KEY + "=false"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        // All service providers can not be disabled through override.
        replacedertions.replacedertEquals(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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140"));
        durls.add(SERVICEURL.setHost("10.20.30.141"));
        registryDirectory.notify(durls);
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://10.20.30.140:9091?" + DISABLED_KEY + "=true"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        replacedertions.replacedertEquals("10.20.30.141", invokers.get(0).getUrl().getHost());
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + CATEGORY_KEY + "=" + CONFIGURATORS_CATEGORY));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers2 = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140"));
        durls.add(SERVICEURL.setHost("10.20.30.141"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers2 = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers2.size());
        replacedertions.replacedertEquals("10.20.30.140", invokers2.get(0).getUrl().getHost());
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("empty://0.0.0.0?" + DISABLED_KEY + "=true&" + CATEGORY_KEY + "=" + CONFIGURATORS_CATEGORY));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers3 = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(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<URL> durls = new ArrayList<URL>();
        durls.add(SERVICEURL.setHost("10.20.30.140").addParameter(ENABLED_KEY, "false"));
        durls.add(SERVICEURL.setHost("10.20.30.141"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(1, invokers.size());
        replacedertions.replacedertEquals("10.20.30.141", invokers.get(0).getUrl().getHost());
        // Enabled by override rule
        durls = new ArrayList<URL>();
        durls.add(URL.valueOf("override://10.20.30.140:9091?" + DISABLED_KEY + "=false"));
        registryDirectory.notify(durls);
        List<Invoker<?>> invokers2 = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(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, // FIX
        "script");
        // BAD
        List<URL> serviceUrls = new ArrayList<URL>();
        // without ROUTER_KEY, the first router should not be created.
        serviceUrls.add(routerurl);
        registryDirectory.notify(serviceUrls);
    // FIXME
    /* List routers = registryDirectory.getRouters();
        replacedertions.replacedertEquals(1 + 1, routers.size());

        serviceUrls.clear();
        serviceUrls.add(routerurl.addParameter(Constants.ROUTER_KEY, Constants.ROUTER_TYPE_CLEAR));
        registryDirectory.notify(serviceUrls);
        routers = registryDirectory.getRouters();
        replacedertions.replacedertEquals(0 + 1, routers.size());*/
    }

    /**
     * Test mock provider distribution
     */
    @Test
    public void testNotify_MockProviderOnly() {
        RegistryDirectory registryDirectory = getRegistryDirectory();
        List<URL> serviceUrls = new ArrayList<URL>();
        serviceUrls.add(SERVICEURL.addParameter("methods", "getXXX1"));
        serviceUrls.add(SERVICEURL2.addParameter("methods", "getXXX1,getXXX2"));
        serviceUrls.add(SERVICEURL.setProtocol(MOCK_PROTOCOL));
        registryDirectory.notify(serviceUrls);
        replacedertions.replacedertTrue(registryDirectory.isAvailable());
        invocation = new RpcInvocation();
        List invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        RpcInvocation mockinvocation = new RpcInvocation();
        mockinvocation.setAttachment(INVOCATION_NEED_MOCK, "true");
        invokers = registryDirectory.list(mockinvocation);
        replacedertions.replacedertEquals(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<URL> serviceUrls = new ArrayList<URL>();
        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<Invoker<DemoService>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(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<URL> serviceUrls = new ArrayList<URL>();
        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<Invoker<DemoService>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(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<URL> serviceUrls = new ArrayList<URL>();
        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<Invoker<DemoService>> invokers = registryDirectory.list(invocation);
        replacedertions.replacedertEquals(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<URL> providers = new ArrayList<>();
        providers.add(provider1);
        providers.add(provider2);
        directory.notify(providers);
        invocation = new RpcInvocation();
        invocation.setMethodName("getXXX");
        List<Invoker<DemoService>> invokers = directory.list(invocation);
        replacedertions.replacedertEquals(2, invokers.size());
        replacedertions.replacedertTrue(invokers.get(0) instanceof MockClusterInvoker);
        replacedertions.replacedertTrue(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);
        replacedertions.replacedertEquals(2, invokers.size());
        replacedertions.replacedertFalse(invokers.get(0) instanceof MockClusterInvoker);
        replacedertions.replacedertFalse(invokers.get(1) instanceof MockClusterInvoker);
    }

    enum Param {

        MORGAN
    }

    private interface DemoService {
    }

    private static clreplaced 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<URL> 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.");
            }
        }
    }
}

14 Source : HttpProtocolTest.java
with Apache License 2.0
from boomblog

@Test
public void testCustomException() {
    HttpServiceImpl server = new HttpServiceImpl();
    ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();
    Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();
    URL url = URL.valueOf("http://127.0.0.1:5342/" + HttpService.clreplaced.getName() + "?version=1.0.0");
    Exporter<HttpService> exporter = protocol.export(proxyFactory.getInvoker(server, HttpService.clreplaced, url));
    Invoker<HttpService> invoker = protocol.refer(HttpService.clreplaced, url);
    HttpService client = proxyFactory.getProxy(invoker);
    try {
        client.customException();
        fail();
    } catch (HttpServiceImpl.MyException expected) {
    }
    invoker.destroy();
    exporter.unexport();
}

14 Source : HttpProtocolTest.java
with Apache License 2.0
from boomblog

@Test
public void testTimeOut() {
    HttpServiceImpl server = new HttpServiceImpl();
    ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();
    Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();
    URL url = URL.valueOf("http://127.0.0.1:5342/" + HttpService.clreplaced.getName() + "?version=1.0.0&timeout=10");
    Exporter<HttpService> exporter = protocol.export(proxyFactory.getInvoker(server, HttpService.clreplaced, url));
    Invoker<HttpService> invoker = protocol.refer(HttpService.clreplaced, url);
    HttpService client = proxyFactory.getProxy(invoker);
    try {
        client.timeOut(6000);
        fail();
    } catch (RpcException expected) {
        replacedertions.replacedertEquals(true, expected.isTimeout());
    } finally {
        invoker.destroy();
        exporter.unexport();
    }
}

14 Source : HttpProtocolTest.java
with Apache License 2.0
from boomblog

@Test
public void testOverload() {
    HttpServiceImpl server = new HttpServiceImpl();
    replacedertions.replacedertFalse(server.isCalled());
    ProxyFactory proxyFactory = ExtensionLoader.getExtensionLoader(ProxyFactory.clreplaced).getAdaptiveExtension();
    Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.clreplaced).getAdaptiveExtension();
    URL url = URL.valueOf("http://127.0.0.1:5342/" + HttpService.clreplaced.getName() + "?version=1.0.0&hessian.overload.method=true&hessian2.request=false");
    Exporter<HttpService> exporter = protocol.export(proxyFactory.getInvoker(server, HttpService.clreplaced, url));
    Invoker<HttpService> invoker = protocol.refer(HttpService.clreplaced, url);
    HttpService client = proxyFactory.getProxy(invoker);
    String result = client.sayHello("haha");
    replacedertions.replacedertEquals("Hello, haha", result);
    result = client.sayHello("haha", 1);
    replacedertions.replacedertEquals("Hello, haha. ", result);
    invoker.destroy();
    exporter.unexport();
}

See More Examples