Java Code Examples for org.apache.dubbo.common.URL

The following examples show how to use org.apache.dubbo.common.URL. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: skywalking   Source File: DubboInterceptorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    dubboInterceptor = new DubboInterceptor();

    PowerMockito.mockStatic(RpcContext.class);

    when(invoker.getUrl()).thenReturn(URL.valueOf("dubbo://127.0.0.1:20880/org.apache.skywalking.apm.test.TestDubboService"));
    when(invocation.getMethodName()).thenReturn("test");
    when(invocation.getParameterTypes()).thenReturn(new Class[] {String.class});
    when(invocation.getArguments()).thenReturn(new Object[] {"abc"});
    PowerMockito.when(RpcContext.getContext()).thenReturn(rpcContext);
    when(rpcContext.isConsumerSide()).thenReturn(true);
    allArguments = new Object[] {
        invoker,
        invocation
    };
    argumentTypes = new Class[] {
        invoker.getClass(),
        invocation.getClass()
    };
    Config.Agent.SERVICE_NAME = "DubboTestCases-APP";
}
 
Example 2
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 6 votes vote down vote up
private Set<String> getServiceNames0(URL url) {
    NacosServiceName serviceName = createServiceName(url);

    final Set<String> serviceNames;

    if (serviceName.isConcrete()) { // is the concrete service name
        serviceNames = new LinkedHashSet<>();
        serviceNames.add(serviceName.toString());
        // Add the legacy service name since 2.7.6
        String legacySubscribedServiceName = getLegacySubscribedServiceName(url);
        if (!serviceName.toString().equals(legacySubscribedServiceName)) {
            //avoid duplicated service names
            serviceNames.add(legacySubscribedServiceName);
        }
    } else {
        serviceNames = filterServiceNames(serviceName);
    }

    return serviceNames;
}
 
Example 3
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 6 votes vote down vote up
private void scheduleServiceNamesLookup(final URL url, final NotifyListener listener) {
    if (scheduledExecutorService == null) {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            Set<String> serviceNames = getAllServiceNames();
            filterData(serviceNames, serviceName -> {
                boolean accepted = false;
                for (String category : ALL_SUPPORTED_CATEGORIES) {
                    String prefix = category + SERVICE_NAME_SEPARATOR;
                    if (serviceName != null && serviceName.startsWith(prefix)) {
                        accepted = true;
                        break;
                    }
                }
                return accepted;
            });
            doSubscribe(url, listener, serviceNames);
        }, LOOKUP_INTERVAL, LOOKUP_INTERVAL, TimeUnit.SECONDS);
    }
}
 
Example 4
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 6 votes vote down vote up
private void subscribeEventListener(String serviceName, final URL url, final NotifyListener listener)
        throws NacosException {
    EventListener eventListener = event -> {
        if (event instanceof NamingEvent) {
            NamingEvent e = (NamingEvent) event;
            List<Instance> instances = e.getInstances();


            if(isServiceNamesWithCompatibleMode(url)){
                /**
                 * Get all instances with corresponding serviceNames to avoid instance overwrite and but with empty instance mentioned
                 * in https://github.com/apache/dubbo/issues/5885 and https://github.com/apache/dubbo/issues/5899
                 */
                NacosInstanceManageUtil.initOrRefreshServiceInstanceList(serviceName, instances);
                instances = NacosInstanceManageUtil.getAllCorrespondingServiceInstanceList(serviceName);
            }

            notifySubscriber(url, listener, instances);
        }
    };
    namingService.subscribe(serviceName, eventListener);
}
 
Example 5
Source Project: dubbo-samples   Source File: DemoServiceIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void verifyConsumer() throws Exception {
    List<String> urls = ZkUtil.getChildren(ZkUtil.toUrlPath("consumers"));
    urls.stream().map(URL::decode).forEach(System.out::println);
    Assert.assertEquals(1, urls.size());
    String url = urls.get(0);

    Assert.assertFalse(url.contains("retries"));
    Assert.assertFalse(url.contains("timeout"));
    Assert.assertFalse(url.contains("owner"));
    Assert.assertFalse(url.contains("actives"));
    Assert.assertTrue(url.contains("application"));
    Assert.assertTrue(url.contains("version"));
    Assert.assertTrue(url.contains("group"));
    Assert.assertTrue(url.contains("release"));
}
 
Example 6
Source Project: dubbo-samples   Source File: UserLoadBalance.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
    for (Invoker t : invokers) {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            String ip = addr.getHostAddress().toString();
            URL u = t.getUrl();
            if (u.getIp().equals(ip)) {
                return t;
            }
        } catch (Exception e) {
            // no op
        }
    }
    return super.doSelect(invokers, url, invocation);
}
 
Example 7
Source Project: skywalking   Source File: DubboInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Format operation name. e.g. org.apache.skywalking.apm.plugin.test.Test.test(String)
 *
 * @return operation name.
 */
private String generateOperationName(URL requestURL, Invocation invocation) {
    StringBuilder operationName = new StringBuilder();
    operationName.append(requestURL.getPath());
    operationName.append("." + invocation.getMethodName() + "(");
    for (Class<?> classes : invocation.getParameterTypes()) {
        operationName.append(classes.getSimpleName() + ",");
    }

    if (invocation.getParameterTypes().length > 0) {
        operationName.delete(operationName.length() - 1, operationName.length());
    }

    operationName.append(")");

    return operationName.toString();
}
 
Example 8
Source Project: dubbo-samples   Source File: DemoServiceIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void verifyConsumer() throws Exception {
    List<String> urls = ZkUtil.getChildren(ZkUtil.toUrlPath("consumers"));
    urls.stream().map(URL::decode).forEach(System.out::println);
    Assert.assertEquals(1, urls.size());
    String url = urls.get(0);

    Assert.assertFalse(url.contains("retries"));
    Assert.assertFalse(url.contains("timeout"));
    Assert.assertFalse(url.contains("owner"));
    Assert.assertFalse(url.contains("actives"));
    Assert.assertTrue(url.contains("application"));
    Assert.assertTrue(url.contains("version"));
    Assert.assertTrue(url.contains("group"));
    Assert.assertTrue(url.contains("release"));
}
 
Example 9
@Override
public final void doSubscribe(URL url, NotifyListener listener) {

	if (isAdminURL(url)) {
		// TODO in future
	}
	else if (isDubboMetadataServiceURL(url)) { // for DubboMetadataService
		subscribeDubboMetadataServiceURLs(url, listener);
		if (from(url).getParameter(CATEGORY_KEY) != null
				&& from(url).getParameter(CATEGORY_KEY).contains(PROVIDER)) {
			// Fix #1259 and #753 Listene meta service change events to remove useless
			// clients
			registerServiceInstancesChangedEventListener(url, listener);
		}

	}
	else { // for general Dubbo Services
		subscribeDubboServiceURLs(url, listener);
	}
}
 
Example 10
Source Project: dubbo-samples   Source File: AnnotationServiceIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void verifyConsumer() throws Exception {
    List<String> urls = ZkUtil.getChildren(ZkUtil.toUrlPath("consumers"));
    urls.stream().map(URL::decode).forEach(System.out::println);
    Assert.assertEquals(1, urls.size());
    String url = urls.get(0);

    Assert.assertFalse(url.contains("retries"));
    Assert.assertFalse(url.contains("timeout"));
    Assert.assertFalse(url.contains("owner"));
    Assert.assertFalse(url.contains("actives"));
    Assert.assertTrue(url.contains("application"));
    Assert.assertTrue(url.contains("version"));
    Assert.assertTrue(url.contains("group"));
    Assert.assertTrue(url.contains("release"));
}
 
Example 11
/**
 * Set web port from {@link ServiceBean#getExportedUrls() exported URLs} if "rest"
 * protocol is present.
 */
private void setServerPort() {
	if (serverPort == null) {
		synchronized (DubboServiceRegistrationNonWebApplicationAutoConfiguration.class) {
			if (serverPort == null) {
				for (List<URL> urls : repository.getAllExportedUrls().values()) {
					urls.stream().filter(
							url -> REST_PROTOCOL.equalsIgnoreCase(url.getProtocol()))
							.findFirst().ifPresent(url -> {
								serverPort = url.getPort();
							});

					// If REST protocol is not present, use any applied port.
					if (serverPort == null) {
						urls.stream().findAny().ifPresent(url -> {
							serverPort = url.getPort();
						});
					}
				}
			}
		}
	}
}
 
Example 12
@Override
public final void doRegister(URL url) {
	if (!shouldRegister(url)) {
		return;
	}
	doRegister0(url);
}
 
Example 13
@Test
public void testInvokeNullApplicationKey() {
    Invoker invoker = mock(Invoker.class);
    Invocation invocation = mock(Invocation.class);
    URL url = URL.valueOf("test://test:111/test?application=");
    when(invoker.getUrl()).thenReturn(url);

    filter.invoke(invoker, invocation);
    verify(invoker).invoke(invocation);

    String application = RpcContext.getContext().getAttachment(DubboUtils.SENTINEL_DUBBO_APPLICATION_KEY);
    assertNull(application);
}
 
Example 14
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<URL> lookup(final URL url) {
    final List<URL> urls = new LinkedList<>();
    execute(namingService -> {
        Set<String> serviceNames = getServiceNames(url, null);
        for (String serviceName : serviceNames) {
            List<Instance> instances = namingService.getAllInstances(serviceName);
            urls.addAll(buildURLs(url, instances));
        }
    });
    return urls;
}
 
Example 15
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doUnregister(final URL url) {
    execute(namingService -> {
        String serviceName = getServiceName(url);
        Instance instance = createInstance(url);
        namingService.deregisterInstance(serviceName, instance.getIp(), instance.getPort());
    });
}
 
Example 16
private ReferenceBean<GenericService> build(ServiceRestMetadata serviceRestMetadata,
		Map<String, Object> dubboTranslatedAttributes) {
	String urlValue = serviceRestMetadata.getUrl();
	URL url = URL.valueOf(urlValue);
	String interfaceName = url.getServiceInterface();
	String version = url.getParameter(VERSION_KEY);
	String group = url.getParameter(GROUP_KEY);

	return build(interfaceName, version, group, dubboTranslatedAttributes);
}
 
Example 17
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Since 2.7.6 the legacy service name will be added to serviceNames
 * to fix bug with https://github.com/apache/dubbo/issues/5442
 *
 * @param url
 * @return
 */
private boolean isServiceNamesWithCompatibleMode(final URL url) {
    if (!isAdminProtocol(url) && createServiceName(url).isConcrete()) {
        return true;
    } else {
        return false;
    }
}
 
Example 18
public AbstractSpringCloudRegistry(URL url, DiscoveryClient discoveryClient,
		DubboServiceMetadataRepository dubboServiceMetadataRepository,
		DubboMetadataServiceProxy dubboMetadataConfigServiceProxy,
		JSONUtils jsonUtils, DubboGenericServiceFactory dubboGenericServiceFactory,
		ConfigurableApplicationContext applicationContext) {
	super(url);
	this.servicesLookupInterval = url
			.getParameter(SERVICES_LOOKUP_INTERVAL_PARAM_NAME, 60L);
	this.discoveryClient = discoveryClient;
	this.repository = dubboServiceMetadataRepository;
	this.dubboMetadataConfigServiceProxy = dubboMetadataConfigServiceProxy;
	this.jsonUtils = jsonUtils;
	this.dubboGenericServiceFactory = dubboGenericServiceFactory;
	this.applicationContext = applicationContext;
}
 
Example 19
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the service names from the specified {@link URL url}
 *
 * @param url      {@link URL}
 * @param listener {@link NotifyListener}
 * @return non-null
 */
private Set<String> getServiceNames(URL url, NotifyListener listener) {
    if (isAdminProtocol(url)) {
        scheduleServiceNamesLookup(url, listener);
        return getServiceNamesForOps(url);
    } else {
        return getServiceNames0(url);
    }
}
 
Example 20
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the legacy subscribed service name for compatible with Dubbo 2.7.3 and below
 *
 * @param url {@link URL}
 * @return non-null
 * @since 2.7.6
 */
private String getLegacySubscribedServiceName(URL url) {
    StringBuilder serviceNameBuilder = new StringBuilder(DEFAULT_CATEGORY);
    appendIfPresent(serviceNameBuilder, url, INTERFACE_KEY);
    appendIfPresent(serviceNameBuilder, url, VERSION_KEY);
    appendIfPresent(serviceNameBuilder, url, GROUP_KEY);
    return serviceNameBuilder.toString();
}
 
Example 21
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated
private List<String> doGetServiceNames(URL url) {
    List<String> categories = getCategories(url);
    List<String> serviceNames = new ArrayList<>(categories.size());
    for (String category : categories) {
        final String serviceName = getServiceName(url, category);
        serviceNames.add(serviceName);
    }
    return serviceNames;
}
 
Example 22
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 5 votes vote down vote up
private List<URL> toUrlWithEmpty(URL consumerURL, Collection<Instance> instances) {
    List<URL> urls = buildURLs(consumerURL, instances);
    if (urls.size() == 0) {
        URL empty = URLBuilder.from(consumerURL)
                .setProtocol(EMPTY_PROTOCOL)
                .addParameter(CATEGORY_KEY, DEFAULT_CATEGORY)
                .build();
        urls.add(empty);
    }
    return urls;
}
 
Example 23
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 5 votes vote down vote up
private List<URL> buildURLs(URL consumerURL, Collection<Instance> instances) {
    List<URL> urls = new LinkedList<>();
    if (instances != null && !instances.isEmpty()) {
        for (Instance instance : instances) {
            URL url = buildURL(instance);
            if (UrlUtils.isMatch(consumerURL, url)) {
                urls.add(url);
            }
        }
    }
    return urls;
}
 
Example 24
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Notify the Healthy {@link Instance instances} to subscriber.
 *
 * @param url       {@link URL}
 * @param listener  {@link NotifyListener}
 * @param instances all {@link Instance instances}
 */
private void notifySubscriber(URL url, NotifyListener listener, Collection<Instance> instances) {
    List<Instance> healthyInstances = new LinkedList<>(instances);
    if (healthyInstances.size() > 0) {
        // Healthy Instances
        filterHealthyInstances(healthyInstances);
    }
    List<URL> urls = toUrlWithEmpty(url, healthyInstances);
    NacosRegistry.this.notify(url, listener, urls);
}
 
Example 25
Source Project: dubbo-registry-nacos   Source File: NacosRegistry.java    License: Apache License 2.0 5 votes vote down vote up
private Instance createInstance(URL url) {
    // Append default category if absent
    String category = url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY);
    URL newURL = url.addParameter(CATEGORY_KEY, category);
    newURL = newURL.addParameter(PROTOCOL_KEY, url.getProtocol());
    newURL = newURL.addParameter(PATH_KEY, url.getPath());
    String ip = url.getHost();
    int port = url.getPort();
    Instance instance = new Instance();
    instance.setIp(ip);
    instance.setPort(port);
    instance.setMetadata(new HashMap<>(newURL.getParameters()));
    return instance;
}
 
Example 26
private DubboMetadataService initDubboMetadataServiceProxy(
		URL dubboMetadataServiceURL) {
	String serviceName = dubboMetadataServiceURL.getParameter(APPLICATION_KEY);
	String version = dubboMetadataServiceURL.getParameter(VERSION_KEY);
	// Initialize DubboMetadataService with right version
	return dubboMetadataConfigServiceProxy.initProxy(serviceName, version);

}
 
Example 27
Source Project: dubbo-samples   Source File: AnnotationServiceIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void verifyProvider() throws Exception {
    List<String> urls = ZkUtil.getChildren(ZkUtil.toUrlPath("providers"));
    urls.stream().map(URL::decode).forEach(System.out::println);
    Assert.assertEquals(1, urls.size());
    String url = urls.get(0);
    Assert.assertTrue(url.contains("retries"));
    Assert.assertTrue(url.contains("owner"));
    Assert.assertTrue(url.contains("timeout"));
    Assert.assertTrue(url.contains("version"));
    Assert.assertTrue(url.contains("group"));
    Assert.assertTrue(url.contains("release"));
    Assert.assertFalse(url.contains("executes"));
}
 
Example 28
/**
 * Create an instance of {@link NamingService} from specified {@link URL connection url}
 *
 * @param connectionURL {@link URL connection url}
 * @return {@link NamingService}
 * @since 2.7.5
 */
public static NamingService createNamingService(URL connectionURL) {
    Properties nacosProperties = buildNacosProperties(connectionURL);
    NamingService namingService;
    try {
        namingService = NacosFactory.createNamingService(nacosProperties);
    } catch (NacosException e) {
        if (logger.isErrorEnabled()) {
            logger.error(e.getErrMsg(), e);
        }
        throw new IllegalStateException(e);
    }
    return namingService;
}
 
Example 29
public void unexportURL(URL url) {
	String key = url.getServiceKey();
	// NPE issue :
	// https://github.com/spring-cloud-incubator/spring-cloud-alibaba/issues/591
	List<URL> urls = allExportedURLs.get(key);
	if (!isEmpty(urls)) {
		urls.remove(url);
		allExportedURLs.addAll(key, urls);
	}
}
 
Example 30
private static void printServiceData() {
    List<String> urls = ZkUtil.getChildren(ZkUtil.toUrlPath("providers"));
    System.out.println("*********************************************************");
    urls.stream().map(URL::decode).forEach(System.out::println);
    System.out.println("not contains 'executes':" + !urls.get(0).contains("executes"));
    System.out.println("contains 'retries':" + urls.get(0).contains("retries"));
    System.out.println("contains 'owner':" + urls.get(0).contains("owner"));
    System.out.println("contains 'timeout(default)':" + urls.get(0).contains("timeout"));
    System.out.println("contains 'version(default)':" + urls.get(0).contains("version"));
    System.out.println("contains 'group(default)':" + urls.get(0).contains("group"));
    System.out.println("contains 'specVersion(default)':" + urls.get(0).contains(RELEASE_KEY));
    System.out.println("*********************************************************");
}